Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pusher - autenticated users not receiving events from private channels
Let's say I have a vue client trying to receive an event from a private channel using pusher services. This client autenticates using pusher auth secuence: Here are the docs: https://pusher.com/docs/channels/server_api/authenticating-users/ Seems I need to provide an endpoint on my server in order to autenticate the user. So, as the docs says, since my server is in a different domain to the front-end app, I need to use CORS or JSONP, I choose JSONP. My server (backend) is made in Django using django-rest-framework and it provides an endpoint that is responsible to process the socket_id, the channel_name and the callback that the pusher-js (which is a pusher frontend library) generates. Something alike to a javascript code is sent to the frontend, so the response needs to be content-type:application/javascript. In order to test the event, I made a simple python script which I will later integrate to my bussiness logic. This script is the responsible to trigger the event. The problem: Well, the main problem is the event never arrives. I looked up into the web-console (frontend) to check the correct function of the requests. The ws protocol requests responds with status 101 and the endpoint /auth/pusher with status 200. So … -
What are the options to deploy my e-commerce Django project?
I am currently learning Django and I am planning to deploy my project to sell a product. What options do I have to deploy? -
Measure Time spent on a view in django
I have a django view that prompts the user to enter something into an input. I want to measure the time that the user took to submit the form. How is this possible? I've seen related problems like Printing Time spent on a view in Django but it doesn't seem to solve my issue, because I do not want to measure the time taken on a function call. Alex -
Remove username field from Django Allauth
I'm trying to remove the username field after overriding the Django Allauth package. I tried the following suggestions: Set ACCOUNT_USER_MODEL_USERNAME_FIELD = None and some more inside settings.py as following: ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_PASSWORD_MIN_LENGTH = 8 Overriding User Model in venv\Lib\site-packages\django\contrib\auth\models.py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' class Meta(AbstractUser.Meta): swappable = "AUTH_USER_MODEL" both failed, as when I run py manage.py createsuperuser, I still got the username field popping up: Username (leave blank to use 'admin'): How can I safely remove the username field while overriding Django Allauth? Could you show me a way to solve this? Thank you! -
Real Time Flash Messages in Django with Django Channels
i want to be implement a real time flash message feature that immediately sends flash messages through django-channels websocket connection to the webpage without the need to pass the message through the normal request method. An Example would be displaying a flash message as soon as notification is received by the channels websocket connection. is this possible? if yes how can it be done. else what other alternatives can be used to achieve the real time flash message functionality (it doesn't have to be django channels) -
I need an logic implementation of following simple scenario
Queue implementation of request I need to run multiple thread in python. My Scenario is: Users send requests on an API. Every user has a Account. Every Account has some request tags like ['1','2','3'] What I need is to run different python background Threads for different Account. Example : user 1 with account 1 -> send request then create new thread that handle request for Account 1 user 2 with account 1 -> send request then if account 1 thread is already running its push in the Account 1 Queue user 3 with account 2 -> send request then if **account 2 ** thread is already running its push in the **Account 2 ** Queue else create new Thread Important Point I also need to keep track of update push in Account Queue: Example: for request in account1Q: #do something if request.last(): if check_for_update_in_queue: reRun Thread else: kill Thread() -
NOT NULL constraint failed: home_contact.name
I Keep Reciving This Error Even All The Attribute Name Is Same From Contact.html and view.py untegrityError at /contact NOT NULL constraint failed: home_contact.name Also Done migration and migrate still no solution views.py from django.shortcuts import render,HttpResponse from datetime import datetime from home.models import Contact # Create your views here. def index(request): # return HttpResponse("This Is Homepage") # To Render String Use HttpResponse context = { 'variable' : "This IS SEND 121212", 'v2' : "V@" } return render(request,'index.html',context) # Render Menas It Load The index.html file and send the data of context def about(request): # return HttpResponse("This Is About") # To Render String Use HttpResponse return render(request,'about.html') # Render Menas It Load The index.html file and send the data of context def services(request): # return HttpResponse("This Is Services") # To Render String Use HttpResponse return render(request,'services.html') # Render Menas It Load The index.html file and send the data of context def contact(request): # return HttpResponse("This Is Contact") # To Render String Use HttpResponse if request.method == "POST": name = request.POST.get('nme') print(name) # email = request.POST.get('email') # print(email) # pwd = request.POST.get('pwd') # print(pwd) c1 = Contact(name=name) # contact = Contact(name=name,email=email,pwd=pwd,date=datetime.today()) c1.save() return render(request,'contact.html') # Render Menas It Load The index.html … -
no such column: accounts_articles.Author_id,
I'm trying to get the author of the article from CustomUser Model using foreignKey but apparently something is missing and I don't know what it is class CustomUser(AbstractUser): email = models.EmailField(unique=True, blank=False,) zip_code = models.CharField(blank=True, max_length=5) username = models.CharField(unique=True, blank=False, max_length=30) class Articles(models.Model): title = models.CharField(max_length=20) content = models.TextField() slug = models.SlugField(blank=True) published = models.BooleanField(default=False) created_at = models.DateField(auto_now_add=True) Author = models.ForeignKey(CustomUser, on_delete=SET_NULL, null=True)# the problem is here -
UUID as primary key throws an overflow error despite trying to use taggit
I am trying to use UUID as a primary key on a model and it throws an Overflow error when using redirect. I looked online for similar problems as I assume it should be quite frequent that people want to do that. I came accross: https://github.com/jazzband/django-taggit/issues/679 So I installed dajngo-taggit and I tried to add the snippet on this link in my code but the problem remains. Below is my current code using the snippet: [models.py] from django.db import models from taggit.managers import TaggableManager from taggit.models import GenericUUIDTaggedItemBase, TaggedItemBase class Person(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) # ... class UUIDTaggedItem(GenericUUIDTaggedItemBase, TaggedItemBase): # If you only inherit GenericUUIDTaggedItemBase, you need to define # a tag field. e.g. # tag = models.ForeignKey(Tag, related_name="uuid_tagged_items", on_delete=models.CASCADE) class Meta: verbose_name = _("Tag") verbose_name_plural = _("Tags") class Car(models.Model): person = models.ForeignKey(Person, null=True, on_delete=models.SET_NULL) brand = models.CharField(max_length=50) colour = models.CharField(max_length=50) # ... [urls.py] # ... urlpatterns = [ # ... path("<uuid:pk>/car/<int:id>/", CarDetail.as_view(), name="car_detail"), # ... ] And the error I get is: OverflowError at /en/person/c8c91051-5773-4c69-9587-92b468186db7/car/1/ Python int too large to convert to SQLite INTEGER Would you have any ideas of what I could try to fix it? I have been on … -
Unable to create account --- Djoser, Django_Rest_Framework
My Custom Model My Custom Serializer My Custom Manager My Error -
Django Error: Reverse for 'signup' not found. 'signup' is not a valid view function or pattern name
When I run the code it gives the message: django.urls.exceptions.NoReverseMatch: Reverse for 'signup' not found. 'signup' is not a valid view function or pattern name. user/home.html enter image description here user/views.py enter image description here user/urls.py enter image description here main/urls.py enter image description here -
Django creating Abstract user models
I am trying to create a user models for me django project where doctor and patient can both signup using same form but will update their profile with different fields, but i got error saying there was clashes even after deleting the previous migrations and SQLite database on my project. here is the error message : ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'users.User.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'users.User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'users.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'users.User.user_permissions'. users.User.groups: (fields.E304) Reverse accessor for 'users.User.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'users.User.groups' or 'auth.User.groups'. users.User.user_permissions: (fields.E304) Reverse accessor for 'users.User.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'users.User.user_permissions' or 'auth.User.user_permissions'. here is the code for the user and profile update` DEPARTMENTS=[ ('Anesthesiology','Anesthesiology'), ('Pharmacy','Pharmacy'), ('Radiology', 'Radiology'), ('Gastroenterology', 'Gastroenterology'), ('Orthopaedics', 'Orthopaedics'), ('Community Medicine', 'Community Medicine'), ('Internal Medicine', 'Internal Medicine'), ('Laboratory', 'Laboratory'), ('Nursing', 'Nursing'), ('Medical Records', 'Medical Records'), ('Cardiology', 'Cardiology'), ('Pediatrics', 'Pediatrics'), … -
How to host api documentation(abc.com/docs) on docs.abc.com on django+gunicorn+nginx setup
We have Django rest API deployed using Nginx through reverse proxy. Sample config: location / { proxy_set_header Host $host; include proxy_params; proxy_pass http://unix:/run/websitebackend.sock; } listen 443 ssl http2; # managed by Certbot ssl_certificate /etc/ssl/private/chain.crt; ssl_certificate_key /etc/ssl/private/private.key; } Now our API documentation(genereted using redoc) is on api.abc.com/docs, which we want to server on subdomain docs.abc.com. How can I achieve this? Thanks in advance! -
Best practice to store the order of table rows?
I have table which has columns like these class AgeAndName(models.Model): name = m.CharField(max_length=20) age = m.IntegerField name age ---- -- John 22 Hitch 38 Heiku 25 Taro 36 Cho 40 Now I want to allow the user to sort as he like, and keep. then I think of two ways. 1.make new column and keep order's class AgeAndName(models.Model): name = m.CharField(max_length=20) age = m.IntegerField order = m.IntegerField name age order ---- -- ----- John 22 1 Hitch 38 5 Heiku 25 3 Taro 36 4 Cho 40 2 2.make one property for model and keep them. class AgeAndName(models.Model): @classmember??? ( I am not sure I have this kind of thing) order = (0,4,2,3,1) name = m.CharField(max_length=20) age = m.IntegerField Which one is the best practice for django?? Or is there any other good way ? -
How can i solve my licensing problem using Django
How can we create the best software licensing algorithm to avoid violation using Django. Users should not be able to use the software by changing the date of the system once the license is expired. -
Enable pdf comment via Python?
i want to enable comment in bunch of pdf . is there any chance to doing this in python???like the following image import os import winerror from win32com.client.dynamic import Dispatch, ERRORS_BAD_CONTEXT ERRORS_BAD_CONTEXT.append(winerror.E_NOTIMPL) my_dir = r"C:\cpsmails" my_pdf = "one.pdf" os.chdir(my_dir) src = os.path.abspath(my_pdf) try: AvDoc = Dispatch("AcroExch.AVDoc") if AvDoc.Open(src, ""): pdDoc = AvDoc.GetPDDoc() jsObject = pdDoc.GetJSObject() jsObject.SaveAs() except Exception as e: print(str(e)) finally: AvDoc.Close(True) jsObject = None pdDoc = None AvDoc = None -
Slice the string from Django template tag's variable
Is it possible to slice the string from Django template tag's variable? Let's say some_variable contain "abcde" I want it to be sliced to be "abc" On Django's template, I tried like this. {{some_variable[:-2]}} It does not work. If it's possible to slice words from Django template tag's variable, please advise me how to do it. -
Django Rest Framework how to serialize a many to many relational Model?
I am doing a project in Django Rest Framework. Now I am trying to serialize many to many relations, but I don't know how this works. Here is my models' code: Model for files def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class Document(models.Model): name = models.CharField(max_length=250, blank=True, null=True) document = models.FileField(upload_to=user_directory_path) def __str__(self): return self.name Model for Expenses and loans class Expenses(models.Model): name = models.CharField(max_length=250, blank=True, null=True) amount = models.DecimalField(default=0.0, decimal_places=2, max_digits=10) date = models.DateField(auto_now=True) additional_files = models.ManyToManyField(Document, blank=True, related_name="expenses") # Upload multiple files def __str__(self): return self.name class Loans(models.Model): name = models.CharField(max_length=250, blank=True, null=True) amount = models.DecimalField(default=0.0, decimal_places=2, max_digits=10) loan_from = models.CharField(max_length=250, blank=True, null=True) date = models.DateField(auto_now=True) additional_files = models.ManyToManyField(Document, blank=True, related_name="loans") # Upload multiple files def __str__(self): return self.name My question: Just want to know how to serialize these additional_files in the Expenses and Loans. It will be much better if give resources and explanations of how that works. -
Delete one of multiple Heroku remote branches (Heroku CLI)
Currently I develop a Django application, which I've deployed on Heroku. intention I just wanted to switch from master to main. Before I've unfortunately done: git push heroku master That's why I have two different remote branches now (heroku/main and heroku/master): (HEAD -> main, heroku/master, heroku/main) What I've tried To delete the heroku/master I've tried the following (which didn't work): git branch -d heroku/master git branch -d master git branch -d heroku:master heroku git branch -d heroku/master git remote rm heroku/master What worked (kind of) Finally I've removed the complete remote using git remote rm heroku Now I don't see the remote on the command line anymore ((HEAD -> main)) But interestingly the app is still available online and in the heroku dashboard. (Now I am going to figure out how to work with the heroku remote again in the command line) But I wonder Isn't there a way to delete the above mentioned heroku/master branch (which is actually just a duplicate of the heroku/main) without removing the complete remote? -
Need to return the User ID along with the access and refresh token while fetching the JWT access token in django rest framework
viewset class CustomRenderer(JSONRenderer): def render(self, data, accepted_media_type=None, renderer_context=None): status_code = renderer_context['response'].status_code response = { "status": "success", "code": status_code, "data": data, "message": None, "user_id": models.Default_User.objects.all(self.id) } if not str(status_code).startswith('2'): response["status"] = "error" response["data"] = None try: response["message"] = data["detail"] except KeyError: response["data"] = data return super(CustomRenderer, self).render(response, accepted_media_type, renderer_context) settings REST_FRAMEWORK= { 'DEFAULT_PERMISSION_CLASS':'rest_framework.permissions.IsAuthenticated', 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=7), 'REFRESH_TOKEN_LIFETIME': timedelta(days=30), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } I need the user id in the response to be fetched while getting the JWT access token call. Currently i couldn't able to fetch the user id along with the responses i coded above. Is there any way to fetch it or else is there any way to decode the token and take the user id and display while getting the token in the code itself. Kindy help me as i am new to this authentication. -
Ubuntu + Django + SQLite - attempt to write a readonly database
I'm hosting my Django project with Apache on a Ubuntu 20.04 server with the standard SQLite database. It works but the database seems to be read-only. When we write to the database we get an OperationalError: attempt to write a readonly database I have tried to change the permissions according to the guide below https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-16-04 I've changed the permissions of the sqlite file to 664 and gave user www-data ownership of the file and the parent folder. Yet I'm still getting the same error. Any ideas what else could be causing this problem? -
'RelatedManager' object has no attribute '_meta'
So I have a view that distuingishs between two different forms by checking the submit buttons name. The first case UserProfileForm works just great but the BankForm case returns the error 'RelatedManager' object has no attribute '_meta' Why's that? # views.py def render_dashboard_profile(request): # Get the user object user = request.user # Get the bank object bank_obj = Bank.objects.get(account_holder=user) # Create a pre-populated form instance for both models user_profile_form = UserProfileForm(instance=user.userprofile) bank_form = BankForm(instance=user.userprofile) # Create Context context = { 'user_profile_form': user_profile_form, 'bank_form': bank_form, 'bank_obj': bank_obj } if request.method == 'POST': form = {} # Determine which form was submitted if 'profile-submit' in request.POST: form = UserProfileForm(request.POST, instance=user.userprofile) # that one works elif 'bank-submit' in request.POST: form = BankForm(request.POST, instance=user.account_holder) # breaks here if form.is_valid(): form.save() return render(request, 'dashboard/dashboard_profile.html', context) else: return render(request, 'dashboard/dashboard_profile.html', context) # forms.py class BankForm(ModelForm): """ A form to change the bank data of a user """ class Meta: model = Bank fields = ['name', 'bic', 'iban'] # models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) surname = models.CharField(max_length=30) .. class Bank(models.Model): """ Stores data about the bank account of a user/investor """ account_holder = models.ForeignKey(User, on_delete=models.CASCADE, related_name='account_holder') name = models.CharField(max_length=30) bic = models.CharField(max_length=10) iban = models.CharField(max_length=30) -
Host Django on VPS Server main IP address not in Host Port
I am trying to deploy a application using Django on VPS server. It is working perfectly. All things are okay. But Here suppose this is my VPS server http://23.234.207.249 but if I click this link it is showing me a apache default page. but if I hit this http://23.234.207.249:8000 after adding port :8000 it is working and showing my application. But I want to show the same in my main IP Address. Which procedure to follow? Here I am deploying with Docker, this is my docker compose file version: '3' services: app: build: . volumes: - .:/django ports: - 8000:8000 image: app:django container_name: django_containe command: python manage.py runserver 0.0.0.0:8000 depends_on: - db db: image: mysql:5.7 environment: MYSQL_DATABASE: 'gascommerce' MYSQL_ALLOW_EMPTY_PASSWORD: 'true' volumes: - ./data/mysql/dbb:/var/lib/mysql -
hey plz help me in my project i am stuck ---->>>> please
hello I am a beginner in django what i want to do is take input through voice in python and simultaneously output it on webpage using django now 1] problem is when i take input using get mehtod it start taking input through voice but without rendering the web page Eg- when start the server it start taking input without loading the page,when all the input are taken then it loads the page and shows us the value 2] when i take input using post mehtod it take input properly as i want but it does not show the output on web page simultaneously, i have seen javasricpt speech to text code snippet were we give input though voice and it shows us on webpage simultaenously but i dont want to use javascript is there any other way please help me my post method code def sample(request): bet = {} if request.method =='POST': TextToSpeech("say your username",230) username=speechtotext(5,'username') TextToSpeech("say your username",230) password=speechtotext(5,'email') print(password) bet.update({'username':username}) bet.update({'eamil':email}) return render(request,'sample.html',context=bet) below is my html code {% extends 'layout.html' %} {% load static %} {% block title %} Welcome !-COMPOSE-! {% endblock %} {% block lay %} <body onclick = "WhichButton(event)"> <div align="center" class="p-5 m-3"> … -
How to test "POST" method via url with dynamic argument (Django Rest Framework)?
I need to test some API endpoints in my app I.e. I want to create "Bookmark" using Django Rest Framework using "toggle_bookmark/<exercise_id>" url How can I substitute a value for <exercise_id> in my test_boomark.py file? This is my urls.py file: from django.urls import path, include from rest_framework import routers from api import bookmark, daily_exercise, like, upload from api.exercise import ExerciseViewSet, exercise_user_info, toggle_done from api.plan import PlanViewSet from api.practice_session import PracticeSessionViewSet from api.practice_session_exercise import PracticeSessionExerciseViewSet app_name = "api" router = routers.DefaultRouter() router.register(r"exercise", ExerciseViewSet) router.register(r"plan", PlanViewSet) router.register(r"practice-session", PracticeSessionViewSet) router.register(r"practice-session-exercise", PracticeSessionExerciseViewSet) urlpatterns = [ path("", include(router.urls)), path("upload-file", upload.upload_file, name="upload_file"), path("exercise_user_info/<user_plan_uid>/<practice_session_exercise_uid>", exercise_user_info, name="get_exercise_user_info"), path("toggle_bookmark/<exercise_id>", bookmark.toggle_bookmark, name="toggle_bookmark"), path("toggle_daily_exercise/<exercise_id>", daily_exercise.toggle_daily_exercise, name="toggle_daily_exercise"), path("toggle_like/<exercise_id>", like.toggle_like, name="toggle_like"), path("toggle_done/<user_plan_uid>/<practice_session_exercise_uid>", toggle_done, name="toggle_done"), ] Here is my test_bookmark.py file: import json from django.urls import reverse from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase, APIClient from rest_framework import status from core.models import User, Bookmark class BookmarkTests(APITestCase): def test_bookmark_api(self): """ Bookmark API Test """ user = User.objects.create_user(email='test@gmail.com', name='lauren') client = APIClient() client.force_authenticate(user=user) client.post('toggle_bookmark/<exercise_id>',{"exercise_id":"123123","exercise":"exerciese1"},format="json") assert response.status_code == 201