Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
Perform long functions on Django web app hosted on Heroku
I am working on creating a web app with django. It involves data handling, and some of the functions take a long time to perform. This is fine on localhost, but when I put it on heroku, I get timeout errors. Right now, I am using forms to submit requests for handling data. Is there an alternative to using POST/GET requests that won't cause timeout errors? Thanks in advance. -
fill a form field in Django views
I am trying fill in a value to one of my form fields. The form has the following fields: Username referral Email Password confirm-password I want to automatically fill the referral field from the views.py but can't get it right. any Ideas? Views.py def consultant_register(request): field_name = 'referral' obj = ReferralResponse.objects.last() referral_code = getattr(obj, field_name) form = ConsultantSignUpForm(request.POST, initial={'field':referral_code}) if form.is_valid(): my_model = form.save(commit=False) my_model.referral_code = referral_code my_model.save() login(request,user) return redirect('/') return render(request, 'accounts/consultant_register.html', {'form': form}) -
Django Multi User Login in a Django Project
I have Implemented a Django Application but it's still in Testing. So I'm using it in local host.So when i login using a form.It authenticates me and im logged in .But If im open it in another tag.Now it actually logs me in as the previous user.So when i Log it out ,i'm totally logged out from both tabs.My question is if say I host this website.And two different people tries to log in at the same time,will the website work properly and log them in???(provided both are using different computers) -
I am trying t create a login/logout functionality in django but am getting follow error
Hi i am trying to create a login/logout functionality in django ,i have been trying for some time now but am getting the following error please help me out i am new to all Django.I have done everything as taught in the course but am still getting this error,i think error is in url file but i don't really know. Using the URLconf defined in TheResources.urls, Django tried these URL patterns, in this order: ^$ [name='index'] admin/ ^FirstApp/ ^user_login/$ [name='user_login'] login/ [name='login'] logout/ [name='logout'] password_change/ [name='password_change'] password_change/done/ [name='password_change_done'] password_reset/ [name='password_reset'] password_reset/done/ [name='password_reset_done'] reset/<uidb64>/<token>/ [name='password_reset_confirm'] reset/done/ [name='password_reset_complete'] ^logout/$ [name='logout'] The current path, FirstApp/user_login/{url 'FirstApp::user_login'}, didn't match any of these. URL.py project urlpatterns = [ url(r'^$',views.index,name='index'), path('admin/', admin.site.urls), url(r'^FirstApp/',include('FirstApp.url')), path('', include("django.contrib.auth.urls")), url(r'^logout/$',views.user_logout,name='logout'), Url .py application file url(r'^Registration/$',views.RegistrationView,name='Registration'), url(r'^user_login/$',views.user_login,name='user_login'), Views.py file def user_login(request): if request.method=='POST': username=request.POST.get('username') password=request.POST.get('password') user=authenticate(username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("account is not active") else: print("Someone else tried to login and failed") return HttpResponse("Invalid credentials") else: return render (request,'FirstApp/Base.html',{}) Temlplate Base.html {%if user.is_authenticated%} <a href="{%url 'logout'%}">Logout</a> {%else%} <a href="{%url 'FirstApp:user_login'%}">login</a> {%endif%} Login.html file <form action="{url 'FirstApp::user_login'}" method='POST'> {%csrf_token%} <label for="username">Username</label> <input type="text" name="username" placeholder="Enter Username"> <label for="password">Password</label> <input type="Password" name="password" placeholder="Enter Password"> <input type="Submit" value="Login"> </form>