Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't install django through pip
Im trying to install django on an venv using python (3.9) on vsc. I already had a hard time activating the venv and now i can't seem to be able to install django. when i use pip install django this shows up : (env) PS C:\CODE_PROJECTS\django_test> pip install Django Fatal error in launcher: Unable to create process using '"C:\Users\camil\CODE_PROJECTS\django_test\env\Scripts\python.exe" "C:\CODE_PROJECTS\django_test\env\Scripts\pip3.9.exe" install Django': O sistema nÒo pode encontrar o arquivo especificado. I have tried pip3, pip3.9 also and same result What should I do? -
"GET /css/styles.css HTTP/1.1" 404 2578
I'm new to Django and this is my first time using it. I keep getting the error "GET /css/styles.css HTTP/1.1" 404 2578" I've already looked through other solutions posted and none have helped. I've followed the documentation exactly as laid out by Django's documentation, but it still isn't working. Relevant settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIR = [ os.path.join(str(BASE_DIR.joinpath('static')),) ] index.html {% load static %} <html lang="en"><head> ... <link href="{% static 'css/styles.css' %}" rel="stylesheet"/> </head>... Relevant urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('App1.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Here is an image of my current directory -
django celery [celery.worker] DEBUG: Timer wake-up! Next ETA when run a scrapy process
I am running a simple spider in Django using celery, in the task.py file. Code that run my spider is below: file task.py: @shared_task(bind=True) def scrape_amazon_products(self,products_urls,current_user,task_id,current_site): process = CrawlerProcess() process.crawl(my_spider) #Here the name of the spider process.start() process.stop() It works great, spider starts and finished but: Problem: The celery never stops and giving these logs continuously mentioned below: [2022-03-12 19:44:57,512: WARNING/MainProcess] 2022-03-12 19:44:57 [celery.worker] DEBUG: Timer wake-up! Next ETA 1.0 secs. [2022-03-12 19:44:58,535: DEBUG/MainProcess] Timer wake-up! Next ETA 0.9690000000118744 secs. [2022-03-12 19:44:58,536: WARNING/MainProcess] 2022-03-12 19:44:58 [celery.worker] DEBUG: Timer wake-up! Next ETA 0.9690000000118744 secs. [2022-03-12 19:44:59,527: DEBUG/MainProcess] Timer wake-up! Next ETA 1.0 secs. [2022-03-12 19:44:59,528: WARNING/MainProcess] 2022-03-12 19:44:59 [celery.worker] DEBUG: Timer wake-up! Next ETA 1.0 secs. [2022-03-12 19:45:00,543: DEBUG/MainProcess] Timer wake-up! Next ETA 0.9839999999967404 secs. [2022-03-12 19:45:00,544: WARNING/MainProcess] 2022-03-12 19:45:00 [celery.worker] DEBUG: Timer wake-up! Next ETA 0.9839999999967404 secs. [2022-03-12 19:45:01,546: DEBUG/MainProcess] Timer wake-up! Next ETA 0.062000000005355105 secs. [2022-03-12 19:45:01,547: WARNING/MainProcess] 2022-03-12 19:45:01 [celery.worker] DEBUG: Timer wake-up! Next ETA 0.062000000005355105 secs. [2022-03-12 19:45:01,619: DEBUG/MainProcess] Timer wake-up! Next ETA 1.0 secs. [2022-03-12 19:45:01,620: WARNING/MainProcess] 2022-03-12 19:45:01 [celery.worker] DEBUG: Timer wake-up! Next ETA 1.0 secs. [2022-03-12 19:45:02,627: DEBUG/MainProcess] Timer wake-up! Next ETA 0.9219999999913853 secs. [2022-03-12 19:45:02,628: WARNING/MainProcess] 2022-03-12 19:45:02 [celery.worker] DEBUG: Timer wake-up! Next … -
Django rest framwwork and MVC architecture
In the Django framework and MVC architecture, the Django Rest Framework serializer and validation of inputs(query_param, body and etc) is part of the controller layer or presentation layer? In this response/request scenario What are the layers related to MVC? request <> django-middleware <> django-view <> DRF serializer <> personal-function <> model -
How to render multiselect field
I have a bootstrap theme that I'm trying to use to style a multi checkbox from a ModelForm but I can't get this to render correctly when applying the attrs() Model class ProjectForm(ModelForm): class Meta: model = Project fields = ('name','website','description','category','type','platform','token_total_supply', 'stage','blockchain','twitter_handle','contract_address') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control wd-xl-250'}), 'website': forms.URLInput(attrs={'class': 'form-control wd-xl-250'}), 'description': forms.Textarea(attrs={'class': 'form-control wd-xl-250'}), 'blockchain': forms.CheckboxSelectMultiple(), } HTML Template <div class="parsley-checkbox wd-250 mg-b-0" id="cbWrapper2"> <label class="ckbox mg-b-5-f"><input data-parsley-class-handler="#cbWrapper2" data-parsley-errors-container="#cbErrorContainer2" data-parsley-mincheck="2" name="browser[]" required="" type="checkbox" value="1"><span>Polygon</span></label> <label class="ckbox mg-b-5-f"><input name="browser[]" type="checkbox" value="2"><span>Ethereum</span></label> <label class="ckbox mg-b-5-f"><input name="browser[]" type="checkbox" value="3"><span>Solana</span></label> <label class="ckbox"><input name="browser[]" type="checkbox" value="4"><span>Binance</span></label> </div><!-- parsley-checkbox --> Using Django Form <div class="parsley-checkbox wd-250 mg-b-0" id="cbWrapper2"> {{ form.blockchain }} </div> I've tried adding 'blockchain': forms.CheckboxSelectMultiple(attrs={'class': 'ckbox mg-b-5-f'}), But it doesn't work, and i'm not sure why. It should be like this: But I get What am I doing wrong here? -
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.