Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django WSGI and ASGI via Passenger confusion
Hi all I have a dedicated plesk server on the internet running debian 12. I've started experimenting with Django and deploying django apps via apache and Nginx. I have successfully managed to get a simple Django app to run via mod_wsgi on apache and also passenger wsgi on both apache and nginx. With mod_wsgi its clear that the Django wsgi.py file in the project is called and the apache directive simply points to that file my first confusion is with passenger and the configuration does it ignore the project wsgi.py settings completely? The second confusion starts with ASGI I thought nginx simply passes the request over to Django and python to handle like it does in WSGI but I can't get it to work I have been trying to find a simple setup for ASGI on a dedicated server but all I get is projects running the local django server. Do I need to configure nginx? should I make a file passenger.asgi.py? there is very little documentation concerning implementing it onto a running server with domains... Any ideas examples or tutorials would be much appreciated.... -
django server protection against WebSocket Flood attack
I have a django application that works as follows: the user through an ajax request uploads a file to the server for processing -> a celery task is created to process this file -> the user receives a response in the form of some unique key -> the user establishes a websocket connection with the server using of this key (the name of the room is created based on it) -> when the processing of the file is completed, the server will send a message to the room by the key and on client whe he received the message then connection will be closed. The url for connecting via websocket connection looks like this - ws/download_result/<str:key>/ I also store the keys by which the websocket connection is established in the database, and therefore when someone tries to establish a third-party connection (if he was not on the site and did not give the file for processing and accordingly there is no key - because with each file processing a new key is created - for in order to be able to connect to the server through it and get a result) then I can check whether such a key exists … -
Filtering with AJAX in Django
In my Django project, I have a basic view where I pass all instances of the Article model and then display them in an HTML template with a for loop. I also have a Topic model, so I display all topics as buttons, also with a for loop. My goal is to filter articles by clicking a specific Topic button, so if I click "Politics," for example, then only articles connected to the "Politics" topic will be displayed instead of all articles. I want to use an AJAX request for this, but I do not have experience with it, so I am having some problems figuring out how to achieve my goal. Here is my view. I am trying to do AJAX in the same view, but I am not sure if this is correct because, in most cases that I saw, a separate view was created: def main_view(request): all_articles = Article.objects.all()[::-1] top_articles = all_articles[:10] topics = Topic.objects.all() if request.is_ajax(): topic_name = request.GET.get('topic_name') all_articles = Article.objects.filter(topics=topic_name) return JsonResponse({'all_articles': all_articles}) return render(request, "mainapp/main_refactor.html", {"all_articles": all_articles, "top_articles": top_articles, "topics": topics}) Simplified HTML template: {% for topic in topics %} <button class="topic-button" data-url="{% url 'mainapp:filter_articles' topic.name %}" data-topic-name="{{ topic.name }}">{{ topic.name }}</button> {% … -
Bar Chart Not Stacking
I have been trying to adapt this tutorial, How to Use Chart.js with Django, to my AWS billing reports. I want to tweak this graph from the tutorial: I want to "stack" the costs from the various AWS services for each month, but when I tried to stack the cost I get this chart: Here is the pertinent code I have written: monthly_cost/views.py: from django.shortcuts import render from django.db.models import Sum from rest_framework import viewsets from django.http import JsonResponse from .models import MonthlyCostReport from .serializers import MonthlyCostReportSerializer def home(request): return render(request, 'home.html') def product_cost_chart(request): colors = ['#DFFF00', '#FFBF00', '#FF7F50', '#DE3163', '#9FE2BF', '#40E0D0', '#6495ED', '#CCCCFF', '#9CC2BF', '#40E011', '#641111', '#CCCC00'] labels = [label.get('bill_billing_period_start_date').strftime('%Y-%m-%d') for label in MonthlyCostReport.objects.values('bill_billing_period_start_date').order_by( 'bill_billing_period_start_date').distinct()] datasets = [] for i, product_cost_pair in \ enumerate(MonthlyCostReport.objects.filter(bill_billing_period_start_date=labels[0]).values( 'line_item_product_code').annotate(product_cost=Sum('line_item_blended_cost')).order_by( '-product_cost')): dataset = { 'label': product_cost_pair.get('line_item_product_code'), 'backgroundColor': colors[i % len(colors)], 'data': [pc.get('product_cost') for pc in MonthlyCostReport.objects \ .filter(line_item_product_code=product_cost_pair.get('line_item_product_code')) \ .values('line_item_product_code', 'bill_billing_period_start_date') \ .annotate(product_cost=Sum('line_item_unblended_cost')).order_by('bill_billing_period_start_date')] } datasets.append(dataset) return JsonResponse(data={ 'labels': labels, 'datasets': datasets, }) templates/home.html {% block content %} <div id="container" style="width: 75%;"> <canvas id="product-cost-chart" data-url="{% url 'product-cost-chart' %}"></canvas> </div> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script> $(function () { var $productCostChart = $("#product-cost-chart"); $.ajax({ url: $productCostChart.data("url"), success: function (data) { console.log(data); var ctx = $productCostChart[0].getContext("2d"); new Chart(ctx, … -
What is the most appropriate way to organize files in Django?
What is the best in django? Should there be a main CSS file for all HTML page files, or should each HTML file have a special CSS file, as well as for JavaScript files in terms of performance? I am a beginner in learning Django and I do not know what is the most appropriate method or the recognized method. -
In Django how to bulk_create with a model that has a file field?
I have a model Document: class Folio(): status = models.OneToOneField(Status, on_delete=models.CASCADE, verbose_name='current status*') file = models.FileField( upload_to=create_route_file, verbose_name='PDF*', help_text='Format PDF' ) I need to create objects of it with bulk_create(), to make it with few queries. I am trying to create objects first with simple Folio() and Status(), putting them into a list and then saving it with bulk_create: status = Status() document_parameters = { 'status': status, ... } document = Document(**document_parameters) file = custom_open_file_function(route_to_file) file_name = 'name...' file.file.save(file_name, File(file)) That last line raise this error: ValueError: save() prohibited to prevent data loss due to unsaved related object 'status'. I don't wanna to do a save() there because that integrity problem with Status and because I don't want to do a query there. All the objetive with bulk_create is to do just one query to statuses and one query for documents, avoiding doing one query per document. But I don't know how to deal with that FileField. -
Python Django UpdateView: 404 not found
I'm using the built in class based views, in this case the UpdateView. The documentation doesn't give any hints towards how the urls.py must look like. Which url pattern is matched by that generic view, so that I can update a particular object (e.g. with id 1 in the database)? I tried: path("myroute/<int:pk>/", views.myUpdateView.as_view(), name="myname") The view behind views.myUpdateView is a django.views.generic.edit.UpdateView and when I navigate to let's say myroute/1/ I get a 404 error. How am I supposed to use that generic view? I was just guessing that it must somehow fetch the pk parameter from my URL, but I see no documentation for that part? Sorry for not including the template ecetera, but it's not really needed here because my question is so simple: which url pattern(s) is (are) processed by the UpdateView? Did I overlook something in the documentation? Thank you in advance! -
How to translate static slug in Django
Hello I am trying to develop a multilanguage website in Django. I am using django-modeltranslation for this. I can change the dynamic slugs via Django admin this is fine. But how can i change the static slug? For example I am talking about this: mydomain.com/services/my-dynamic-service Here is services is static slug. But when I change the language of website, I want to change /services/ slug to new slug meaning /services/ from the language I switch. -
strange behavior when getting env var in container | Django, Poetry, Docker
I need to get an env var from an docker container. This build is triggered with a docker compose file and I passed also the env variables with env_file. When I login to the container with docker exec -it conatinerName bash I can echo the variable and get correct output. Even when I trigger docker exec -it containerName echo $DEBUG inside the poetry environment, I get the correct answer. When I trigger this command from a terminal session without acitvated environment I get nothing. For me its very confusing, because I thought my docker container has nothing to do with my poetry environment. I just want to get the env var($DEBUG) from inside the container undependend the location I trigger this command. -
Is it a good idea to separate general and user-specific characteristics of the same row in two MySQL tables?
I'm currently making an app for uni in which you can put your clothes and it will select your outfit of the day. We're at the beginning of the project, so a lot of it is barebones, but we had a problem come up when talking with our professor. We talked about databases and we struggled with 2 possible schemas for one reason: clothes might not be unique. If they're not unique, and two users have the same top, pair of pants, etc., then He showed me some stuff that showed how I might be wrong, but he told me to post here just in case. He said it would be preferable to make the database like this: Users user_id (user credentials and others) Possessions possession_id possessor_id (FOREIGN) possession_clothes_id (FOREIGN) (personal parameters, like how many times worn or if it's one of the user's favorite for example) Clothes clothes_id clothes_name clothes_type clothes_size (impersonal parameters, such as color and others) I suggested making a database schema that made the clothes completely unique, whether they're the same or not, which would basically look like this: Users user_id (user credentials and others) Clothes clothes_id possessor_id (FOREIGN) clothes_name clothes_type clothes_color clothes_size (other impersonal parameters) … -
Dynamic creation of Django models
I've developed a frontend constructor for creating data models for users who don't know how to code. The issue I'm encountering is that when the function is executed, migrations are not applied (which is one of the requirements of my task), and after server reboot, the created models disappear. How can I fix this issue? I'm using SQLite with Python 3.12. -
Encountering Race Conditions Despite Using Django's Atomic Transactions and select_for_update
I'm encountering race conditions in my Django application despite implementing atomic transactions and utilizing the select_for_update method. Here's an overview of the problem and the steps I've taken so far: Problem: I have two Django models, Transaction and Account, where Transaction instances affect the balance of associated Account instances. However, due to the large size of transactions, I'm experiencing race conditions, resulting in false outcomes and incorrect balance updates. Database Schema: Transaction: id (Primary Key) amount account_id (Foreign Key referencing Account.id) Account: id (Primary Key) balance Steps Taken Atomic Transactions: I've wrapped the critical sections of my code that involve database operations within Django's atomic transactions using the @transaction.atomic decorator or transaction.atomic context manager. Row-Level Locking: I've utilized the select_for_update method to lock the rows in the Account table during reads, ensuring that concurrent transactions don't interfere with each other's updates. Despite implementing these measures, I'm still encountering race conditions, leading to incorrect balance calculations and data inconsistency. Additional Context: I'm using a PostgreSQL database for my Django application. The race conditions seem to occur when multiple transactions attempt to update the balances of related accounts simultaneously. I've verified that the critical sections of my code are indeed encapsulated within … -
How to dynamically set urls in Django
I have a form that updates the quantity of a product or a custom order, i am currently using "{% if custom_orders %}{% url 'custom_order_update' item.custom_order.id %}{% else %}{% url 'update_bag' item.product_id %}{% endif %}" as the action URL, however Django is complaning with a redirect error for this syntax. Could anyone recommend another way to set the URL dynamically? -
Encountering file not found error in production
I hosted my django project on vercel, every static file is working correctly. django views.py function def view_pdf(request): file_path = os.path.join(settings.BASE_DIR, 'static', 'media', 'Shashank_Joshi_resume.pdf') with open(file_path, 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') instead of mimetype response['Content-Disposition'] = 'inline; filename="Shashank_Joshi_resume.pdf"' return response html template <div class="resume"> <input type="button" value="Resume" class="btn btn-primary" onclick="window.open('view_pdf')"> </div> error im getting FileNotFoundError at /view_pdf [Errno 2] No such file or directory: '/var/task/static/media/Shashank_Joshi_resume.pdf' But i have button in my html template by which a pdf file is shown when i click that its showing file not found error on vercel but when i run it locally its working totally fine. The github repo is also upto date. -
objects in object Django API
Why when I get all products in included_lessons instead of objects I receive only their ID, when I want to receive full object: id, name and so on. What I receive: [ { "id": 5, "author": "author", "name": "math product", "start_time": "2024-03-01T08:25:17Z", "min_users_in_group": 5, "max_users_in_group": 1, "included_lessons": [ 7, 8, 9 ] } ] What I want to receive: [ { "id": 5, "author": "author", "name": "math product", "start_time": "2024-03-01T08:25:17Z", "min_users_in_group": 5, "max_users_in_group": 1, "included_lessons": [ { "id": 1, "name": "some name", "something else": "something else" }, { "id": 2, "name": "some name 2", "something else": "something else 2" } ] } ] Model: class Product(models.Model): author = models.CharField(max_length=64) name = models.CharField(max_length=64) start_time = models.DateTimeField() min_users_in_group = models.IntegerField() max_users_in_group = models.IntegerField() included_lessons = models.ManyToManyField(Lesson, related_name='lessons') class Meta: db_table = 'product' def __str__(self): return self.name Serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' View model: class ProductApiView(viewsets.ReadOnlyModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer I tried to change queryset in API View model, but it is useless -
why this error shows when deploying a django projejct on verce;l
Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt ERROR: Ignored the following versions that require a different python version: 5.0 Requires-Python >=3.10; 5.0.1 Requires-Python >=3.10; 5.0.2 Requires-Python >=3.10; 5.0a1 Requires-Python >=3.10; 5.0b1 Requires-Python >=3.10; 5.0rc1 Requires-Python >=3.10 how do i fix the issue -
How to create a Django decorator that creates a signal for a model?
I want to create a custom decorator in Django that I can put on my model, and it creates a signal with my business logic. The logic is the same for each signal, the only thing changing is the model it is being attached to. I am having trouble understanding how to accomplish this. Given a model such as: class Post(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) title = models.CharField(max_length=100) I ideally would want a functionality with my decorator to put it on my model such as: @custom_signal_decorator() class Post(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) title = models.CharField(max_length=100) And it would create a signal such as this one: @receiver(post_save, sender=sender) def notify_created(sender, instance, created, **kwargs): channel_layer = channels.layers.get_channel_layer() group_name = f'notifications_{instance.company.id}' async_to_sync(channel_layer.group_send)( group_name, { "type": "notify_change", } ) The end goal is tracking changes in real time by sending a notification to the frontend when a new post is created. This all works when creating a signal by hand for each model, but I feel like a decorator would make more sense, to put on models we want to track. Any kind of input to how I would go about implementing this would be helpful, or another way that you think might work … -
Django 5.0.2: TypeError: Cannot filter a query once a slice has been taken
Why is this not working? I get the error "Cannot filter a query once a slice has been taken." What can I do to solve this? class LogbookLastViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = LogbookSerializer permission_classes = [permissions.IsAuthenticated] filterset_fields = ['organizationID'] def get_queryset(self): queryset = Logbook.objects.filter(organizationID='1111').order_by('-created')[:10] return queryset I need something like this: SELECT * FROM logbook WHERE organizationID='1111' ORDER_BY created LIMIT 10; -
Trying to iterate through numbers in a table rather than displayng all the values for each number in each cell
I am currently attempting to make a table which takes the lab number for a sample and returns the 'Value 2' of that number(I know it's a bad name but it's what I'm being made to work with) so far I can retrieve the data when a specific lab number is searched for, however if I just have a list of lab numbers in the table, it either displays as 'None' or it starts listing every lab number in order in each cell, as a dictionary. The code that isn't displaying the data properly: def GetValue2(self, _pageOfWorkflowCases): _resultsDict = {} for row in _pageOfWorkflowCases: LabNumber = row['LABNO'] with connection.cursor() as _cursor: _cursor.execute("{CALL dbo.uspShireXGetValue2(%s)}", [LabNumber]) _results = self.utilities.ConvertCursorListToDict(_cursor) if _results: _resultsDict[LabNumber] = _results.get['VALUE2'] return _resultsDict The code that displays a lab number when it's searched for: def GetValue2(self, _LabNumber): with connection.cursor() as _cursor: _cursor.execute("{CALL dbo.uspShireXGetValue2(%s)}", [_LabNumber]) _results = self.utilities.ConvertCursorListToDict(_cursor) if _results: _results = self.utilities.ConvertCursorListToDict(_cursor) return _results -
Django form fields don't appear in my html render page
i have a problem in my django project. Im quite new and im try to create a base form to create a new item in my database. this is forms.py from django import forms from .models import Progetto class Myprogetto(forms.ModelForm): class Meta: model = Progetto fields = ['nome', 'descrizione', 'data_inizio', 'data_fine'] this is my views.py from django.shortcuts import render,redirect from .models import Progetto from django.http import JsonResponse, HttpResponseRedirect from .forms import Myprogetto def aggiungi_progetto(request): if request.method == "POST": form = Myprogetto(request.POST) if form.is_valid(): nome = form.cleaned_data['nome'] Myprogetto_object=form.save(commit=False) Myprogetto_object.save() return HttpResponseRedirect("/thanks/") else: form = Myprogetto() return render(request, 'lista_progetti.html', {"form": form}) this is my lista_progetti.html <form id="popUpForm" display="none" action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Salva"> </form> the problem is that when i lauch the server the form appear empty with just the button <salva>. I added a screenshot. my form view in html render Anyone can help me? Thank you i tried to use both forms.ModelForm class and forms.Form class but the result is the same. I also try to write a simple form in html using html syntax and the fields appears but then i have problems in django to send the data to database cause it … -
Troubles with postgres while building docker container
I am trying to lauch DJANGO + POSTGRES inside a single container with DOCKERFILE. I have the folowing dockerfile which basicly installs all the python dependencies and postgresql. Then it lauches the script to create db and user (presented below). FROM python WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . RUN apt update && apt -y install postgresql postgresql-contrib RUN service postgresql start && su -c "bash config.db.bash" postgres WORKDIR /app/psql RUN python manage.py makemigrations && python manage.py migrate #Error EXPOSE 8000 CMD service postgresql start && python manage.py runserver 0.0.0.0:8000 Here is the script "config.db.bash" #!/bin/bash psql <<-INPUT CREATE USER docker; ALTER USER docker WITH PASSWORD 'password'; CREATE DATABASE docker; GRANT ALL PRIVILEGES ON DATABASE docker TO docker INPUT requirements.txt asgiref==3.7.2 Django==5.0.2 sqlparse==0.4.4 tzdata==2024.1 psycopg2 Here is the DJANGO`s settings.py -> Database config (psycopg_2 module installed) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "docker", "USER": "docker", "PASSWORD": "password", "HOST": "localhost", "PORT": 5432, } } It works just fine until this line RUN python manage.py makemigrations && python manage.py migrate Then docker says that error occured during this operation. Log basicly says that DJANGO cant connect to postgress DB. > [9/9] RUN python manage.py … -
make a choice list from a field into other field through the Foreign key Django
I have two models connected with foreign key with each other as below : class Service(models.Model): title = models.CharField(max_length=100) counter = models.PositiveIntegerField() def __str__(self) -> str: return f'{self.title}' class Reservation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) turn = models.PositiveIntegerField() def __str__(self) -> str: return f'{self.user}' What I want to do is turn field in Reservation get option choices and choice values are from 1 to service.counter. service is the foreign key here. for example if counter in Service model is 5 the turn field in Reservation would be something like this : turn = models.PositiveIntegerField(choices=[1,2,3,4,5]). for loop won't work obviously :) . Should I create a property field or Meta class ? anyway, How can I change my field like this? Any help will appreciate and grateful. -
Python: Extract year from datetime.datetime.today().date()
I registered a date to system with dates that is in this format: DateRegistered = datetime.datetime.today().date() . So I want to get the number of user that registered this year. I used this: len(Applicant.objects.filter(DateRegistered=datetime.datetime.today().year)) But it returned 0. Is there other way on how to extract the year? -
Redirect error due to context being passed to template - Django
I am working on an e-commerce site using Django. I have encountered a problem which I can't think of a solution. My site processes normal products and custom orders. I have a view to update the quantity of custom orders and a separate view to update the products quantity. I am using a form with some template logic in the URL to decide which URL pattern I need depending if it is a custom order or a product. bag.html <form class="form" action="{% if custom_orders %}{% url 'custom_order_update' item.custom_order.id %}{% else %}{% url 'update_bag' item.product_id %}{% endif %}" method="POST"> {% csrf_token %} <div class="col-12"> <div class="form-group w-100"> <div class="input-group"> <div class="input-group-prepend"> <button class="btn btn-main rounded-0 decrement" id="decrement_{{item.product.id}}" data-product_id="{{ item.product.id }}"> <span class="icon"> <i class="fa-sharp fa-solid fa-less-than"></i> </span> </button> </div> <input class="form-control quantity" type="number" name="quantity" value="{{item.quantity}}" min="1" max="50" id="quantity_{{item.product.id}}" data-product_id="{{ item.product.id }}"> <div class="input-group-append"> <button class="btn btn-main rounded-0 increment" id="increment_{{item.product.id}}" data-product_id="{{ item.product.id }}"> <span class="icon"> <i class="fa-sharp fa-solid fa-greater-than"></i> </span> </button> </div> </div> </div> </div> <button class="btn btn-main btn-sm rounded-0 mt-2"> Update </button> </form> If i add normal products to the bag application and then add a custom order i get a redirect error stating: Reverse for 'custom_order_update' with arguments '('',)' not … -
How can I call a function from within a Javascript fetch event?
I'm trying to call startTimer() from within the Javascript fetch().then() call, but it isn't going through. How can the fetch() see the startTimer() function and execute it? This happens even when I create an empty test() function that simply prints to console, so I know it isn't related to the code within the startTimer() function. <script> $(document).ready(function(){ function startTimer(duration, display) { var timer = duration, minutes, seconds; const interval = setInterval(function () { minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); // minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) { clearInterval(interval); } }, 1000); } }); const form = document.querySelector('#data'); form.addEventListener('submit', (event) => { event.preventDefault(); var subject = $("#subject").val(); var sender = $("#sender").val(); var email = $("#email").val(); fetch('', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ 'csrfmiddlewaretoken': document.querySelector('[name=csrfmiddlewaretoken]').value, 'subject': subject, 'sender': sender, 'email': email }) }) .then(response => response.json()) .then(data => { const filename = data.filename; const email = data.email; startTimer(60, document.querySelector('#timer')); var msg = `Your ${filename} was sent successfully to ${email}!`; alert(msg); }) .catch(error => { …