Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Long running Django Celery task close DB connection
I have a Django Celery task that performs long-running operations and sometimes loses connection to the database (Postgres). the task looks like something like this: @app.task(name='my_name_of_the_task') def my_long_running_task(params): with transaction.atomic(): object_list = self.get_object_list_from_params(params) for batch in batches(object_list): self.some_calculations() MyObject.objects.bulk_create(objs=batch) # <- here connection could be lost I want to ensure the connection (but also be able to unit test this code). For example: @app.task(name='my_name_of_the_task') def my_long_running_task(params): with transaction.atomic(): object_list = self.get_object_list_from_params(params) for batch in batches(object_list): connection.connect() self.some_calculations() MyObject.objects.bulk_create(objs=batch) # <- here connection could be lost This would work (because it always opens new connections) but the unit test throws the error that can't roll back on teardown. I am thinking about @app.task(name='my_name_of_the_task') def my_long_running_task(params): with transaction.atomic(): object_list = self.get_object_list_from_params(params) for batch in batches(object_list): try: self.some_calculations() MyObject.objects.bulk_create(objs=batch) # <- here connection could be lost except Exception e: connection.connect() MyObject.objects.bulk_create(objs=batch) # retry this insert but is there a better way to handle this? -
Does nest js provide anything that runs after saving, updating or deleting, like how django signals provides?
I am running a project with nest js and prisma orm. Suppose I am creating a post record like following: // Query the database to create post ------------------------------------------------------- try { post = await this.prisma.post.create({ data: { uuid: uuidv4(), author: createPostDto.author, categoryId: postCategory.id, title: createPostDto.title, content: createPostDto.content, createdAt: new Date(), updatedAt: new Date(), } }) } catch (err) { this.logger.error(err); throw new InternalServerErrorException("Failed to create the post"); } After creating a record I want to run some perticular code. suppose I want to send notification to admins by calling sendNotification() method. But I don't want to call this method from inside an api. I know that django signals provide similar feature that can be used to run some part of code after creating, updating, or deleting a row. But I don't know what should be aprropeiate in the case of nest js. -
Django program gets stuck on get request, needs to be interrupted with Ctrl C to continue
I have tried everything I can possibly think of but I don't know what the solution is. I have a django application which running on my local network and receives requests from a react app. When the page loads tables (around 10 requests) the server seems to work quite well but randomly gets hung. When it gets hung it doesn't reach the view (the print statement doesnt run: def f(request): start_time = time.time() print('Received GET request')) and the moment I interrupt it a backlog of get requests like: Received GET request <WSGIRequest: GET '/api> Received GET request <WSGIRequest: GET '/api> Received GET request <WSGIRequest: GET '/api> Received GET request <WSGIRequest: GET '/api> Received GET request <WSGIRequest: GET '/api> which print in one go and then all the remaing requests are filled. Sometimes the requests with large responses crash, but sometimes even '/' hangs which only returns a hello world for me to test the server I am using a conda environment with some: asgiref 3.7.2 pyhd8ed1ab_0 conda-forge django 4.2.7 pyhd8ed1ab_0 conda-forge django-cors-headers 4.3.1 pyhd8ed1ab_0 conda-forge django-silk 5.0.4 pyhd8ed1ab_0 conda-forge djangorestframework 3.14.0 pyhd8ed1ab_0 conda-forge memory_profiler 0.58.0 pyhd3eb1b0_0 numexpr 2.8.7 py310h2cd9be0_0 pip 23.3.1 py310haa95532_0 pyodbc 4.0.39 py310hd77b12b_0 python 3.10.13 he1021f5_0 sqlite 3.41.2 … -
Setting value for template variable in django
I am using a for loop in django template. My logic is based on the previous value of item in the for loop. This is for comparing the previous value of that item with current value of the item, while the for loop iterate. Below mentioned is my requirement. Can anybody please help me with this code in django. Note: I am NOT using jinja, only django. Thanks. {% set var_name=0 %} {% for name in employees %} {% if var_name != name %} <td> {{ name }} </td> {% varname=name%} {% else %} <td> </td> {% endif %} {%endfor%} -
Where to pass context data in Response (Django)
I am wondering how to pass some context data to response in Django. I have this endpoint: /api/facebook/user/ which returns data like this: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "facebook_account_id": "176890406129409", "first_name": "Ivan", "last_name": "K", "token_status": "active", "facebook_access_token": 1 }, { "facebook_account_id": "123123123", "first_name": "Ivan", "last_name": "FFFF", "token_status": null, "facebook_access_token": null }, { "facebook_account_id": "123123", "first_name": "Test", "last_name": "test", "token_status": null, "facebook_access_token": null } ] Here is my list serializer: class FacebookUserListSerializer(ModelSerializer): token_status = SerializerMethodField() class Meta: model = FacebookUser fields = ["facebook_account_id", "first_name", "last_name", "token_status", "facebook_access_token"] def get_token_status(self, obj): try: facebook_token = obj.facebook_access_token if facebook_token: return "active" if facebook_token.is_active else "inactive" except FacebookToken.DoesNotExist: return None Here is my list view: def list(self, request, *args, **kwargs): response = super().list(request, *args, **kwargs) data = response.data inactive_accounts = sum(1 for account in data if account.get("token_status") == "inactive") accounts_without_token = sum(1 for account in data if account.get("token_status") is None) context = {"inactive_accounts": inactive_accounts, "accounts_without_token": accounts_without_token} # Is this the correct way of passing context data to a response? response.context_data = context return response In list view, in the "context" variable, I am attempting to pass data to the frontend, but I am sure that I … -
Handling concurrent connections
I thought of implementing a game lobby (similar to chess.com). A player randomly paired with another player . I implemented this with a queue . When a new Request arrives , it checks queue and pairs to front element if any player exists in queue . Later I realized that this fails in real world as concurrent requests try to connect with same front element leading to various problems . My question is How real world game lobbies handle this problem ? Is there a way to Handle concurrent connections ? Any help is appreciated :) -
save method in django not saving data,field changes
i have tried all i think i should but my django model is not updating. The save() method is not working even though there seem not to be an error. #models.py class ApplicantDetails(models.Model): user = models.OneToOneField(User,null=True,blank=True, on_delete= models.SET_NULL,related_name='applicant') phone = models.CharField(max_length=200, null=True,blank=True) program = models.ForeignKey(Course,null=True,blank=True,on_delete= models.SET_NULL,related_name='courses') application_date =models.DateTimeField(auto_now_add=True,null=True,blank=True) nationality =CountryField(blank=False, null=False) passport_photo = models.FileField(upload_to="user_photo/", blank=True, null=True) #passport= models.CharField(max_length=200,choices=job_type_choices,null=True,blank=True) is_passport = models.BooleanField(default=False) is_credentials = models.BooleanField(default=False) is_address = models.BooleanField(default=False) is_emergency = models.BooleanField(default=False) is_worked_exp = models.BooleanField(default=False) is_additional = models.BooleanField(default=False) is_document = models.BooleanField(default=False) application_ID =models.CharField(max_length=200, null=True,blank=True) def __str__(self): user_name = self.user if self.user else "Unknown" user_first_name = self.user.first_name if self.user else "Unknown" user_last_name = self.user.last_name if self.user else "Unknown" return f"{user_name} {user_first_name} {user_last_name}'s Applicant Details" def save(self, *args, **kwargs): if not self.application_ID: nationality_prefix = self.nationality.code if self.nationality else '' phone_suffix = str(self.phone)[-4:] if self.phone else '' username_suffix = str(self.user.username)[:4] if self.user else '' uuid_part = str(uuid4())[:4] date_suffix = self.application_date.strftime('%y') if self.application_date else '' self.application_ID = nationality_prefix + phone_suffix + username_suffix + uuid_part + date_suffix super().save(*args, **kwargs) class Meta: verbose_name_plural='Applicant Details' class ApplicantPassport(models.Model): VISA_CHOICES = [(True, 'Yes'), (False, 'No')] user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='passport_detail') middle_name = models.CharField(max_length=200, null=False, blank=False) dob = models.DateField(null=True, blank=True) passport_num = models.CharField(max_length=200, null=False, blank=False) place_of_issue = models.CharField(max_length=200, null=False, blank=False) place_of_birth … -
How do i resolve django staff and student dashboard work
Please fellow programmers, can someone help me write a Django staff and student dashboard where registered students who are attached to a particular staff can receive YouTube video uploads from their teacher's dashboard into their dashboard? # myapp/models.py from django.db import models class Staff(models.Model): name = models.CharField(max_length=100) class Student(models.Model): name = models.CharField(max_length=100) staff = models.ForeignKey(Staff, on_delete=models.CASCADE) class Video(models.Model): title = models.CharField(max_length=100) url = models.URLField() student = models.ForeignKey(Student, on_delete=models.CASCADE) # myapp/views.py from django.shortcuts import render, redirect from .models import Staff, Student, Video from .forms import VideoUploadForm def staff_dashboard(request, staff_id): staff = Staff.objects.get(id=staff_id) students = Student.objects.filter(staff=staff) context = {'staff': staff, 'students': students} return render(request, 'staff_dashboard.html', context) def student_dashboard(request, student_id): student = Student.objects.get(id=student_id) videos = Video.objects.filter(student=student) context = {'student': student, 'videos': videos} return render(request, 'student_dashboard.html', context) def upload_video(request, student_id): student = Student.objects.get(id=student_id) if request.method == 'POST': form = VideoUploadForm(request.POST, request.FILES) if form.is_valid(): video = form.save(commit=False) video.student = student video.save() return redirect('student_dashboard', student_id=student.id) else: form = VideoUploadForm() context = {'form': form, 'student': student} return render(request, 'upload_video.html', context) # myapp/urls.py from django.urls import path from .views import staff_dashboard, student_dashboard, upload_video urlpatterns = [ path('staff/<int:staff_id>/', staff_dashboard, name='staff_dashboard'), path('student/<int:student_id>/', student_dashboard, name='student_dashboard'), path('student/<int:student_id>/upload/', upload_video, name='upload_video'), ] -
Handle React routes from django, in Django, React Web App
I'm developing a Full-Stack Web App using Python Django as Backend and React Js as a backend. And Django Rest Framework for APIs. Now i'm facing issue of restricting users to access only routes having permissions. I want to handle react routes and navbar from django so that users access routes according to permissions given to them. Kindly guide me how can i do it. I want to handle react routes and navbar from django so that users access routes according to permissions given to them. Kindly guide me how can i do it. -
Display Django Form Fields depending on option selected using Javascript
I am working on a Django Project and I have the following html page which renders a form. I do not know much of Javascript, and I think I am going wrong somewhere in the Javascript Function or something else entirely. What I need to do is render the "id_mapnubparam01" field only when value of "id_mapnubfunction" is 'GETDATA'. I've split the if condition into 2 just to be clear, the first if condition for the "p" tag works perfectly fine. However using the same if then else logic the "id_mapnubparam01" does not do anything. Any help is appreciated. Thanks. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Data</title> </head> <body> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="fieldWrapper"> <label>{{ field.label_tag }}</label> {{ field }} </div> {% endfor %} <input type="submit" value="Submit"> </form> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("id_mapnubfunction").value; if (x != 'GETDATA') {document.getElementById("demo").innerHTML = ""; } else {document.getElementById("demo").innerHTML = "You selected: " + x; } if (x != 'GETDATA') {document.getElementById('id_mapnubparam01').hide(); } else {document.getElementById('id_mapnubparam01').show(); } } </script> </body> </html> -
Ubuntu is not serving Static files from Django project. Getting Permission issue
I have a django project deployed on Ubuntu 23.04 and using nginx and gunicorn to serve the website. Static setting is defined as follows: STATIC_DIR=os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' if DEBUG: STATICFILES_DIRS = [ STATIC_DIR, ] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' We have Debug = False in Production. Gunicorn service [Unit] Description=gunicorn daemon Requires=opinionsdeal.socket After=network.target [Service] User=panelviewpoint Group=www-data WorkingDirectory=/home/panelviewpoint/opinionsdealnew ExecStart=/home/panelviewpoint/opinionsdealnew/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/opinionsdeal.sock \ opinions_deal.wsgi:application [Install] WantedBy=multi-user.target nginx file server { server_name opinionsdeal.com www.opinionsdeal.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/panelviewpoint/opinionsdealnew; } location / { include proxy_params; proxy_pass http://unix:/run/opinionsdeal.sock; } } SSL lines have been removed from nginx file in this code only but it is already there in server. I am using Django 4.2 and python 3.11 We are seeing that website HTML pages are being served but static files like js, css and images are not being served. I have deployed similar projects in past on ubuntu 20 and worked well but this time it is not working. I have given permission for static folder to all users. Please suggest if there is any solution. -
Is it possible to have a conditional statement distinguish which model a Python variable is coming from? [duplicate]
In my Django view I have 3 models and I want to do a conditional based on where a variable is coming from. I have tried... if (type(variable)) is ModelA: do this... If I do... print(type(variable)) it prints out '<class 'app.models.ModelA'>' But the conditional never kicks in. I'm not sure what I am missing. -
Django logon SSO through Active Directory without any actions with DC server
We are moving from Java-GWT-Tomcat on Python-Django-Apache. We have Active Directory and SSO mechanism as getting users member groups info. It's made with Waffle and it's doesn't require any server-side Kerberos keytab or adding service account in AD. Is there any way to do this with Python-Django-Apache? -
How to migrate database django from postgresql to mysql
Please help me, yesterday I switched providers to deploy my django website, in the old provider I used postgresql as the database, but in the new provider only supports mysql, so inevitably I have to migrate my database to mysql. For the database settings in my django project I have adjusted as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'achmadir_portfolio', 'USER': '**************', 'PASSWORD': ******************', 'HOST': 'localhost', 'PORT': '3306', } } I have previously backed up my database and I want to restore it in django on a new provider. But when I want to migrate in the terminal with : python manage.py migrate There is an error : django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'None) NOT NULL, `gambar` varchar(100) NOT NULL, `gambar2` varchar(100) NOT NULL,' at line 1") For information, I have included the code information in the models in the application that indicated the error which can be seen in the error information: from django.db import models from django.utils import timezone from django.utils.text import slugify # Create your models here. class Proyek(models.Model): ITEM_CHOICES = [ ('SQL', … -
Django : Using Onclick To Div With Scrolling ( Tab Menu )
I'm trying to create tab menu with scroll. My actual problem is, How to scroll to section by clicking the button? Smooth scroll to div id Is there a better way to do this? Thank you my code : html <section id="section_{{ html_component.title }}" class="card"> <div> <div> <h3>{{ html_component.title }}</h3> </div> </div> </section> <section id="section_{{ html_component.title }}" class="card"> <div> <div> <h3>{{ html_component.title }}</h3> </div> </div> </section> <nav class="menu__main"> <ul> {% for html_component in html_components %} <li> <a href="javascript:void(0);" onclick="ScrollTabMenu()"> <span>{{ html_component.title }}</span> </a> </li> {% endfor %} </ul> </nav> jquery function ScrollTabMenu (){ let TabMenu = $(`section_{{html_component.title}}`) }; Please tell me the best solution for jQuery or Javascript? -
how to correct the spacing of texts?
I made this blog but when I write a post in the write a new post page the spaces between the lines and all that is correct but when I post it and go to detail.html to see it it all just displays beneath each other with no space between the lines what should I do? if I need to post another page please let me know I appreciate your help new.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <form method="post"> <style> textarea { resize: none; } </style> {% csrf_token %} <div style="margin-top: 15px"></div> <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <div style="margin-top: 20px"></div> <button class="btn btn-outline-info" type="submit">Create</button> </div> </form> {% endblock %} detail.html {% extends "base.html" %} {% load static %} {% block content %} <html> <div style="margin-top: 20px"></div> <body class="text-center" style="line-height: 2;"> <article> <h1>{{post.title}}</h1> <p style="margin-top: 15px;">{{post.body}}</p> </article> </body> <div style="margin-top: 24px"></div> <a style="color: darkgray; font-size: 22px;"> <img src="{% static 'website/icons8-sparkles-25.png'%}"> Written by {{post.author}} <img src="{% static 'website/icons8-sparkles-25.png'%}"> </a> </html> {% endblock %} looks like this while writing looks like this when posted -
How can I add additional metadata into the django.server logs?
What I am trying to do is as given below, The current logs for the server requests look like the following. [29/Nov/2023 02:33:50] "GET /api/health/ HTTP/1.1" 200 31 The new format I need is as following. [29/Nov/2023 02:33:50] "GET /api/health/ HTTP/1.1" 200 31 user-id:<user_id> I tried to add a logs filter. "django.server": { "()": "django.utils.log.ServerFormatter", "format": "[%(asctime)s] %(levelname)s %(module)s %(message)s user_id:%(user_id)s ", } The following is my filter. class UserIdFilter(logging.Filter): def filter(self, record): user_id = None if hasattr(record, "request"): try: user_id = record.request.user.id except Exception as exp: user_id = "anon" if not user_id: user_id = "unknown" record.user_id = user_id return True The problem is the record object above is a socket.socket object and does not have any request http payload metadata. What could I do differently to find and append the request user_id to the logs? -
Django and staticfiles
I have a problem with Django static files. Let's assume, that the Django is configured to be server at www.example.com/app. When my configuration is: STATIC_URL = "/static/" MEDIA_URL = "/media/" STATIC_ROOT = "/home/hostxxx/domains/webpage.com/DjangoApp/static" MEDIA_ROOT = "/home/hostxxx/domains/webpage.com/DjangoApp/media" Then Django looks for: https://example.com/static/styles/style.css and it doesn't exist: GET https://example.com/static/styles/style.css net::ERR_ABORTED 404 (Not Found) but the file exists here: https://example.com/app/static/styles/style.css But when I change the static url: STATIC_URL = "/app/static/" Then it looks for a good url: https://example.com/app/static/styles/style.css but now the staticfile is available here: https://example.com/app/app/static/styles/style.css Update: urls.py: from django.contrib import admin from django.urls import path from mainapp import views urlpatterns = [ path("admin/", admin.site.urls), path("", views.lists, name="lists"), # MAIN VIEW ] but tried also this as urls.py: from django.contrib import admin from django.urls import path from django.contrib.staticfiles.urls import staticfiles_urlpatterns from mainapp import views urlpatterns = [ path("admin/", admin.site.urls), path("", views.lists, name="lists"), ] urlpatterns += staticfiles_urlpatterns() and base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>AAA</title> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" /> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" /> <link rel="stylesheet" href="{% static 'styles/style.css' %}"> # HERE ... The hosting use passenger_wsgi.py, which is: import imp import os import sys sys.path.insert(0, os.path.dirname(__file__)) wsgi = imp.load_source("wsgi", "app/wsgi.py") application = wsgi.application django-admin --version: 5.0 python --version: … -
Django Migration Error with PostGIS: 'double free or corruption (out) Aborted (core dumped)
I am developing a web application using Django and encountering a critical issue during database migration with PostGIS. While migrations work seamlessly with the SpatiaLite engine, switching to the PostGIS engine leads to a crash. The error message I receive is: "double free or corruption (out) Aborted (core dumped)". This issue arises specifically when I attempt to make migrations with the PostGIS engine. My Django project settings for the database are as follows: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geodesia_interoperable', 'USER': 'depiction', 'PASSWORD': '************', 'HOST': 'localhost', 'PORT': '5432', } } I have verified that PostgreSQL and PostGIS are correctly installed and configured, and the database credentials are accurate. The application runs as expected with SpatiaLite but fails when switched to PostGIS. Has anyone encountered a similar issue, or does anyone have insights into what might be causing this error with PostGIS in Django? Any suggestions for troubleshooting or resolving this problem would be greatly appreciated. -
React: 'map' function
I'm fetching a list of objects. Using map function should display a list but there wasn't. I checked if it was saved to 'useState' via console.log(posts), and yes there was a list of objects. My only problem is I cant display it to the browser. Also, I already attached the necessary scripts for 'react', 'reactDOM', and 'babel'. {% extends "network/layout.html" %} {% block body %} <div id="index"></div> <script type="text/babel"> const AllPosts = () => { const [posts, setPosts] = React.useState([]); React.useEffect(() => { fetch("/allposts") .then((response) => response.json()) .then((data) => { setPosts(data.posts); }) .catch((error) => { console.error(error); }); }, []); return ( <ul> {posts && posts.map((post, index) => { <li key={index}>{`Try ${index}`}</li>; })} </ul> ); }; const Index = () => { return <AllPosts />; }; const container = document.getElementById("index"); const root = ReactDOM.createRoot(container); root.render(<Index />); </script> {% endblock %} I wanted to return each object on the list in an li tag, however, there was no data when I inspected it on the browser. -
Django 5.0: How GeneratedField actually works?
I've read the Django documentation about the new models.GeneratedField, but I don't quite understand how it works inside a database. Can someone explain this? -
CannotPullContainerError: pull image manifest has been retried failed to resolve ref xxxxx.dkr.ecr.us-east-1.amazonaws.com/xxx-proxy:latest: not found
After reading through docs I still cant seem to resolve this myself. The proxy image does have the tag of "dev" which ive tried to add and was thrown a seperate error saying failed to normalize image. Currently using Fargate v1.4.0. I have a IAM CI user with given permissions for building/reading etc. variables.tf variable "ecr_image_proxy" { description = "ECR Image for API" default = "xxxxxx.dkr.ecr.us-east-1.amazonaws.com/xxxxxxxx-proxy:latest" } ecs.tf resource "aws_iam_role_policy_attachment" "task_execution_role" { role = aws_iam_role.task_execution_role.name policy_arn = aws_iam_policy.task_execution_role_policy.arn } resource "aws_iam_role" "app_iam_role" { name = "${local.prefix}-api-task" assume_role_policy = file("./templates/ecs/assume-role- policy.json") tags = local.common_tags } data "template_file" "api_container_definitions" { template = file("templates/ecs/container- definitions.json.tpl") vars = { app_image = var.ecr_image_api proxy_image = var.ecr_image_proxy django_secret_key = var.django_secret_key db_host = aws_db_instance.main.address db_name = aws_db_instance.main.db_name db_user = aws_db_instance.main.username db_pass = aws_db_instance.main.password log_group_name = aws_cloudwatch_log_group.ecs_task_logs.name log_group_region = data.aws_region.current.name allowed_hosts = "*" } } resource "aws_ecs_task_definition" "api" { family = "${local.prefix}-api" container_definitions = data.template_file.api_container_definitions.rendered requires_compatibilities = ["FARGATE"] network_mode = "awsvpc" cpu = 256 memory = 512 execution_role_arn = aws_iam_role.task_execution_role.arn task_role_arn = aws_iam_role.app_iam_role.arn volume { name = "static" } tags = local.common_tags } resource "aws_ecs_service" "api" { name = "${local.prefix}-api" cluster = aws_ecs_cluster.main.name task_definition = aws_ecs_task_definition.api.family desired_count = 1 launch_type = "FARGATE" platform_version = "1.4.0" network_configuration { subnets … -
customize django admin panel login view
I Want to do a little job when an admin wants to log into the admin panel. and that's it: I have a gateway service and I want from that gateway to handle authenticating of my users and just give me a token and then I handle them with the help of that token. now I'm confused how can I add my preferred logic alongside with all the default logic of handling authentication and logging admins into admin panel of django. I tried to override the default method, or even copy & paste that logic all by hand :/ thanks for any help or recom.. :) -
Django floatformat: no unnecessary zeros
Django's floatformat filter has a few options for formatting decimals. However, none of them work for what I consider the "standard" way to represent decimals in non-programming fields, like math or science. Specifically, I'd like decimals to be displayed with "as many decimal places as needed", up to a defined limit. Here are some examples with a limit of 3: The decimal What I want floatformat floatformat:3 floatformat:"-3" 15.000000 15 15 ✅ 15.000 ❌ 15 ✅ 15.666667 15.667 15.7 ❌ 15.667 ✅ 15.667 ✅ 15.550000 15.55 15.6 ❌ 15.550 ❌ 15.550 ❌ 15.500000 15.5 15.5 ✅ 15.500 ❌ 15.500 ❌ Tests passed: 2/4 1/4 2/4 The closest filter for my goal is probably {{ thing | floatformat:"-3" }}, and that's what I'm using right now. All I would like is to remove the "trailing zeros" from this filter's output. Thanks a lot! -
Cant import views django
I Tried importing app views into my url patterns but i get this error, using newest django version and python 3.11 File "C:\Users\IK959\mysite\mysite\urls.py", line 18, in <module> from chatapp.views import chat_view ImportError: cannot import name 'chat_view' from 'chatapp.views' (C:\Users\IK959\mysite\chatapp\views.py) this is my directory enter image description here and this is my code for my url pattern and my view urlpattern: from django.contrib import admin from django.urls import include, path from chatapp.views import chat_view urlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls), path('chat/', chat_view, name='chat'), ] chatapp view: from django.shortcuts import render def chat_view(request): return render(request, 'chatapp/chat.html') Ive tried the index but i do not know how to do it correctly