Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-filter compose filtered url
I'm using django-filter and I would like to link to the view with a pre-set filter. At this time, I'm doing like this: <a href='{{ url "order_list" }}/?year=2023'> or urlnext = ( reverse('order_list') + "?year=2023" ) return HttpResponseRedirect(urlnext) I would like to know if exists a more elegant approach. Thanks -
Create an exe file from a Django project with pyinstaller
I have a problem with generating an .exe file from a Django project using PyInstaller. My goal is to start the Django development server and open the web browser to the homepage by running the file. For this purpose, I have created a file (start.py) that is supposed to start the server: import os import time import webbrowser from django.core.management import execute_from_command_line os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_test.settings") def run_server(): execute_from_command_line(["manage.py", "runserver"]) if __name__ == "__main__": run_server() I create the exe file using PyInstaller: pyinstaller start.py --onefile When I run the exe file (./dist/start), I get the following error: Traceback (most recent call last): File "start.py", line 19, in <module> run_server() File "start.py", line 16, in run_server execute_from_command_line(["manage.py", "runserver"]) File "django/core/management/__init__.py", line 442, in execute_from_command_line File "django/core/management/__init__.py", line 436, in execute File "django/core/management/base.py", line 412, in run_from_argv File "django/core/management/commands/runserver.py", line 74, in execute File "django/core/management/base.py", line 458, in execute File "django/core/management/commands/runserver.py", line 111, in handle File "django/core/management/commands/runserver.py", line 118, in run File "django/utils/autoreload.py", line 673, in run_with_reloader File "PyInstaller/hooks/rthooks/pyi_rth_django.py", line 24, in _restart_with_reloader File "django/utils/autoreload.py", line 272, in restart_with_reloader File "django/utils/autoreload.py", line 229, in get_child_arguments IndexError: list index out of range When I run the start.py file, the server can be started without any … -
Integrating my Django REST API based extension into OpenedX container
I made a django extension according to these details:"Stand up an instance of Open edX using either the Dockerized Tutor release or our https://gallery.ecr.aws/ibleducation/ibl-edx-ce (architected using Tutor). Develop an extension that exposes a REST API endpoint and saves a greeting from the user (secure this endpoint with OAuth2 in the same way that Open edX secures its other API endpoints). This endpoint should do the following things with the user-submitted greeting: Log it (it should be visible in the platform’s LMS logs). Save it in the database (the greeting should be visible from the Django Admin). If the greeting is “hello”, then the view of this API endpoint should call the original greeting endpoint again with “goodbye” as the parameter. This is to make sure that you can write an Open edX view that can make an OAuth2-secured API call with a client ID, a client secret and an access token. Of course, if your code calls this endpoint with “hello” again then it’ll be recursive and things will crash." And now the steps where OpenedX is involed are left only please someone guide me through it. I created a docker container using the image link provided above now I … -
django passing variable to javascript in html template
I was trying to pass a variable to my html template in my django project and I can't seem to find a solution to why it doesn't work. The input of username_list: ['name1', 'name2'] back end: username_list = [user.username for user in User.objects.all()] return render(response, "main/main-page.html", {"list": username_list}) template: <script> let availableKeywords = {{ list }}; console.log(availableKeywords); </script> The javascript won't run and I don't understand if there is another correct way of doing it that I am not aware of. Can't figure it out. Thanks for the help! -
How to schedule tasks with Celery in Django based on a model field and update them dynamically?
I've encountered a challenge while developing an application with Django and using Celery to schedule tasks based on a model field. I'd like to share my solution and seek advice on potential improvements. As a relatively inexperienced developer, I welcome any guidance. I'm working on a Django application for managing training courses, and I need to schedule tasks when a registration deadline is reached. I've implemented Celery for task scheduling and store task IDs in a model field to allow for revocation if necessary.My challenge is ensuring that when the registration deadline is changed, the scheduled task is also updated or executed if the deadline has passed. from datetime import datetime from celery.result import AsyncResult from django.db import transaction from django.db.models.signals import post_save, pre_delete, pre_save from django.dispatch import receiver from django.shortcuts import get_object_or_404 from django.utils import timezone from .models import Training from .tasks import post_registration_deadline def delay_and_assign_registration_deadline_task(training_id): """ The post_registration_deadline notifies the members of the training manager group if the minimum number of candidates is not reached. If there is still some registrations to review, they are canceled with the reason "REGISTRATION_DEADLINE_PASSED". """ training = get_object_or_404(Training, id=training_id) task_id = post_registration_deadline.delay(training.id).task_id training.registration_deadline_task = task_id training.save() @receiver(pre_save, sender=Training) def pre_save_training(sender, instance, **kwargs): … -
how can redirect to another page when if statement is true in django template?
I have a HTML page that displays some information retrieved from database, in this template i have if statement when it is return True, it must be redirect to another page, here is my HTML Page: Communications.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> {% load bootstrap5 %} {% bootstrap_css %} <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous"> <style> label{ font-size: 18px; } </style> </head> <body> <table id="tblToExcl" class="table table-striped table-bordered table-sm"> <thead class="thead-dark"> <tr> <th>Day</th> <th>From</th> <th>To</th> <th>Name Lecturer</th> <th>Lesson</th> <th>Lab</th> </tr> </thead> <tbody> {% for table in tables %} <tr> <td>{{ table.day }}</td> <td>{{ table.strt_lec }}</td> <td>{{ table.end_lec }}</td> <td>{{ table.name_lecurer }}</td> <td>{{ table.name_lesson }}</td> <td>{{ table.lab }}</td> {% if table.comm_time_compare%} <p>time is equal</p> {% else %} <p> time is not equal</p> {% endif %} </tr> {% endfor %} </tbody> </table> </body> </html> models.py: class Communications(models.Model): day = models.CharField(max_length=20) strt_lec = models.CharField(max_length=20) end_lec = models.CharField(max_length=20) name_lecurer = models.CharField(max_length=40, choices=LECTURER_NAME_Comm) name_lesson = models.CharField(max_length=70, choices=LESSONS_Comm) lab = models.CharField(max_length=20, choices=LAB_NAMES_Comm) @property def comm_time_compare(self): current_time = time.strftime("%I:%M") if current_time == self.strt_lec: return True else: return False urls.py: from django.urls import path from . import views from django.views.generic import TemplateView urlpatterns = [ path('members/', views.members, name='members'), path('', views.index, name='index'), path('Communications', … -
Gateway timeout(504) in django application
I've built a website in django and hosted it on vercel. However if the website stay inactive for 5-10 mins I get a 504 error. I'm not sure why it is happening. Any suggestions on how to fix this issue will be really helpful? -
"I'm having trouble with my Django 'delete' function in customer registration. It doesn't delete as expected. Can you review and advise? Thanks!"
"I'm working on a Django project for customer registration, and I'm encountering an issue with the 'delete' function. When I try to delete a customer's information, it doesn't work as expected. Can someone please review my 'delete' function and suggest any corrections or improvements? Thank you!" This my view.py code block. from . models import Customer from django.contrib import messages def cutomer_registration (request): message = '' data = '' number = 0 if 'ok' in request.POST: name = request.POST['name'], surname = request.POST['surname'], email = request.POST['email'], phone = request.POST['phone'] if name and surname and email and phone: if Customer.objects.filter(email=request.POST['email']).exists(): message = "This email already exists." elif Customer.objects.filter(phone=request.POST['phone']).exists(): message = "This phone already exists" else: save_data = Customer( name = request.POST['name'], surname = request.POST['surname'], email = request.POST['email'], phone = request.POST['phone '], note = request.POST['note'] ) save_data.save() message = "Customer registration was successful." else: message = "Fill in the appropriate boxes" data = Customer.objects.all().order_by('-id') number = Customer.objects.count return render(request, 'registration_m.html', {'message' : message, 'data' : data, 'number' : number}) def del(request, id): if 'delete' in request.POST: customer = Customer.objects.get(id=id) if 'yes' in request.POST: customer.delete() else: return redirect('registration') return render(request, 'registration_m.html', {'customer' : customer}) This my html code block. <h2>Customer Registration</h2> <form method="post"> {% … -
How to generate one json into two json?
I have the following fixture from a Django project: [ { "model": "music", "pk": 1, "fields": { "attributed_to": false, "creator": null, "name": "Piano Trio No. 1", "name_en": "Piano Trio No. 1", "name_de": "Trios für Pianoforte, Violine und Violoncello, Nr. 1", "dedicated_to": "Prince Karl Lichnowsky", "piece_type": "Trio", "category": "Chamber Music", "date_start": "1792-01-01", "date_completed": "1794-01-01", "key": "e-flat major" }, { "model": "music", "pk": 2, "fields": { "attributed_to": false, "creator": null, "name": "Piano Trio No. 2", "name_en": "Piano Trio No. 2", "name_de": "Trios für Pianoforte, Violine und Violoncello, Nr. 2", "dedicated_to": "Prince Karl Lichnowsky", "piece_type": "Trio", "category": "Chamber Music", "date_start": "1792-01-01", "date_completed": "1794-01-01", "key": "G major" }, { "model": "music", "pk": 3, "fields": { "attributed_to": false, "creator": null, "name": "Piano Trio No. 3", "name_en": "Piano Trio No. 3", "name_de": "Trios für Pianoforte, Violine und Violoncello, Nr. 3", "dedicated_to": "Prince Karl Lichnowsky", "piece_type": "Trio", "category": "Chamber Music", "date_start": "1792-01-01", "date_completed": "1794-01-01", "key": "c minor" } ] Due to a restructure of the app, I need to spilt/sort various columns of this fixture/json into two separate fixture/jsons. The two new fixture/json files should look like this: Fixture #1 [ { "model": "music", "pk": 1, "fields": { "creator": null, "name": "Piano Trio No. 1", "name_en": "Piano … -
Can`t get the value of input Django
So i need to get the quantity of product and then add it to cart. I made an input field with quantity value and when i click 'add to cart' i want to send it to django view, but i get None type for some reason. Im using htmx for dynamic requests. views.py product = Product.objects.get(slug=slug) quantity = request.POST.get('quantity') print(quantity) productId = product.pid customer = request.user.customer product = Product.objects.get(pid=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) orderItem.quantity = quantity orderItem.save() if orderItem.quantity <= 0: orderItem.delete() html code <form method="post">{% csrf_token %} <div class="body-product__actions"> <div data-quantity class="body-product__quantity quantity"> <button data-quantity-minus type="button" class="quantity__button quantity__button_minus"></button> <div class="quantity__input"> <input data-quantity-value='True' autocomplete="off" type="text" name="quantity" value="1"> <!-- here is the input im trying to get --> </div> <button data-quantity-plus type="button" class="quantity__button quantity__button_plus"></button> </div> <button data-ripple type="submit" hx-get="{% url 'Add product page' product.slug %}" hx-trigger="click" class="body-product__add-to-cart button button_cart"><span class="_icon-cart-plus">Add to cart</span></button> <!-- This is the button that sends the htmx request --> <a href="#" class="body-product__cicil border-button border-button_cicil"> <img src="{% static 'mstore/img/icons/cicil.svg' %}" alt="cicil"> </a> </div> </form> I tried to get the value with post, get requests but the result is similar, i have similar code in my other project and it works perfect. -
Order save multiple times in Django online store
as I stated in the title, I have a problem where an order is saved multiple times in my online store, the more I go into the problem, the more I mess it up. I am pretty new at this and I need some assistance, thank you for taking the time to look at this hot mess. models.py: from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200, null=True) phone = models.IntegerField(null=True) def __str__(self): return str(self.first_name) + ' ' + str(self.last_name) class Product(models.Model): name = models.CharField(max_length=200) category = models.CharField(max_length=200, null=True, blank=True) price = models.IntegerField(default=1000, null=True, blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return str(self.id) + '.' + str(self.name) def display_in_euro(self): cents = str(self.price) return round(int(cents) / 100) @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) + '. ' + str(self.customer) @property def get_cart_total(self): order_items = self.orderitem_set.all() total = sum([item.get_total for item in order_items]) / 100 return total @property def get_cart_items(self): order_items = self.orderitem_set.all() quantity = sum([item.quantity … -
How use scalene for memory profiling in a django app
I am trying to find memory leak inside my django app but couldn't find a way in official docs of scalene or somewhere else about how can i use it with django. so far i have tried running runserver command like below $ scalene manage.py runserver and after that when i execute my regular view ( which i want to profile ). nothing happens. when i press ctrl + c it stops the runserver command & created a file profile.html ( around 25 MB size ) i open that file in chrome but it shows some benchmarks ( like expected ) but nowhere i saw my django view code which i want to profile. 😔 I just tried searching every where but couldn't find a way. -
Custom Exception Handler doesn't get invoked
I've been using custom exception handler to alter the default behavior while raising ValidationError, since i need to get user-friendly message in json instead 500 status code and html page. However, im faced with an issue, that handler does not even get invoked. The path to handler is specified correctly in settings.py: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'api.utils.exception_handler.handler', } Part of the handler function in exception_handler.py: def handler(exc, context): response = exception_handler(exc, context) ... Part of the post method in APIView class: def post(self, request, *args, **kwargs): serializer = UserMiniSerializer(data=request.data) if serializer.is_valid(raise_exception=True): ... Part of the Validate method of UserMiniSerializer: def validate(self, attrs): ... if not user.check_password(password): raise ValidationError({'password': 'Invalid password. Please, try again.'}) ... I've tried to handle ValidationError with try-except block in post method, however i think there is a better solution. Thanks. -
manytomany: ImportError: cannot import name '...' from partially initialized module '...' (most likely due to a circular import)
I'm facing this problem with a ManyToManyField in Django . Import Error: cannot import Room from partially initialized module. file contact.py: from django.db import models from accounting.models.account import Account class Contact(models.Model): id = models.BigAutoField(primary_key=True) last_name = models.CharField(max_length=255, blank=True, null=True) account = models.ManyToManyField(Account, through='contactaccount') file account.py from django.db import models from .accountgroup import AccountGroup from .accountclass import AccountClass class Account(models.Model): id = models.BigIntegerField(primary_key=True) code = models.IntegerField() class_account = models.ForeignKey(AccountClass, models.DO_NOTHING,default=0) group_account = models.ForeignKey(AccountGroup, models.DO_NOTHING,default=0) file contactaccount.py from django.db import models from accounting.models.account import Account from .contact import Contact class ContactAccount(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) contact = models.ForeignKey(Contact, on_delete=models.CASCADE) I can' find the solution -
Give access to add items only to admin created superuser
guys. Im new using django . I did this CRUD app ,and I want to give access to add items in to the app only to 'the admin superuser' created before.Can anyone explain me how to do that, sorry for my english another thing that I need to improve to. thanks . -
djngo account register match with Users app
One of the two apps I created in my Django project is accounts and the other is Users. Accounts allows users to register, log in and log out. The Users app creates a user page using their information. How can I import the information of the user registered in the Accounts app to the app in Users? how can I do some one if registered automatically create I new user in Users app how can I access this data -
Django TIME_ZONE and USE_TZ
In my project settings I have TIME_ZONE="Europe/Kiev" and USE_TZ=True. Problem description: if it is 12.00 in Kyiv, I will receive 9.00. How can I fix this? -
django and react integration without RestApi
please let me know can we use django with react without using RestApi. i want to get the answer that can we use django with react without using django-RestApi. gimme the solution please to how can i integrate without RestApi -
postgres database is not connecting while using with docker container on django application
enter image description here this is my .env file POSTGRES_READY=0 POSTGRES_DB=dockerdc POSTGRES_PASSWORD=mysecretpassword POSTGRES_USER=myuser POSTGRES_HOST=localhost POSTGRES_PORT=5434 this is my docker-compose.yaml file version: "3.9" services: postgres_db: image: postgres restart: always command: -p 5434 env_file: - web/.env expose: - 5434 ports: - "5434:5434" volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: i think this part is having issue on this part postgres_db: image: postgres restart: always command: -p 5434 env_file: - web/.env expose: - 5434 ports: - "5434:5434" volumes: - postgres_data:/var/lib/postgresql/data/ The docker-compose.yaml file you provided seems mostly correct, but there is a minor issue with the command field for the postgres_db service. The value for command should be specified as an array of strings, but you have used a single string with a leading hyphen ( Here's the corrected docker-compose.yaml file: -
New session is creating every time I visit the cart. Django REST Framework
I want 1 session for 1 anonymous user. The thing is, every time I enter cart endpoint, session does not save. Cookie sessionid is creating only when I log in to admin panel. # views.py in cart app def get_or_create_cart(request): if request.user.is_authenticated: token, created = Token.objects.get_or_create(user=request.user) cart, _ = Cart.objects.get_or_create(user_token=token) else: if not request.session.session_key: request.session.create() session_key = request.session.session_key print(session_key) cart, _ = Cart.objects.get_or_create(session_key=session_key) cart.session_key = session_key cart.save() return cart @api_view(['GET', 'POST', 'PUT', 'DELETE']) def cart_view(request): cart = get_or_create_cart(request) if request.method == 'GET': cart_items = CartItem.objects.filter(cart=cart) serializer = CartItemSerializer(cart_items, many=True) return Response(serializer.data, status=status.HTTP_200_OK) ... # settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], } SESSION_ENGINE = "django.contrib.sessions.backends.db" SESSION_COOKIE_NAME = "sessionid" SESSION_COOKIE_SECURE = False SESSION_SAVE_EVERY_REQUEST = True``` -
How to config django to support bulk_create with mysql upsert?
I checked MySQL with follow SQL: INSERT INTO extras (`date`, `code`, `is_st`) VALUES ('2013-01-04', '000001.XSHE', 0) ON DUPLICATE KEY UPDATE is_st = 1; But when call MyModel.objects.bulk_create, it reports error: django.db.utils.NotSupportedError: This database backend does not support updating conflicts with specifying unique fields that can trigger the upsert. -
missing files at django-admin startproject
I am learning Django & when following through I can create the startup project however it only brings one file.. so I cannot continue to start the Django development server. These are the instructions I followed so far: How do I recreate those missing files as depicted in the instructions' tree . Please assist -
Data missing (files) in my django serializer
I have an issue, some data are missing in my serializer (in validate and create functions). My Model: class PostsImage(models.Model): image = models.ImageField(upload_to="posts/images") post = models.ForeignKey( "socialmedia.Post", on_delete=models.CASCADE, related_name="posts_images" ) class Meta: verbose_name = "PostsImage" verbose_name_plural = "PostsImages" def __str__(self): return self.image class PostsAttachedFile(models.Model): attached = models.FileField(upload_to="posts/attached") post = models.ForeignKey( "socialmedia.Post", on_delete=models.CASCADE, related_name="posts_attached_files", ) class Meta: verbose_name = "PostsAttachedFile" verbose_name_plural = "PostsAttachedFiles" def __str__(self): return self.attached class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() business_sector = models.CharField(max_length=50, choices=BUSINESS_SECTOR_CHOICES) author = models.ForeignKey( "users.User", on_delete=models.CASCADE, related_name="posts" ) created_at = models.DateTimeField(auto_now_add=True) valid_until = models.DateTimeField() location_type = models.CharField(max_length=20, choices=LOCATION_CHOICES) location = models.CharField(max_length=255) location_radius = models.PositiveIntegerField(null=True, blank=True) class Meta: verbose_name = "Post" verbose_name_plural = "Posts" def __str__(self): return self.title My serializer: class PostSerializer(serializers.ModelSerializer): images = PostsImageSerializer(many=True, source="posts_images", required=False) attached_files = PostsAttachedFileSerializer( many=True, source="posts_attached_files", required=False ) class Meta: model = Post fields = "__all__" def validate(self, attrs): print(attrs) author = attrs.get("author") location_type = attrs.get("location_type") location_radius = attrs.get("location_radius") valid_until = attrs.get("valid_until") user = self.context["request"].user if author and author != user: raise serializers.ValidationError( {"author": "You can't create post for another user"} ) if location_type == "local" and not location_radius: raise serializers.ValidationError( { "location_radius": "You must provide location radius if location type is local", } ) if valid_until and … -
how should i make a button a link without losing the appearances?
I have been given a series of button elements which i have to change them into links But they lose their appearances when i put them inside a element. how should i turn these buttons into links? an example is the below button <a href="{% url 'blog:post-detail' post.slug %}" class="text-decoration-none"> <button> read more </button> </a> the main purpose of these buttons is to navigate in pages and i can not replace them entirly with links -
Are there any alternatives to PyInstaller for making standalone Python Executables or Linux Libraries
Everyone recommends pyinstaller, but I'd like to: Create the C version of the python code (including all dependent modules). In a simple script. Compile this C version into an executable or library. Call it wherever I want. For example, on linux. With this I want to gain more speed in the execution of the code because it will be compiled machine code and not interpreted. A pseudo-code to example: import numpy as np # Create two matrices matrix_A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) matrix_B = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]]) # Compute the dot product dot_product = np.dot(matrix_A, matrix_B) print("Dot Product of Matrix A and Matrix B:") print(dot_product) # Compute the transpose of the resulting matrix transpose_result = np.transpose(dot_product) print("\nTranspose of the Dot Product:") print(transpose_result) I did a few searches but all of them landed on the PyInstaller option.