Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use a Paypal and 2Checkout payment integration in Pakistan to take transections from around the globe? (even Paypal is not allowed here)
I live in Pakistan. I just made a Django E-Commerce Website and wanna set a payment integration of Paypal (Paypal is not available for transections) to take money transections from other countries. -
Downloading Python Packages onto Bitnami through AWS Lightsail
I am trying to publish a Django project through AWS LightSail however, I am unable to get the dependencies necessary to run my manage.py file. I try the following command: pip3 install "packagename" Defaulting to user installation because normal site-packages is not writeable I've also tried easy_install "packagenmae" which just stalls as it looks for the package. How can I go about installing my requirements.txt files. Thank you for all your help! -
Websocket immediately disconnects after upgrading Heroku Redis version for Django Channels app
Since Heroku will deprecate the version of Redis my app was using (5.0.12), I upgraded to Redis version 6.2.3. Since then, the websocket immediately triggers the onclose callback in my client. In the logs, I get this error message: 2021-06-21T18:18:20.761857+00:00 app[web.1]: 2021-06-21 18:18:20,761 ERROR [daphne.server] [asyncioreactor.py:290] - Exception inside application: [Errno 104] Connection reset by peer 2021-06-21T18:18:20.761866+00:00 app[web.1]: Traceback (most recent call last): 2021-06-21T18:18:20.761867+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/sessions.py", line 183, in __call__ 2021-06-21T18:18:20.761867+00:00 app[web.1]: return await self.inner(receive, self.send) 2021-06-21T18:18:20.761868+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/middleware.py", line 41, in coroutine_call 2021-06-21T18:18:20.761868+00:00 app[web.1]: await inner_instance(receive, send) 2021-06-21T18:18:20.761868+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/consumer.py", line 59, in __call__ 2021-06-21T18:18:20.761869+00:00 app[web.1]: [receive, self.channel_receive], self.dispatch 2021-06-21T18:18:20.761869+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/utils.py", line 58, in await_many_dispatch 2021-06-21T18:18:20.761870+00:00 app[web.1]: await task 2021-06-21T18:18:20.761870+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/utils.py", line 50, in await_many_dispatch 2021-06-21T18:18:20.761871+00:00 app[web.1]: result = task.result() 2021-06-21T18:18:20.761871+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 435, in receive 2021-06-21T18:18:20.761871+00:00 app[web.1]: real_channel 2021-06-21T18:18:20.761872+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 490, in receive_single 2021-06-21T18:18:20.761872+00:00 app[web.1]: index, channel_key, timeout=self.brpop_timeout 2021-06-21T18:18:20.761872+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 330, in _brpop_with_clean 2021-06-21T18:18:20.761873+00:00 app[web.1]: async with self.connection(index) as connection: 2021-06-21T18:18:20.761873+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 835, in __aenter__ 2021-06-21T18:18:20.761873+00:00 app[web.1]: self.conn = await self.pool.pop() 2021-06-21T18:18:20.761873+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 73, in pop 2021-06-21T18:18:20.761874+00:00 app[web.1]: conns.append(await aioredis.create_redis(**self.host, loop=loop)) 2021-06-21T18:18:20.761886+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/aioredis/commands/__init__.py", line 175, … -
Change Django HyperlinkedModelSerializer ID
I'm learning about Django Rest Framework and trying to get used to it. I'm using a HyperlinkedModelSerializer which, if I understand correctly, allows me to call my models by id like www.example.com/api/1. I was wondering if there was any way to change the id to a custom field, like a username - e.g. www.example.com/api/myusername (similarly to how GitHub API works). models.py from django.db import models class RoomInfo(models.Model): name = models.CharField(max_length=50) dev_name = models.CharField(max_length=50) brief_desc = models.TextField() def __str__(self): return self.name serialisers.py from rest_framework import serializers from .models import RoomInfo class RoomInfoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RoomInfo fields = ['id', 'name', 'dev_name', 'brief_desc'] views.py from django.shortcuts import render from rest_framework import viewsets from rest_framework.generics import RetrieveAPIView from .models import RoomInfo from .serializers import RoomInfoSerializer class RoomApi(viewsets.ModelViewSet): queryset = RoomInfo.objects.all().order_by('name') serializer_class = RoomInfoSerializer -
Unable to register django custom template tags
I want to register 3 custom template tags and show the info they generate in all the pages of my project. I have read the documentation and created the following files: blog_tags.py from django import template from django.db.models import Count from ..models import Post register = template.Library() @register.simple_tag def total_posts(): return Post.published.count() @register.inclusion_tag("blog/post/latest_posts.html") def show_latest_posts(count=5): latest_posts = Post.published.order_by("-publish")[:count] return {"latest_posts": latest_posts} @register.simple_tag def get_most_commented_posts(count=5): return Post.published.annotate(total_comments=Count("comments")).order_by( "-total_comments" )[:count] And my template: base.html {% load static %} {% load blog_tags %} <!DOCTYPE html> <html> <head> <title> {% block title %}{% endblock %} </title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %}{% endblock %} </div> <div id="sidebar"> <h2> My blog</h2> <p> This is my blog. I've written {% total_posts %} posts so far.</p> <h3> Latest posts</h3> {% show_latest_posts 3 %} <h3> Most commented posts</h3> {% get_most_commented_posts as most_commented_posts %} <ul> {% for post in most_commented_posts %} <li> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </li> {% endfor %} </ul> </div> </body> </html> However, the tags are not getting loaded. The page does not open. Instead, I get the following error: Invalid block tag on line 3: 'total_posts'. Did you forget to register or load this … -
Django don't display default value in form field
I have a large django form where most of the options have the same default value. When a user goes to enter the form they have to remove the default value before they can enter their information. I figured I could solve the issue by adding a place holder widgets = { 'form_item': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'OEM'}) } Now when I load the form it still has the default value text entered but if you remove it the place holder text is showen. How do I not display the default value text in a form field -
Django Authentication with pyrebase
I know in Django there is a check authentication by: if request.user.is_authenticated: And there is a decorator like: @login_required I can't use them because I work with realtime database of firebase, so I want to know how to replace them in django while working with pyrebase. -
DRF Create a custom relational data or smth similar?
I have three mudles, one called Events and one called Tasks. Each one have field called deadline. Goal: I need create a section in my Custum User modle called Todis and asection called Overdos where i filter the Events and tasks tha has deadline less than now and put the in the todos and i need to filter the other Tasks and Events object to put them in theOverdows. I know how to filter and all these stuff but I nedd an idea to get that data and set them inside the user modle without create a new datafield to gether them, just like using the relational data -
Django signals how to create register forms for two types of users with groups
I have two types of users all inheriting from the User model. Class 'Teacher' and class 'Student' each with its own registration form and belonging to the respective groups 'teacher' and 'student'. but when I try to register a user 'Teacher', he registers in the group 'prof' and 'etudiant' at the same time and i have a duplicate integrity error. How can i avoid this ? models.py : this is my two models models.py signals.py : signals.py views.py : pofesseur register register view views.py : etudiant register register view apps.py : ready function django admin panel : my two groups concerned groups in admin panel Sorry for my aproximative english -
How to loop through visible form fields but do something when a certain field is met in Django?
Is it possible to stop at a certain form field when you looping through the visible form fields in form's __init__? def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): if visible == "field_name": #<---? #do something -
How can I bypass drf Token Authentication when using firebase for authentication in django?
I need to sign in a user using firebase from my django app.I have done what I think I needed to do but I seem to be missing something.I am using the pyrebase library.I have created a user on firebase and now I need to sign them in. I am posting the email and password on Postman and I get the 'idToken' and 'refreshToken', which means the user gets authenticated on firebase.But this only works when I use the drf Token authentication(DEFAULT AUTH CLASSES) and authorization token of a user previously created on django admin. What am I missing so that I can authenticate the user without the drf token authentication? views.py config = { "apiKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxx", "authDomain": "xxxxx.firebaseapp.com", "databaseURL": "https://xxxxxxxxx-default-rtdb.firebaseio.com", "storageBucket": "xxxxxxxxx.appspot.com", } firebase = pyrebase.initialize_app(config) auth = firebase.auth() class Auth(APIView): def post(self, request, format=None): email = "xxxx@gmail.com" password = "xxxx" user = auth.sign_in_with_email_and_password(email, password) return Response(user) Settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.TokenAuthentication", ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), } -
Can You Add More Details to my Temperature Heat Control App?
Hello i am building a temperature heat monitor using arduino. This is the pseudo code LED1 LED2 LED3 LEDRED Relay1 Relay2 When Settings are changed If device is at 0% Power (0W) LED1, LED2, and LED3 are off If device is at 0 to 39% power (2.5 W) LED 1 is on, LED2 and LED3 are off If device is at 40 to 79% power (5 W) LED 1 and LED2 are on, LED3 is off If device is at 80 to 100% power (7.5 W) LED 1, LED2 and LED3 are on Ton = Tcycle * Intensity / 100% Continuously happen with timing signals If Tsurface >Tmax Relay1, Relay2 are off LEDRED is on Else At t=0+Ton/2 Turn Relay1 off At t=Tcycle-Ton/2 Turn Relay 1 on At t=Tcycle/2 - Ton/2 Turn Relay 2 on At t=Tcycle/2 + Ton/2 Turn Relay 2 off So far this is what i have done from django.contrib import admin from django.urls import path, include from .views import (home,led_off,led_on, increase_temp,decrease_temp) urlpatterns = [ path('', home, name='home'), path('on/', led_on, name='led_on'), path('off/', led_off, name='led_off'), path('inc/', increase_temp, name='inc'), path('dec/', decrease_temp, name="dec"); from view.py from django.conf import settings from pyfirmata import Arduino import warnings # Arduino configuration try: board … -
STATICFILES_DIRS pointing to remote server without being collected
I have a view that is loading a table of elements from an SQL server database to show a list of invoices from system. these invoices files are located in a shared network drive. right now in my development environment I'm able to do a runserver and use my website as I want. The proble comes when I deploy in a IIS Server (production) since I need to now provide these files from the same remote serve and I have the problem that my staticfiles_dirs is not being resolved. Right now I have: STATIC_URL = '/static/' STATICFILES_DIRS = ['//SharedDrive/folder/folder',] and my home.html is doing a {%load static%} where later I reference the path using {% static %} the problem is that this works in my local machine, but not deployed. how can I make it work without having to move this content to my django server? (since the data is over 400gb) Thank you. -
How to test views in Django?
I try to create test to my views in django app, in my setUp method i want to create new object and then pass id of this object to reverse('edit') to test passing an id like I have in my urls, here is code: test_views.py def setUp(self): self.client = Client() self.edit = reverse('edit', args=['id']) self.id = Employee.objects.create( econtact='testContact', eemail='test@tset.pl', ename='testName' ).id urls urlpatterns = [ path('edit/<int:id>', views.edit, name="edit"), ] model class Employee(models.Model): ename = models.CharField(max_length=100) eemail = models.EmailField() econtact = models.CharField(max_length=15) can somone tell me why, after run this test case, my console throw me: django.urls.exceptions.NoReverseMatch: Reverse for 'edit' with arguments '('id',)' not found. 1 pattern(s) tried: ['edit/(?P<id>[0-9]+)$'] thanks for any help! -
API Fetch from HTTPS to HTTPS
I'm building an application with it's frontend build in React and deployed using netlify. Backend build in django and django rest framework and deployed using heroku. Now the issue is when my project is on localhost i.e :8000(backend) and :3000(frontend) the fetch api calls runs fine as both are HTTP. But as soon as i switch to HTTPS my application stopped working. I have byfar tried to resolved all possible CORS issues yet nothing seems working. Can Anyone help me with how to make api calls from a HTTPS server(heroku hosted) to HTTPS client (netlify hosted / or i'll host it on heroku if that helps). -
Invalid block tag: 'endblock'. Did you forget to register or load this tag?
Given is my folder structure. In 'home.html': {% extends 'job_main/base.html' %} {% block title %}Home{% endblock title %} {% block content %} <h1>Home Page</h1> {% endblock content %} In 'base.html': . . . <title>{% block title %}{% endblock title %} | Jobs Portal</title> <body> . . {% block content %} {% endblock content %} </body> -
How to run Cron jobs in app engine using django
I am using django 2.2.0 and I have deployed it on appengine standard environment. I want to run some cron jobs on server. Any idea, how can it be done? -
How to customize 404 page in django?
In my django app I want to show a custom not found 404 page. But after reading the documentation and coding I am still getting the default 404 Not found page. I am working with Django 2.2.8 I also set DEBUG=False Here is my code: in setting.py I have defined: handler404 = 'riesgo.views.views.error_404' Definition in riesgo/views/views.py def error_404(request, exception): return render(request,'404.html') -
What's the best way or tool to work with data and database?
I'm currently working for the accounts department of a hospital. I have been given an assignment outside of my job profile, to create a web application to track and maintain patients' data and prepare bills and reports for subsequent analysis. The data will not be huge in amount but might be enough to overwhelm us sometimes. We have several joint ventures with several hospitals in several cities where we provide our services. So I'm allowed to take my own time to get it done, but it should happen in this year itself. I have plenty of time to learn and practice and develop a well functioning application. I already know Python, Django, HTML, CSS, SQL, JS. I'm going to make the application with Django. My question is that what tools I should use to work with Data and Database? We should be able to enter data, use it to generate few other databases and tables and subsequently generate reports and charts with the options to export them to presentable Excel, PDF or PowerPoint files as the requirement arrives. Can I achieve this using just the ORM of Django, Charts.js and openpyxl or I need to learn something more? Any suggestions? … -
Select database before entering admin site in Django
I have a Django app configured for multiple databases. My issue is I want the admin user to be able to select the what database to use before they get to the admin menu. The reason is there's a sandbox, dev, prod all with the same tables just different data. What I've tried so far was to have a view to set the session to the database they chose and then I tried to get that session in admin.py but I can't use request to get that without and error. Side info(I'm using oracle as my db) s = SessionStore() d = s['database'] #for example it gets back-> dev using = 'f{d}' Any ideas how to get this done/if I'm attacking it the completely wrong way. -
'RedisCache' object has no attribute 'keys'
my keys in cache are like this /notifications/api/v1/faq every key in cache are start with / from django.core.cache import cache print("keys",cache.keys("/*")) when i try to print keys I'm getting this error 'RedisCache' object has no attribute 'keys' -
Django urls.py issue, not sure what to put in 'urlpatterns'
I've been following this tutorial (Django Tutorial Part 3) and I've stumbled across what I'm assuming is a syntax issue between the time this tutorial was written and the new Django releases. My admin page loads just fine. Code Block in Question So in the picture linked, that is the area that I am having trouble with from the tutorial. I think my "mysite/urls.py" file is fine, but the "polls/urls.py" file is where I'm not sure what to put. Below is what mysite/urls.py looks like: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), And here is what my polls/urls.py looks like: from django.urls import path from . import views urlpatterns = [ path(**??? not sure what to put here**, views.index, name='index'), ] -
Why do I get this error when I pip install django and django-rest-framework?
WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) Collecting django Using cached Django-3.2.4-py3-none-any.whl (7.9 MB) Collecting djangorestframework Using cached djangorestframework-3.12.4-py3-none-any.whl (957 kB) Requirement already satisfied: asgiref<4,>=3.3.2 in c:\python39\lib\site-packages (from django) (3.3.4) Requirement already satisfied: sqlparse>=0.2.2 in c:\python39\lib\site-packages (from django) (0.4.1) Requirement already satisfied: pytz in c:\python39\lib\site-packages (from django) (2021.1) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) Installing collected packages: django, djangorestframework ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: 'c:\python39\Scripts\django-admin.py' Consider using the --user option or check the permissions. WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: You are using pip version 21.1.1; however, version 21.1.2 is available. You should consider upgrading via the 'c:\python39\python.exe -m pip install --upgrade pip' command. -
How to read html input \t as a tab instead of as \\t
Okay, so I tried to look for a solution for about one hour and couldn't find anything that works. Let me describe the problem. I have a simple html form where the user uploads a file (.csv) and then also gives a delimiter for that file that I will be using to read it. The problem arises when the user submits a tab delimiter \t. When I try to access it in django delimiter = request.POST['delimiter'] I get a string \\t which just corresponds to a string \t (not a tab). Is there a way to read the input as a tab or somehow convert anything with the escape character to the right form. The only way I figured out would be to do delimiter.replace('\\t', '\t') But then I would have to do this for \n etc. so there has to be a better way. -
Dynamically assign names to variables in Python for loop
In my project, I want to be able to create a list of Querysets, where each Queryset is named after the category of their respective items. I am familiar with dynamically naming variables in the context of system paths/directories (where I use f'{}), but I'm unsure how to utilize any aspect of this in my current problem. I intended for my function to look something like this: def productsfromcategory(categories): productcontext = [] for category in categories: {dynamicallynamedvariable} = Product.objects.prefetch_related("product_image").filter(category=category)[15] print(dynamicallynamedvariable) biglist.append(dynamicallynamedvariable) In this, I meant for dynamicallynamedvariable to be the name of the current category being looped through but I'm unsure as to how to implement this. Any advice on how to tackle this problem would be much appreciated.