Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DateField - how to setup model and form
How should I set-up the model and form to be able to enter the date to the form with different input formats and, at the same time, save to database the date in python's datetime format? I was trying to find an answer here and in Django documentation, but I didn't manage to find out, what is proper way of doing this. I have a DateField field in my model. Date is to be provided by user via form. I want that the form accepts several input formats, especially European-style, but save to database date in python's format. (For the moment, I'm trying to set-up just one format, when I finally understand how does it work, I want to enlarge the allowed input formats list.) My model: class Foo(models.Model): date = models.DateField(null=True) My form: class FooForm(forms.Form): date = forms.DateField(required=False, widget=forms.DateInput(format='%d/%m/%Y', attrs={'placeholder': 'yyyy-mm-dd'})) My settings DATE_INPUT_FORMATS = ['%d/%m/%Y'] Placeholder in the form is just for me to remember the format, in which Django accepts the date. All other format - included the formats specified in settings.py and form's widget, result in non-validation of the form. With the code like above, it seems that Django is doing the opposite of what I … -
Django URLs doesn't support to have any patters. How to solve this error
My main folder URL has the following code: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('quotes.urls')), ] And my website folder has this code: from django.urls import path from . import views urlpatters = [ path('',views.home, name="home") ] This is the error I am getting: C:\stock\stocks\quotes\urls.py changed, reloading. Watching for file changes with StatReloader Performing system checks... return check_resolver(resolver) File "C:\stock\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\stock\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check messages.extend(check_resolver(pattern)) File "C:\stock\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\stock\venv\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\stock\venv\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\stock\venv\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'quotes.urls' from 'C:\stock\stocks\quotes\urls.py'>' does not appear to have any patterns in it. If yo u see valid patterns in the file then the issue is probably caused by a circular import. Please let me know what do I need to change -
Django Decorator For Try Except
I am wondering if there is some existing (or one I could write) decorator that does a try except on the function, and if it fails, returns a 404/403/500 (not sure which is supposed to be shown) page. Thanks! -
Django Twilio - Not all unsubscribers are being captured in my app - why?
I've implemented a function to capture unsubscribers. However, only some of the unsubscribers are captured by my app. For example I am getting multiple 21610 - Attempt to send to unsubscribed recipient for customers that have replied stop and were not captured in my app as unsubscribers. Here is the part of phone number sms webhook that checks if user wants to unsubscribe: if umessage_body == 'STOP' or umessage_body == 'STOPALL' or umessage_body == 'UNSUBSCRIBE' or umessage_body == 'CANCEL' or umessage_body == 'END' or umessage_body == 'QUIT': place_num = request.POST['To'] Unsubscriber.objects.update_or_create( unsubscriber_number = request.POST['From'], place = place ) resp = MessagingResponse() return HttpResponse(str(resp)) For context my app sends text messages to thousands of users at once, maybe it is something about my webhook being overwhelmed. Any idea what is causing this, and how to ensure all unsubscribers are being captured in my app. -
Sending upgrade progress from S3 Boto3 to Angular Frontend
I am using Django to upload files to AWS S3 using Boto3. I have been successful in doing this, but I wonder how I can get the AWS S3 upload progress, provided by Boto3 via a callback, sent over to the frontend. I am using the code similar to the following to upload using Boto3: s3.upload_file("filename.txt", AWS_BUCKET_NAME, "key", Callback=ProgressPercentage("filename.txt")) And in turn using the callback example provided by the Boto3 docs: import os import sys import threading class ProgressPercentage(object): def __init__(self, filename): self._filename = filename self._size = float(os.path.getsize(filename)) self._seen_so_far = 0 self._lock = threading.Lock() def __call__(self, bytes_amount): # To simplify, assume this is hooked up to a single filename with self._lock: self._seen_so_far += bytes_amount percentage = (self._seen_so_far / self._size) * 100 sys.stdout.write( "\r%s %s / %s (%.2f%%)" % ( self._filename, self._seen_so_far, self._size, percentage)) sys.stdout.flush() But instead of passing the output to sys.stdout.write I want to somehow get it over to the frontend (specifically, to an Angular client). Any ideas on how I do this? If I do print the output of the above callback I get the following in the Django console: filename.txt 262144 / 3457480.0 (7.58%) filename.txt 524288 / 3457480.0 (15.16%) filename.txt 786432 / 3457480.0 (22.75%) ... This output … -
Django changed files not synchronizing changes on ubuntu nginx gunicorn
My django project working fine which is deployed on ubuntu server with nginx, Gunicorn. But when I make changes in Template files, Views, Forms, Models and upload using Filezilla, No changes synchronize/ Or project is not showing made changes by me. Can scholars and seniors help in this please. -
I really don’t understand this allautho. Is really frustrating me
Before now I was just using the regular generic views LoginView, LogOutView and I redirected the default redirection to account/profile to a url of my choice. More interesting is that the next works, if you want to do something, it will redirect you to where you wanted to go before you where asked to login. But is not the same with allauth, it doesn’t redirect you to the place you wanted to go before you where asked to login and the worst is it redirects you to account/profile. I have done everything I can and googled for all the solutions that I can but I can’t get any help. I tried putting LOGIN_REDIRECT_URL in the settings.py but it gave error and said LOGIN not defined! Please guru in the house, help me. -
How do I make my button increment the value of my iteration value and show the effect on the site? (django)
views.py def create(request): choicenumber = 3 submitbutton = request.POST.get('submit', False) choicebutton = request.POST.get('add_choice', False) if choicebutton: choicenumber += 1 render(request, 'polls/create.html', { 'questionfields': Question.__dict__, 'choicenumber': choicenumber, }) if submitbutton: new_question = Question.objects.create(question_text=request.POST.get('question_text', ''), pub_date=timezone.now()) if new_question.question_text == '': context = { 'questionfields': Question.__dict__, 'error_message': "No poll question entered.", 'choicenumber': choicenumber, } del new_question return render(request, 'polls/create.html', context) else: for i in range(choicenumber + 1): choice = request.POST.get(('choice' + str(i)), '') if choice: choice_obj = Choice.objects.create(question=new_question, choice_text=choice) new_question.choice_set.add(choice_obj) new_question.save() return HttpResponseRedirect(reverse('polls:detail', args=(new_question.id,))) else: return render(request, 'polls/create.html', context) create.html {% extends "polls/base.html" %} {% block title %}Create a Poll{% endblock title %} {% block header %}Create:{% endblock header %} {% load custom_tags %} {% block content %} {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:create' %}" method="post"> {% csrf_token %} {% for field in questionfields %} {% if field == 'question_text' %} <label for="{{ field }}">{{ field|capfirst|replace }}:</label> <input type="text" name="{{ field }}" id="{{ field }}"> <br> {% endif %} {% endfor %} <br> {% for choice in choicenumber|rangeof %} <br> <label for="choice{{ forloop.counter }}">Choice {{ forloop.counter }}:</label> <input type="text" name="choice{{ forloop.counter }}" id="choice{{ forloop.counter }}"> <br> {% endfor %} <br> <input type="button" name="add_choice" value="Add choice"> <br> <br> … -
Django getting SMTP Server URL as URL in the password reset email
I made a Django application with custom users. I followed the docs to create my password reset pages and forms. I found this similar question and tweaked my configuration to use the right domain name. My SITE_ID is set to 1, and I'm sure the Site with pk=1 is configured to be my domain. When I try to get a password reset email, the subject contains the correct URL for the site I am requesting the password reset for. (Subject is "Password reset for myMainDomain.com") The problem is the link inside the mail: the auto-generated link points to a CNAME of my mailserver, for some unknown reason. Django shouldn't even know that, since the only place I put the mailserver's domain is in the mail settings in setting.py My users.urls.py: urlpatterns = [path('accounts/', include('django.contrib.auth.urls')), path('', views.UserListView.as_view(), name='lista-user'), path('accounts/signup/', views.Iscriviti.as_view(), name='signup'), path('<int:pk>', views.Profilo.as_view(), name='profilo'), path('accounts/edit/<int:pk>', views.Modifica.as_view(), name='modifica-utente')] My template password_reset_email.html: Here is your password-reset link: {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} Relevant part of my settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.myMailServerdomain.it' EMAIL_PORT = '25' EMAIL_HOST_USER = 'MYUSER' EMAIL_HOST_PASSWORD = 'MYPASS' EMAIL_USE_TLS = False EMAIL_USE_SSL = False DEFAULT_FROM_EMAIL = 'noreply@myMailServerdomain.it' SITE_ID = 1 # -> This is … -
How can apply sorting on django rest serializer custom fields
I have serializer for user detail and I want to apply sorting on serializer custom fields. class ABCSerializer(serializers.ModelSerializer): status = serializers.SerializerMethodField() def get_status(self, obj): if obj.status == 'Draft': return 'Draft' elif obj.status == 'Inactive': return 'Inactive' else: if obj.publish_start_date and obj.publish_start_date > timezone.now(): return "Upcoming" elif obj.publish_end_date and obj.publish_end_date < timezone.now(): return "Expired" return 'Active' -
How to show the value of radio button from database to html template in Django?
To show the value in the edit page, incase of a simple textbox, we can show the value stored in database using {{ data.note }} where data is rendered from the views.py to html template. <div class="col-md-4 mb-3"> <label>Notes <span class="red-color">*</span></label> <input type="text" name="important_note" class="form-control" id="important_note" value="{{ data.note }}"> </div> If I want to do the same incase of the following group radio button, how can I show the selected value stored in database table ? (for example, Value B is stored in the database) <div class="col-md-4 mb-3" id="list_id"> <label>Select List</label> <input type="radio" name="list" value ="A" id="A"> A <br> <input type="radio" name="list" value="B" id="B"> B <br> <input type="radio" name="list" value="C" id="C"> C <br> <input type="radio" name="list" value="D" id="D"> D <br> <input type="radio" name="list" id="E" value="E"> E </div> NOTE: I don't want to use forms.py in this case. Thanks. -
Django AttributeError: 'function' object has no attribute 'as_view' in urls.py
Django AttributeError: 'function' object has no attribute 'as_view' in urls.py urls.py file from django.urls import path, register_converter from . import views, converter register_converter(converter.HexConverter, 'hex') urlpatterns = [ path('', views.QuestionView.as_view()), path('ask/', views.Ask.as_view()), path('<hex:pk>/', views.QuestionCurrent.as_view(), name='question_current'), ] -
Django serializing foreign key ids incorrectly
This is driving me nuts. I have a nested serializer that is retrieving the id of the related model. The id SHOULD be 5 but it's returning as 1. Hence when I run the following: class ReviewsMember(APIView): def get(self, request, *args, **kwargs): reviews = Review.objects.all() serializer = ReviewSerializer(reviews, many=True) review = serializer.data questions = review[0].get('review_questions') for question in questions: question_id = question.get('id') check_question = Question.objects.get(pk=question_id) return Response(serializer.data) I get DoesNotExist: Question matching query does not exist. at the check_question line. What am I doing wrong? -
resetting primary key for a user
I am having issues when I am testing endpoints using swagger with with my django project. I get the following error: { "user": [ "Invalid pk \"xxxxxxxxxx" - object does not exist." ], "session": [ "Invalid pk \"xxxxxxxxxx" - object does not exist." ] } Here is my models.py: # External Imports from django.db import models import uuid # Internal Imports from applications.models.application import Application from users.models.user import User from .session import Session # Fake data import factory import factory.django import factory.fuzzy from datetime import datetime from faker import Faker from faker.providers import BaseProvider import random from faker import Factory class ButtonClick(models.Model): """**Database model that tracks and saves button clicks for an application** """ # identifier id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) # info button_name = models.CharField(max_length=128, null=True, blank=True) application = models.ForeignKey( Application, related_name='button_clicks', null=True, blank=True, on_delete=models.CASCADE) user = models.ForeignKey( User, related_name='button_clicks', null=True, blank=True, on_delete=models.CASCADE) session = models.ForeignKey( Session, related_name='button_clicks', null=True, blank=True, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now=True) class Meta: db_table = 'button_clicks' ordering = ('-timestamp', ) def __str__(self): return f'{self.application} - {self.button_name}' I have tried creating a new superuser and using that to test endpoints but I still have the same primary key and session primary key (I'm sure this is probably … -
Confusing Django manage.py error on Docker run
I am trying to run the following command: % docker run --publish 8000:8080 --detach --name projectname projectname:latest but I keep getting this very unusual error I can't seem to figure out: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/src/mprova/backend/mellon/settings.py", line 101, in <module> 'default': dj_database_url.parse(os.environ.get('DATABASE_URL'), conn_max_age=600) File "/usr/local/lib/python3.8/dist-packages/dj_database_url.py", line 80, in parse if '?' in path and not url.query: TypeError: a bytes-like object is required, not 'str' This might have something to do with the npm WARN when I run docker build . -t projectname: Step 7/12 : RUN npm install ---> Running in XXXXXXXX (not … -
Django webapp (on an Wampserver) hangs indefintely when importing nltk in views.py
I've deployed the web app using Wampserver on a Windows Server 2012. When I import nltk in views.py, the web page refuses to load. Add this WSGIApplicationGroup% {GLOBAL} in the Wampserver htpd.config configuration file as indicated in this post and part of the problem has been resolved, but now when running the application using nltk package, the browser shows Server Error (500) -
Which is the best way to validate errors in Django?
I found that there is a lot of ways to validate errors in Django, I'm just wondering which one is preferable and why? e.g. using clean in form, like : deadline = self.cleaned_data.get('deadline') if datetime.strptime(str(deadline)[:19], '%Y-%m-%d %H:%M:%S') < datetime.today(): raise forms.ValidationError(_('Deadline cannot be in past!')) return deadline before saving we can validate if there is any error and sending the instence if everything right, like: def save(self, force_insert=False, force_update=False, *args, **kwargs): if datetime.strptime(str(deadline)[:19], '%Y-%m-%d %H:%M:%S') < datetime.today(): raise forms.ValidationError(_('Deadline cannot be in past!')) else: super(MODEL, self).save(force_insert, force_update, *args, **kwargs) also, we can do that in the forms in the class form we can check before saving if everything is right I want to know which is the best as a programmer and write a professional code -
Django fetch GenericRelation with aggregation
I'm using Django and Django Rest Framework to build my service. I used GenericForienkey to enable user to take an action on generic objects which contains Post model in here. Here's the models I've made class Post(SoftDeletableAndTimeStampedModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.TextField() content = models.TextField() reacts = GenericRelation(ReactedItem) class ReactedItem(TimeStampedModel): class Action(models.IntegerChoices): UNKNOWN = 0, "undefined" LIKE = 1, "like" UNLIKE = 2, "unlike" user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) action = models.IntegerField(_('action'), choices=Action.choices, default=Action.UNKNOWN) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.CharField(max_length=32) content_object = GenericForeignKey('content_type', 'object_id') What I wanted to do is, when getting the list of posts, I want to append how many people do like/unlike on each post. I override get_queryset method like this def get_queryset(self): queryset = Post.objects.aggregate( num_of_like=Count('reacts', filter=Q(reacts__action__exact=ReactedItem.Action.LIKE))) return queryset However it's not working as intended. Anyone knows how to solve this? Thanks in advance! -
Table not creating for django-background-tasks
I am new to django and i am trying to use background-tasks for sending mail notifications. But I am getting error as django.db.utils.OperationalError: no such table: background_task I have added background_task inside INSTALLED_APPS and gone through other related questions asked and so tried python manage.py makemigrations background_task But I am still getting same error. I am using Django==3.0.7 django-background-tasks==1.2.5 django-compat==1.0.15 Will appreciate any help -
A Django Issue when testing my website with a dropdown
I am following the tutorial at Django Tutorials. The goal is to get a dropdown list to display a logout when I click on it. Here is my settings.py where the static files are held: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] LOGOUT_REDIRECT_URL = 'home' I am getting a HTTP 404 error because of this. It's saying GET HTTP/1.1 404 1683 when I run it. Because of the error, when I click on the arrow, it won't show me the dropdown list. Can anyone show me how to fix this and what this error means? -
Django: Redirect to another page after download triggered
i want to Redirect to another page after download triggered my code is: animated_gif = BytesIO() frames[0].save(animated_gif, format='gif', save_all=True, append_images=frames[1:], ) animated_gif.seek(0) response = HttpResponse(content_type="image/gif") response['Content-Disposition'] = "attachment; filename=%s.gif" % "new" response.write(animated_gif.getvalue()) return response -
Unresolved error when importing app in urls.py file
I created 2 apps in my project. The first app works correctly. I followed the same method for the second app. When I try to import that apps view file, it gives me an error. from users import views it gives me an unresolved error(it is not recognizing users) I also added that app in settings.py file of the blog project. users.apps.UsersConfig is also added in setting.py file -
How to change list number in Django templates loop?
So basically I have a list of 10 items from my database that I'm looping into one of my templates. How could I dynamically change the number of the list item as well? Here is what my loop looks like {% for list in lists %} <div class='collection-item avatar cart-row'> <div> <h5 class="center container left card-title">{{ list.value }}</h5> </div> </div> {% endfor %} The current result is "Shirt", "Shoes", "Pants", etc. What I want to achieve is "1. Shirt", "2. Shoes", "3. Pants", etc. My question is how could I do that? Thank you. -
uwsgi/nginx doesn't respond until subprocess is done
I have server with nginx the passes http trafic to uwsgi runnig my django app. the django view I'm calling is creating a subprocess that runs the following test.sh bash script: #!/bin/sh echo hello sleep 10 echo morning for some reason I am not getting the 200 response from the view until the bash is done, i.e. "morning" is printed, although subprocess supposed to create a thread that run in parallel. While trying to debug this issue I noticed that if I cURL locally from server while running django directly with python manage.py runserver or when running uwsgi with http=127.0.0.1:8000 I get the 200 response before the "morning" print as expected. Any ideas why with socket=127.0.0.1:8000 and nginx it behaves different? my nginx is configured to pass http trafic to django: upstream django { server 127.0.0.1:8000; # for a web port socket (we'll use this first) } server { listen 80; location /api/ { uwsgi_pass django; include /path_to/uwsgi_params; # the uwsgi_params file you installed } } my uwsgi ini: [uwsgi] socket=127.0.0.1:8000 module=my_module.wsgi:application chdir=/project_dir master=true vacuum=true logger=file:/log_path stats=/tmp/uwsgi_stats.socket single interpreter=true and my view.py is: from subprocess import Popen from rest_framework import views from rest_framework.response import Response class TestApi(views.APIView): def post(self, request, … -
Bootstrap4 multi-slide carousel with Django
I'm trying to build a dynamic multi-slide carousel with Django and Bootstrap. Following the instructions laid out here, I've built the following but there is a problem with the html as the data from the model is not rendered on screen. (I am certain that it is a problem with the below as I have another similar carousel on the page which works fine). template.html: <div class="container"> <div id="modelCarousel" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> {% for modelInstance in modelData %} {% if forloop.first %} <li data-target="#modelCarousel" data-slide-to="0" class="active"></li> <li data-target="#modelCarousel" data-slide-to="1"></li> <li data-target="#modelCarousel" data-slide-to="2"></li> {% endif %} </ol> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"> <img data-src="{{ model.image }}"> </div> </div> {% endfor %} <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="icon-prev" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <span class="icon-next" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> Thanks!