Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to hide the Token model from rest_framework.authtoken in django admin panel
I tried to solve the problem using this two methods from rest_framework.authtoken.models import Token admin.site.unregister(Token) ----- from rest_framework.authtoken.models import TokenProxy admin.site.unregister(TokenProxy) But the response is a mistake that says "The model Token is not registered" -
Upload and process files on Django results in 500 error when deploy on Heroku
The website is: https://atw.herokuapp.com It allows users to drop in Microsoft Word files, and once Django receives files, it processes them. I use React to build my frontend, and the code responsible for making the POST request once the user dropped in files is: const onDrop = useCallback((acceptedFiles) => { // Do something const csrftoken = Cookies.get("csrftoken"); var form_data = new FormData(); for (var i = 0; i < acceptedFiles.length; i++) { form_data.append("atw", acceptedFiles[i]); } axios .post("https://atw.herokuapp.com/upload/", form_data, { header: { "content-type": "undefined", "X-CSRFToken": csrftoken, }, }) .then((res) => { window.open("https://atw.herokuapp.com/download/"); }) .catch((e) => console.log(e)); }, []); I have a Django view that handles uploaded files: class Upload(APIView): """ Process Microsoft Word files received through POST requests """ def post(self, request): form = DocumentForm(request.POST, request.FILES) if form.is_valid(): STATE['status'] = 'processing' for f in request.FILES.getlist('atw'): newfile = Document(docfile=f) newfile.save() output_filename = "OUT-ATW.docx" processor = FilesProcessor(output_filename) processor.process() STATE['status'] = 'done' return HttpResponse("Successfully processed files!") else: form = DocumentForm() return render(request, 'myapp/index.html') I use django-cors-headers to handle CORS headers and all that, and have whitelisted herokuapp in my settings.py: ALLOWED_HOSTS = ['.herokuapp.com', '127.0.0.1'] The Problem It works fine locally, but after I deployed the project on Heroku, I cannot upload files successfully. You … -
Django Migration questions
I am new to Django, but every time I do any change to the models, I need to do 'python manage.py makemigrations' then 'python manage.py migrate' makemigrations will create new files under migrations folder: 0001_xx 0002_xx 0003_xx ... My question is, is this the right way to do it? Because if every time there is a change to the DB model, then a new migration file is created, in the end I could end up having many migration files. Then how to do migration when I want to move to production? Just run the 'python manage.py migrate'? -
Is it possible to prepopulate Django FormSets with FileFields?
Thanks for stopping to take the time to read my question. Here's my issue. I am creating attachments on a form. Multiple. All is well and good. Here's the problem...I want to "GET" those attachments on an update form so that they are displayed and can be deleted if the form is approved. This is proving challenging. I am prepopulating forms in some cases by using a dictionary to get the data that I need as initial data. All is working as expected except for FileFields or FieldFile as Django references it. I have read a few similar articles on SO...but nothing is helping. I understand the security issues and I am not trying to "FORCE" uploads..I simply want to grab the attachment name and copy it to another model essentially. My form submits, but the attachments are not being processed. Here's my code.... HTML... <form method="POST" enctype="multipart/form-data" id="forms"> {{ procedure_attachment_form.management_form }} {{ procedure_attachment_form.non_form_errors }} {% for fileform in procedure_attachment_form.forms %} {{ fileform.id }} <div class="inline {{ procedure_attachment_form.prefix }}"> {{ fileform.attachments }} {% if procedure_attachment_form.non_form_errors %} <h3 class="spacer174"> {{ procedure_attachment_form.non_form_errors }} </h3> {% endif %} {% if fileform.attachments.errors %} <h3 class="spacer174"> {{ fileform.attachments.errors }} </h3> {% endif %} {{ fileform.procedure.as_hidden … -
how to create foreign key from multiple models on single field in django
i have multiple models like, class Service1(models.Model) class Service2(models.Model) class Service3(models.Model) class Service4(models.Model) class Orders(models.Model): user = models.ForeignKey(User, on_delete=models.CASECAD) orders = models.ForeignKey((Service1, Service2, Service3, Service4), on_delete=models.CASECAD) how is this possible to create orders with different services like above -
Django query performance slow unless limited
I have a relatively simple view that I use for AJAX requests that takes a simple ORM query and renders it as a string. I did not include the building of the params as I have tested the method and isolated the issue to rendering the query results in the template. Products.objects.filter(**params) return render_as_string('templates/product.html', {'products': products'}, request) The query returns 1255 records, which isn't really much, but takes 31 seconds to complete the AJAX request. However, if I slice/limit the query to 1255 rows as follows: Products.objects.filter(**params)[:1255] return render_as_string('templates/product.html', {'products': products'}, request) then the AJAX request will only take 1.2 seconds. Still less than ideal but I can at least work with that. I plan on setting up pagination to get the time to a comfortable level but I am confused to the underlying issue. I am feeding the same number of rows to render as string. -
How to pass a URL value from a template to a form_valid method inside a Class Based View in Django
I started working with django and I have come across a problem that I am not able to solve. I believe this should be easy but I cannot figure it out. I am getting an Id from a template which I pass through a URL. data.html ... <div class="container"> <form method="GET" action="{% url 'data:next' %}"> <input type="hidden" required name='job_id'> <button type="submit" class="btn btn-primary">Run Next</button> {% csrf_token %} </form> </div> ... url.py app_name = "data" urlpatterns = [ ... ... path('next/', RunNextView.as_view(), name='next'), ] This seems to pass the job_id value to the URL as after selecting a checkbox (in this case with job_id pointing at 44) and clicking on the Run Next button I get to a url such as: http://localhost:8000/data/next/?job_id=44&Some-token which I think is good. Now I want to pass the number 44 to a class based view which is the problem and I was not able to do it. As shown below I need the job_id in order to run the run_next_task task. How do i grab that 44 and pass it to the form_valid method inside the CBV ? views.py class RunNextView(FormView): template_name = 'next.html' form_class = RunForm success_url = reverse_lazy('data:list') def dispatch(self, request, *args, **kwargs): if … -
Django forms - need a form that shows a set of questions each question having a list of possible answers
I have the following three models: models.py class Exam(models.Model): lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name="exams") passing_grade = models.IntegerField(default=85) must_pass = models.BooleanField(default=True) to_next_lesson = models.BooleanField(default=True) display_order = models.IntegerField(default=1) class ExamQuestion(models.Model): exam = models.ForeignKey(Exam, on_delete=models.CASCADE, related_name="questions") text = models.CharField('Question', max_length=255) class ExamAnswer(models.Model): question = models.ForeignKey(ExamQuestion, on_delete=models.CASCADE, related_name="answers") text = models.CharField('Answer', max_length=255) is_correct = models.BooleanField('Correct answer', default=False) The Form I require would render each question in an exam roughly something like this (sorry couldn't figure out to show rendered html in question: <form> <div> "Quality" is one our core values<br /> <input type="radio"/> True <br /> <input type="radio"/> False </div> <div> What should you do if you see an employee stealing?<br /> <input type="radio"/> Report it to your manager<br /> <input type="radio"/> Call the police<br /> <input type="radio"/> Confront the employee<br /> </div> <div> <input type="submit"> </div> </form> Ignoring the incomplete and possibly stupid HTML (shown bare bones here for the concept) How can I get the Django form language to output each individual question with multiple answers beneath it? Note: The number of questions is variable, some exams might have 3 questions, others could have 5 or 6. The number of answers per question is also variable, some questions might have two answers … -
Django, direct download link in email is not working
Django: direct download link in email is not working Hi, I have a view that looks like this: def download_kit(request): file_path = "path/to/my/file" return FileResponse(open(file_path, 'rb'), as_attachment=True) But the link is not working when I send it in an email. What am I doing wrong? The link works well in a normal page, it works if I type the link directly in the browser too. -
ModuleNotFoundError: No module named 'encodings'. Django Deployment with mod-wsgi and apache
I am Deploying the Django project with mod_wsgi and Apache on Microsoft Windows Server 2019. I am unable to find the proper solution to this on the internet. I don't know why mod-wsgi is not loading python modules? Here is my httpd.conf ServerName xx.xx.xx.xx:80 # Django Project LoadFile "C:/Users/abc/AppData/Local/Programs/Python/Python39/python39.dll" LoadModule wsgi_module "C:/Users/abc/AppData/Local/Programs/Python/Python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "C:/Users/abc/AppData/Local/Programs/Python/Python39" WSGIScriptAlias / "C:/inetpub/wwwroot/myproject/django/myapp/wsgi.py" WSGIPythonPath "C:/inetpub/wwwroot/myproject/django/" <Directory "C:/inetpub/wwwroot/myproject/django/myapp/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/inetpub/wwwroot/myproject/django/static/" <Directory "C:/inetpub/wwwroot/myproject/django/static/"> Require all granted </Directory> When I run command: ./httpd.exe -k start I get this error in logs. And the server doesn't start. Starting the 'Apache2.4' service The 'Apache2.4' service is running. pm_winnt:notice] [pid 6896:tid 552] AH00455: Apache/2.4.49 (Win64) mod_wsgi/4.9.0 Python/3.9 configured -- resuming normal operations [Tue Sep 28 19:25:46.975430 2021] [mpm_winnt:notice] [pid 6896:tid 552] AH00456: Apache Lounge VS16 Server built: Sep 12 2021 10:23:43 [Tue Sep 28 19:25:46.975430 2021] [core:notice] [pid 6896:tid 552] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Tue Sep 28 19:25:46.991023 2021] [mpm_winnt:notice] [pid 6896:tid 552] AH00418: Parent: Created child process 9780 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe' sys.base_prefix … -
Django how to show choices in select input
how can I show my choices in the "select" input for a form? And why can't I access the DateInput to set a Input as a datepicker in the form, like I do for "grund" as "Select"? Code: from django import forms from django.forms.widgets import DateInput from .models import expense class DateInput(forms.DateInput): input_type = 'date' class ExpenseForm(forms.ModelForm): class Meta: model = expense CHOICES = ( ('ME', '1'), ('YOU', '2'), ('WE', '3'), ) fields = [ 'datum', 'grund', 'beschreibung_grund', 'summe_ausgabe' ] widgets = { 'datum': DateInput(), 'grund': forms.Select } -
NGINX/gunicorn - password protect whole Django website using NGINX conf
I need to temporarily password-protect a running website using basic auth. The website shouldn't be accessed by anybody (not even existing users) except those who have given credentials, let's say: USERNAME: 'xxx' PASSWORD: 'yyy' I know I can password-protect directories that are indexed by NGINX but is this also possible for NGINX/gunicorn? server { listen 80; server_name www.mysite.com; return 301 $scheme://mysite.com$request_uri; } server { listen 80; server_name www.mysite2.com; return 301 $scheme://mysite2.com$request_uri; } server { server_name mysite2.com mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/futilestudio/mysite; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mysite.com-0001/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mysite.com-0001/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } -
django pytest case fails while postman does not
I am writing a test for an API using Django rest framework. The user has to register and then login to acces my endpoint. If I register (post) with postman, then login (post) and I get the access_token that I consequently pass to the post request I get a 200. Also using curl curl --location --request GET 'localhost:8000/api/v1/signals/' \ --header 'Authorization: token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJleHAiOjE2MzI4NTc2MzIsImlhdCI6MTYzMjg1NzMzMn0.WCjjg3jSZ4TO_Q51hGwZmj04iFeV9ffRnp9GaFch_IM' \ --header 'Cookie: csrftoken=HrgKpprN95ExIPmm6Y2Qqc3WvDrfqQRgqUY9v4bTN9gT7nETEuBjhtY6IS7Sv9Ky; sessionid=ml04spqh6gmjuicp8vnda1t0lqopnuvx' \ --data-raw '' but If I write a test, it fails def test_get_signal(client): form_data = { "username": "testuser", "password": "mytestpassword", } CustomUser.objects.create_user(**form_data) response = client.post("/accounts/login/", form_data, follow=True) assert response.status_code == 200 response_content = json.loads(response.content) token = response_content["access_token"] headers = { "Authorization": "Token " + token, "Content-Type": "application/json", } response = client.get( path="/api/v1/signals/", headers=headers, ) assert response.status_code == 200 I get a 403. what am I doing wrong? -
testdriven.io django tdd - got Error: '$' is not a valid port number when running docker run
Every time I try to run the command docker run --name django-tdd -e "PORT=8765" -p 8008:8765 registry.heroku.com/lit-sierra-68791/web:latest I get Error: '$' is not a valid port number Dockerfile.prod # pull official base image FROM python:3.9.5-slim-buster # set working directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV DEBUG 0 ENV SECRET_KEY fgerg345y4y56u5u5757jk5k56kuykykyk ENV DJANGO_ALLOWED_HOSTS localhost 127.0.0.1 [::1] ENV PORT 8765 # install system dependencies RUN apt-get update \ && apt-get -y install gcc postgresql \ && apt-get clean # add and install requirements RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # add app COPY . . # add and run as non-root user RUN adduser --disabled-password myuser USER myuser # run gunicorn CMD gunicorn drf_project.wsgi:application --bind 0.0.0.0:$PORT I even added the ENV PORT 8765 in the file above, but it didn't worked too. -
Django ListCreateAPIView not calling get_querryset
Hello I started with Django couple weeks ago, I wanted to return the objects that are closest to the location send in the query parameters. I think that the function get_querryset is never called because it doesn't change anything. These are the files I have: #models.py from django.contrib.gis.db import models class CarOffering(models.Model): name = models.CharField(max_length=200) location = models.PointField(null=True,blank=True) def __str__(self): return self.name #serializer.py from .models import CarOffering from rest_framework import serializers class CarSerializer(serializers.ModelSerializer): distance = serializers.FloatField(source='distance.mi', read_only=True, required=False) class Meta: model = CarOffering fields = ['name','location', 'distance'] read_only_fields = ['location'] #Views.py from .models import CarOffering from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.db.models.functions import Distance from .serializers import CarOfferingSerializer from django.shortcuts import render from rest_framework.generics import ListCreateAPIView import geocoder class ListCreateCarOffering(ListCreateAPIView): queryset = CarOffering.objects.all() serializer_class = CarOfferingSerializer def get_querryset(self): qs = super().get_querryset() latitude = self.request.query_params.get('lat', None) longitude = self.request.query_params.get('lng', None) if latitude and longitude: pnt = GEOSGeometry('POINT(' + str(longitude) + ' ' + str(latitude) + ')', srid=4326) qs = qs.annotated(distance=Distance('location', pnt)).order_by('distance') return qs #urls.py from django.contrib import admin from django.urls import path from proj.views import ListCreateCarOffering urlpatterns = [ path('admin/', admin.site.urls), path('api/caroffer', ListCreateCarOffering.as_view(),name = 'list_caroffer') When I look in http://127.0.0.1:8000/api/caroffer I get the same thing as if I do http://127.0.0.1:8000/api/caroffer?lat=0&lng=0: [ { … -
Fetch load a page that only shows the Json data instead of the page that should be displayed
I am trying to make a twitter like application for a class project. When the like button is clicked the button should then change to say unlike and the like count should increase without reloading the page. Instead the page reloads to a white background and the only thing on the page is "{"likeButton": "Unlike", "total_likes": 0}" my json data. Any help would be appreciated. views.py @login_required def likes(request, post_id): try: current_user = request.user post = Post.objects.get(id = post_id) likeCount = Post.objects.get(id = post.id) total_likes = likeCount.like_count likeButton = request.POST.get('buttonForLikes') if likeButton == 'Like': total_likes = total_likes + 1 post.like_count = total_likes post.save() post.like.add(current_user) post.save() else: total_likes = total_likes - 1 post.like_count = total_likes post.like.remove(current_user) post.save() return JsonResponse ({'likeButton': likeButton, 'total_likes': total_likes,}, status=200,) except KeyError: return HttpResponseBadRequest("Like Error") urls.py from django.urls import path from . import views app_name = "network" urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("new-post", views.new_post, name="new-post"), path("profile/<str:username>", views.profile, name="profile"), path("follows/<str:username>", views.follows, name="follows"), path("following", views.following, name="following"), path("edit", views.edit, name="edit"), path("likes/<int:post_id>", views.likes, name='likes') ] HTML {% extends "network/layout.html" %} {% load static %} {% block body %} {% if user.is_authenticated %} <div class="borderDiv"> <div class="newPostCard"> <form id = "new_post_form" name="newPost" … -
Django ModelForm: change a field value when blank
Is there any way to change a field value (related to a foreign key) in a Django ModelForm once the form is initialized and filled by the user (I'm using request.POST). I want to change the value when the user doesn't select any option of the dropdown list. I tried this with no result: form.data['field'] = 1 I got this message: This QueryDict instance is immutable I know I can set an initial (default) before introducing data in the form but I don't want to have the default option highlighted in the dropdown. -
Pass kwarg into an inlineformset_factory?
I am trying to pass the request object into my inlineformset_factory and am struggling to accomplish this. In forms.py I have the following: class SummativeScoreForm(forms.ModelForm): """ Form definition for SummativeScore Form """ subdomain_proficiency_level = forms.ModelChoiceField( empty_label="Undecided", queryset=SubdomainProficiencyLevel.objects.none(), widget=forms.RadioSelect, required=False, ) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request", None) super(SummativeScoreForm, self).__init__(*args, **kwargs) if self.instance: if self.request.user == self.instance.summative.employee: self.fields["subdomain_proficiency_level"].disabled = True self.fields[ "subdomain_proficiency_level" ].queryset = SubdomainProficiencyLevel.objects.filter( subdomain=self.instance.subdomain ) self.fields[ "subdomain_proficiency_level" ].label = f""" {self.instance.subdomain.character_code}: {self.instance.subdomain.short_description} """ class Meta: model = SummativeScore fields = "__all__" widgets = { "subdomain_proficiency_level": forms.RadioSelect( attrs={"class": "list-unstyled"} ), } SummativeScoreInlineFormset = inlineformset_factory( Summative, SummativeScore, fields=("subdomain_proficiency_level",), can_delete=False, extra=0, form=SummativeScoreForm, ) I'm using a FormView CBV to show this inline_formset class SummativeScoreFormView( LoginRequiredMixin, UserIsObserverOrObserveeMixin, SingleObjectMixin, FormView, ): model = Summative template_name = "commonground/summative_score_form.html" pk_url_kwarg = "summative_id" def get(self, request, *args, **kwargs): summative_id = kwargs.pop("summative_id") self.object = self.get_object( queryset=Summative.objects.filter(id=summative_id) ) return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): summative_id = kwargs.pop("summative_id") self.object = self.get_object( queryset=Summative.objects.filter(id=summative_id) ) return super().get(request, *args, **kwargs) def get_form(self, form_class=None): return SummativeScoreInlineFormset( **self.get_form_kwargs(), instance=self.object ) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["request"] = self.request return kwargs def form_valid(self, form): form.save() messages.add_message(messages.SUCCESS, "Changes were saved!") HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form): print("invalid form") return super().form_invalid(form) def get_success_url(self): user_id = self.kwargs["user_id"] … -
How to trigger the page reload animation without refreshing?
Any ideas? Image, at least 30 characters -
What does that mean Pending request status in chrome developer tool while login apache based application?
enter image description hereWhile login apache 2.4 based application backend url status shows in pending state in chrome developer tool and not able to proceed further and unable to login application. Also not able to logged error in the apache log file. -
How to calculate average of fields on some if conditions in django?
I am working on Django where I have two models Gigs and Orders and I am calculating average Completion time of order of every gig. in order model I have two fields order start time (which I'm sending whenever seller accepts the order) and order completed time (which I'm sending when seller delivered) the order. but I want to calculate average of only those orders where isCompleted = True Models.py class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') orderStartTime = models.DateTimeField(default=timezone.now) orderCompletedTime = models.DateTimeField(default=timezone.now) isCompleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if getattr(self, '_average_completionTime', None): return self._average_completionTime return self.gig.aggregate(Avg(F('orderCompletedTime') - F('orderStartTime'))) Views.py class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin): def get_queryset(self): return Gigs.objects.annotate( _average_completionTime=Avg( ExpressionWrapper(F('gig__orderCompletedTime') - F('gig__orderStartTime'), output_field=DurationField()) ) ) serializer_class = GigsSerializerWithAvgTime permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.retrieve(request, *args, **kwargs) Serializers.py class GigsSerializerWithAvgTime(serializers.ModelSerializer): average_completionTime = serializers.SerializerMethodField() def get_average_completionTime(self, obj): return obj.average_completionTime class Meta: model = Gigs … -
I am trying save the Exception to sql lite db in my django project.But getting error
The Exception value is local variable 'func' referenced before assignment when i am trying to save it to db i am getting this error Failure near "func": syntax error Please Help me with this -
Why are django tags causing problems?
Is there any reason why 1st django tag above !DOCTYPE html is causing error and {% comment %} tag is not working at all? I'm working in pycharm. -
Adding features and filtering later on the product model
If I need to explain more clearly compared to the title, there is a table on the database of the Product class created in the models.py file. Is it possible for the user to add a new attribute to this Product table? In other words, the user will add a property called color and assign values to this property, and then filter on it. A system written in PHP called IdeaSoft supports this, but is it possible to do this with Django? Is there a library about it? -
ModuleNotFoundError: No module named 'django_heroku'
i wanted to run my project in server. Well when I start the server I get an error ModuleNotFoundError: No module nameddjango_heroku enter image description here but i don't use heroku thanks for answer