Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Login page
views.py def userhomepage(request): usersgmail_id = request.POST.get("user_gmail_id") userspassword = request.POST.get("user_gmail_pas") myslt = User.objects.filter( useremlid__contains=usersgmail_id, userpassword__contains=userspassword ) if myslt != "": return render(request, "UserHome.html") else: return render(request, "mylogin.html") I am making a login page using Django table. When no record match with the table of Django database I get "<QuerySet []>" in the "myslt" variable and when match any record than it displays the record no like "<QuerySet [<User: User object (2)>]>". I want to render "UserHome.html" page when record match with the table of Django. Otherwise render "mylogin.html" page. The problem here is that the above code always opens the "UserHome.html" page. When no record match than it also opens the "UserHome.html" page. I also used if myslt != "<QuerySet []>": in place of if myslt != "": but it has no effect. Is there a way to open "UserHome.html" page when record match and open "mylogin.html" page when no record match. -
How to send emails from django shell with AWS ses?
I have verified my domain with AWS SES and as a result my site successfully does send password verification emails (via allauth). I would, however, also like to be able to send emails based on local scripts. To do this I have been using django shell_plus: from django.core.mail import send_mail send_mail("It works!", "This will get sent through anymail", "me@mysite.com", ["me@mysite.com"]) I get output of '1' suggesting this the email has been sent successfully but I do not receive an email I think my config is correct given that the site does successfully send emails: EMAIL_BACKEND = "anymail.backends.amazon_ses.EmailBackend" ANYMAIL = { "AMAZON_SES_CLIENT_PARAMS": { "aws_access_key_id": AWS_ACCESS_KEY_ID, "aws_secret_access_key": AWS_SECRET_ACCESS_KEY, "region_name": "us-east-1", }, } Can anyone explain what I need to do to send emails from the terminal i.e. without being directly logged into an AWS server? -
Combine models to get cohesive data
Im writing app in witch I store data in separate models. Now I need to combine this data to use it. The problem. I have three models class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50, blank=True) ... class Contacts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") contact_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="contact_user") class UserPhoto(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) url = models.CharField(max_length=220) How can I get the current user contacts with their names and pictures like this (serialized) { { "contact_user":"1", "first_name":"Mark ", "url":first picture that corresponds to contact_user id }, { "contact_user":"2", "first_name":"The Rock", "url":first picture that corresponds to contact_user id } } Now im queering the Contacts model to get all contatcs_user id's that he has connection to class MatchesSerializer(serializers.ModelSerializer): class Meta: model = Contacts fields = '__all__' depth = 1 class ContactViewSet(viewsets.ModelViewSet): serializer_class = ContactsSerializer def get_queryset(self): return Contacts.objects.filter(user__id=self.request.user.id) -
How should I use localization and internationalisation on Django
I'm building a new bible website, using Django. I started with English and now I want to translate it to other languages like Spanish, Hebrew, etc. Here's the issue: The bible has many versions - King James bible, new international bible, etc. Each version can be in a few languages - like English, Spanish, etc. Here's the model I used for the default King James english bible: class verses (models.Model): id = models.IntegerField("ID",primary_key=True) book = models.CharField("Book",max_length=20,default=1) chapter = models.IntegerField("Chapter",default=1) verse = models.IntegerField("Verse",default=1) versetext = models.CharField("Versetext",max_length=550,default=1) title = models.CharField("Title",max_length=100,default=1) summary = models.CharField("Summary",max_length=550,default=1) id: a primary key for each verse book - the name of the book (in English). For example: Genesis chapter: the number of the chapter. For example: 1 verse: the number of the verse. For example: 2 versetext: the verse text. For example: In the beginning God created the heaven and the earth title: the title of the chapter (in English). For example: Creation summary: the summary of the chapter (in English). For example: In chapter 1 God creates the heaven and the earth... I want to achieve two things: A user should see a default language of the website, based on his location. Spain users should see the … -
Does DOMContentLoaded works in Django?
Trying to get my button working. Project is setup on Django, using pure JS. My JS script button.js: document.addEventListener('DOMContentLoaded', () => { const btn = document.getElementById('exchange-button'); console.log("Button: " + btn); // Button: nu;; if (btn) { btn.addEventListener('click', () => { console.log('btn clicked'); }); } else { console.log("Not Working") } }); And usage in html declared in head tag: <div> <button class="exchange-button">Get Exchange rate</button> </div> {% load static %} <script src="{% static 'js/button.js' %}"> </script> When Im checking if button exists, its not, the button is null and gettig same error all the time: Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at HTMLDocument. (button.js:5:7) Script is working perfectly when Im using pure html and js in other project. What am I doing wrong? Thanks for help -
Django DRF Djoser - change default User model to custom model which is not equal but inherited from AUTH_USER_MODEL
In django have the following custom user structure: class CinemaUser(AbstractUser): ... class CinemaAdmin(CinemaUser): .... class Cinemagoer(CinemaUser): ... Logic is that I have Cinemagoer - an ordinary user, CinemaAdmin - kind of administrator and superuser. Cinemagoer - can register themselves, CinemaAdmin is created only by superuser in settings: AUTH_USER_MODEL = CinemaUser the problem is with Djoser, a request http://localhost:8000/auth/users/ (with data in body) creates CinemaUser, because Djoser has User = get_user_model(), which means Djoser uses AUTH_USER_MODE, while I need Djoser to use Cinemagoer model to create Cinemagoer). How can I use Cinemagoer with Djoser in this case? I tried to change in Djoser/serializers directly User = CinemaUser ... just for test, it works fine, but it is definitely the wrong way. -
Django/Nginx - 403 on Static Files
I've recently uploaded a django project to an Ubuntu 22.04 DigitalOcean droplet. Nginx, gunicorn, and postgres have all been set up without a hitch, but the static files are all being 403'd. In both development and production, I never used collectstatic. The reason being, I always put all my static files in a static folder in the root of my project, so I figured I didn't have to do it. I'm not sure if collectstatic needs to be done in order for static files to be shown in production, but it seems that other people have still encountered this problem even when they've done collectstatic. My project on the server is called pyapps, and in that folder there are the static and media folders. The static folder is further broken down into css, js, and images folders. The media folder is further broken down into photos, then folder by year, month, then day, all of which correlate to the time the photos were uploaded. Below are my settings.py, urls.py and /etc/nginx/sites-available/ files' code. settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))] MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) /etc/nginx/sites-available/Car-terra … -
Test not found in github actions
I am trying to do an automated test. There should be 21 tests, but github-actions can't find them for some reason. https://github.com/duri0214/portfolio/actions/runs/4215160033/jobs/7316095166#step:3:6 manage.py is under mysite directory, so... (Below is when I run it on my local PC) (venv) PS D:\OneDrive\dev\portfolio\mysite> python manage.py test Found 21 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). : self.client.post(reverse('vnm:likes', kwargs={'user_id': 1, 'article_id': 99}), follow=True) AssertionError: ObjectDoesNotExist not raised ====================================================================== FAIL: test_post_click_good_button (vietnam_research.tests.test_views.TestView) ---------------------------------------------------------------------- OK Anyone know a solution? thanks -
Applying multiple validations to a field using Django REST framework
I want to check if a field in an incoming request body contains only a list of predefined integers. for example, given: valid_values=[2, 3, 8] [2, 8] should pass the validation and [4, 8] or ['2', 8] should raise a validation error. First I tried using serializers.ChoiceField() but it didn't raise any validation errors for ['2', 8]. also I have tried chaining validators but apparently it's not supported in Django REST framework. so this raised a TypeError: class MySerializer(serializers.Serializer): valid_rules = [2, 3, 8] tags = serializers.ListField(child=serializers.IntegerField().ChoiceField(valid_rules)) and I didn't found anything on the documentation either. -
Sign up function using django
i hope you are all doing great. I am currently working on a Django project. In views.py i did a function that handles registration. The user is an object from a class that django generated when i connected mysql to my django project. The request method in my form is set to POST but django doesnt execute it. It was working all good but suddenly i am getting a ValueError my function didnt return a HttpResponse. It returned None instead. The method in my html form is set to POST and the action attribute leads to the url ( {% url 'name_in_my_url_file %} -
Restful API Real-time order tracking
I design a api for a restaurant one of the features is that the user can make an order online and the oreder status is pending until the restaurant cashier or restaurant admin staff convert status by accept or refuse so i wanna create a notification or icons appears in client html page if there is pending orders or something that the admin staff or cashier know that there is an pending order created now without need to update or refresh the page , to decide if he accept the order or refuse it , so my question is how i make a html page show pending order without user refresh the page and may the page have some section to make order using restaurant staff or show current orders status i use django rest framework I hear about websocket and Django channels Also i hear about SSE Also i read about client freamwork send requests every n minute to update the page I need to know what the best approach to implement this and if there is another technology and what is best for server if there is a lot of loading or the application used by millions of … -
Django upload and process multiple files failing with libreoffice
I'm working on a Django application that works with excel files. It only works with xlsx files but if you upload an xls or an ods file I convert it previously to xlsx in order to work with that processed file. My application supports multiple file upload in the form. All files uploaded are uploaded successfully and saved into a model in Database with a field status = 'Created'. A post-save model function triggers a new Thread that process files for processing those files in background. After files are processed them are saved as status = 'Error' or status = 'Processed'. I have also added an extra option to reprocess files. The problem comes when I try to upload multiple files which are not xlsx those files need to be converted to xlsx before my own processing stuff. For that purpose I'm using libreoffice --convert-to xlsx filename --headless in a python subprocess. This is working fine with one or two file upload at the same time. But if I upload multiple files at the same time, some are failing and some files are being processed successfully, and there aren't any pattern with the files. All files for testing works properly … -
Unable to deploy Django/Docker/Nginx/Gunicorn/Celery/RabbitMQ/SSL on AWS Lightsail
I have been trying for more than a week few hours daily. Needless to say, I'm beginner in most of these things, but I have tried hundreds of configurations and nothing worked. That's why I am finally coming here for help. I am currently getting 502 Bad Gateway. My suspicion is that either Nginx can't find staticfiles or nginx upstream doesn't know what is web (in config). Nginx error logs are printing this: connect() failed (111: Connection refused) while connecting to upstream...upstream: "https://some-ip-address-here?:443" (this might be that nginx doesn't know about the web) Dockerfile # Pull base image FROM python:3.10.2-slim-bullseye # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Create and set work directory called `app` RUN mkdir -p /app RUN mkdir -p /app/staticfiles WORKDIR /app # Install dependencies COPY requirements.txt /tmp/requirements.txt RUN set -ex && \ pip install --upgrade pip && \ pip install -r /tmp/requirements.txt && \ apt-get -y update && \ apt-get -y upgrade && \ apt-get install -y ffmpeg && \ rm -rf /root/.cache/ # Copy local project COPY . /app/ COPY wait-for-it.sh /wait-for-it.sh RUN chmod +x /wait-for-it.sh docker-compose.yml version: '3.7' services: web: container_name: web build: . restart: always command: ["/wait-for-it.sh", "db:5432", "--", "gunicorn", … -
Django authorization through mobile application request
Is it possible with Django to authenticate users through a mobile app (enter login/password, then connect to the Django server and get some response)? I've tried to do something like that, but I can't figure out what to do next. Views.py def user_login(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponse(status=200) else: return HttpResponse(status=403) I used the extended User class, my Models.py class DiaUsers(AbstractUser): middle_name = models.CharField(blank=True, max_length=150) birth_date = models.DateField(blank=True, null=True) weight = models.FloatField(blank=True, null=True) height = models.FloatField(blank=True, null=True) attending_doctor = models.CharField(max_length=150, default="Toivo Lehtinen") app_type = models.CharField(max_length=150, default="Dia I") Serializer.py class DiaUsersSerializer(serializers.ModelSerializer): class Meta: model = DiaUsers fields = ['id', 'username', 'email', 'password', 'first_name', 'last_name', 'middle_name', 'birth_date', 'weight', 'height', 'attending_doctor', 'app_type', 'last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined'] Admin.py admin.site.register(DiaUsers, UserAdmin) admin.site.unregister(Group) -
RelatedObjectDoesNotExist at CustomUser has no student
i'm trying to filter logbook report based on the logged in industry supervisor, the supervisor should be able to see the report of students under his supervision views.py class LogbookEntryView(ListAPIView): queryset = LogbookEntry.objects.all() serializer_class = StudentLogbookEntrySerializer def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) request = self.request user = request.user if not user.is_authenticated: LogbookEntry.objects.none() return qs.filter(student_id__industrysupervisor = request.user.student.industry_based_supervisor) models.py LogbookEntry Model class LogbookEntry(models.Model): week = models.ForeignKey("api.WeekDates", verbose_name=_("Week Id"), null=True, on_delete=models.SET_NULL) student = models.ForeignKey("students.Student", verbose_name=_("Student Id"), on_delete=models.CASCADE) entry_date = models.DateTimeField() title = models.CharField(_("Title"), max_length=50) description = models.CharField(_("Description"), max_length=1000) diagram = models.ImageField(_("Diagram"), upload_to=profile_picture_dir) Student Model class Student(models.Model): user = models.OneToOneField(get_user_model(), null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(_("profile picture"), upload_to=profile_picture_dir) department_id = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL) phone_no = models.CharField(max_length=11) school_based_supervisor = models.ForeignKey("school_based_supervisor.SchoolSupervisor", verbose_name=_("School Supervisor"), null=True, on_delete=models.SET_NULL) industry_based_supervisor = models.ForeignKey("industry_based_supervisor.IndustrySupervisor", verbose_name=_("Industry Supervisor"), null=True, on_delete=models.SET_NULL) placement_location = models.ForeignKey("industry_based_supervisor.PlacementCentre", verbose_name=_("Placement Location"), null=True, blank=True, on_delete=models.SET_NULL) Industry Supervisor Model class IndustrySupervisor(models.Model): user = models.OneToOneField(get_user_model(), null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(_("profile picture"), upload_to=profile_picture_dir) phone_no = models.CharField(max_length=11) placement_center = models.ForeignKey("industry_based_supervisor.PlacementCentre", verbose_name=_("Placement Centre"), null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.user.username -
How to update multiple instance of a model
I am working on a project whereby user are able to apply to borrow book from a Libray. Whenever a user apply to borrow a book or books, an instance of the model PendingRequest is automatically created using a post_save function in signals.py. What i want to achieve is to be able to filter and update all the instance of the PendingRequest model by user. models.py class PendingRequest(models.Model): book_request = models.ForeignKey(Borrow, on_delete=models.CASCADE, null=True) member = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True) book = models.ForeignKey(Books, on_delete=models.CASCADE, default=None, null=True) approved = models.BooleanField(default=False) not_approved = models.BooleanField(default=False) approval_date = models.DateTimeField(auto_now=True, null=True) What i want to achieve specifically is to be able to approve the request and if the request isn't approved, not_approved will be True in database. -
how redirect user with stripe react component and django
I would like to redirect my user after he has made a payment (successful or failed) to a page automatically. Currently, the payment is going well, the update is a success on stripe and I manage to retrieve the necessary information with my django view. However, after successful payment, no redirection takes place. There are several documentation but I can't find a way to do it with the react component proposed by stripe themselves. How can I proceed? here is my work Offers.js : ReactComponent by Stripe <stripe-pricing-table pricing-table-id="prctbl_<my_pricing_table_key>" publishable-key="pk_test_<my-stripe-public-key>" // user informations for update subscriptions django model customer-email={`${info_user.info_user.email}`} client-reference-id={`${info_user.info_user.id}`} > </stripe-pricing-table> When I click on the subscribe button, everything is fine. the payment is made on stripe and I retrieve the information in my webhook with django views.py class StripeWebhookView(APIView): permission_classes = [] authentication_classes = [] helpers = AbonnementHelpers updating = UpdateAbonnementHelpers def post(self, request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] endpoint_secret = STRIPE_WEBHOOK_SECRET # webhook try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: return Response(status=status.HTTP_400_BAD_REQUEST) except stripe.error.SignatureVerificationError as e: return Response(status=status.HTTP_400_BAD_REQUEST) # full session data recovery if event['type'] == 'checkout.session.completed': info_event = self.helpers().stripe_event(event) user = UserAccount.objects.get(id=info_event['user_id']) # check if user subscription exist in my … -
Please help me sort the products in the django online store
How to sort the goods in the online store so that you can click on the button and the sorting has changed, for example: price,-price. And to views.py was in class, not in def. views.py class SectionView(View): def get(self, request, *args, **kwargs): sort_form = request.GET.getlist('sort') products = Product.objects.filter(available=True) if sort_form.is_valid(): needed_sort = sort_form.cleaned_data.get("sort_form") if needed_sort == "ДТ": products = products.order_by( "created") # или updated в зависимости от того, что ты вкладываешь в понятие по дате elif needed_sort == "ДЕД": products = products.order_by("price") elif needed_sort == "ДОД": products = products.order_by("-price") return render( request=request, template_name='main/index.html', context={ 'products':products, } ) forms.py class SortForm(forms.Form): sort_form = forms.TypedChoiceField(label='Сортировать:', choices=[('ПУ', 'По умолчанию'), ('ДТ', 'По дате'), ('ДЕД', 'От дешевых к дорогим'), ('ДОД', 'От дорогих к дешевым')]) index.py <form action="{% url 'product_list' %}" method="get" class="sort-form"> {{ sort_form }} <p><input type="submit" name="sort" value="Сортировать"></p> {% csrf_token %} </form> -
Reference comment count on different using Django
I have a BlogPage that references all my blogs with snippets of text. These can be clicked to view the full blog on a ViewBlog page, at the bottom of the view-blog page you can add a comment, and all comments are subsequently shown on this page. I want to be able to reference the amount of comments made on every post some where on the snippet box on the blog page as screenshot below shows (I don't require help with the code for this, only the code to be able to reference it on the BlogPage; MODELS.PY class BlogPost(models.Model): title = models.CharField(max_length=100, null=False, blank=False, default="") text = RichTextUploadingField(null=True, blank=True, default="text") featured_text = models.TextField(max_length=550, null=True, blank=True, default="text") image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") date = models.DateField(auto_now_add=True) published = models.BooleanField(default=False) featured = models.BooleanField(default=False) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title class BlogComment(models.Model): post = models.ForeignKey(BlogPost, related_name="comments", on_delete=models.CASCADE) name = models.CharField('Name',max_length=100, default="") text = models.TextField('Comment',max_length=1000, default="") date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class Meta: ordering = ("date",) def __str__(self): return '%s -- Name: %s'%(self.post.title, self.name) VIEWS def BlogPage(request): posts = BlogPost.objects.filter(date__lte=timezone.now()).order_by('-date') blog_paginator = Paginator(posts, per_page=4) page_number = request.GET.get('page') page = blog_paginator.get_page(page_number) … -
iexact doesn't work in declaring filterable field in django-filter
I am using django-filter lib with DRF. class OrganizationFilter(FilterSet): class Meta: model = Organization fields = { 'city': ['iexact', 'contains'], 'zipcode': ['exact', 'contains'] } city: CharField I want to filter city field case-insensitive. I can make it work by specifying the following. class OrganizationFilter(FilterSet): city = filters.CharFilter(lookup_expr='iexact') ... Unless If I don't specify the lookup_expr it's not working. I want to know why? -
How to generate 10 digit unique-id in python?
I want to generate 10 digit unique-id in python. I have tried below methods but no-one worked get_random_string(10) -> It generate random string which has probability of collision str(uuid.uuid4())[:10] -> Since I am taking a prefix only, it also has probability of collision Do we have any proper system to generate 10 digit unique-id? -
Reading a file in view vs template in Django - is one more performant over the other?
Let's say I want to read a .txt file in Django. I can do it in two ways: 1. View def index(request): file = open('path/to/file', 'r') return render(request, 'index.html', {"text": file.read()}) And then just use that in the template like so: {{ text }}. 2. Template Or I could do it directly in the template using include, like so: {% include 'path/to/file' %}. Not my question is, is one approach better than the other one? Like is there a performance benefit in doing 2? Thanks for any help. -
How to combine two different tables information together in vuejs and django?
I am trying to build a application where there is on table called party which contains basic customer information and then another table called leads which contains more information about the same customer. But I am not able to get the two different tables information in one ag-grid table to show the information on my Vue.js frontend. Here is the code for the two tables separately: Party table <template> <div class="tasks_container"> <div class="tasks_content"> <h1>Party table</h1> <ag-grid-vue style="width:1310px; height: 650px" class="ag-theme-alpine" :columnDefs="columnDefs" :rowData="rowData" > </ag-grid-vue> </div> </div> </template> <script> import axios from 'axios'; import "ag-grid-community/styles/ag-grid.css"; import "ag-grid-community/styles/ag-theme-alpine.css"; import { AgGridVue } from "ag-grid-vue3"; import 'ag-grid-enterprise'; export default { components: { AgGridVue, }, data() { return { columnDefs: null, rowData: null, } }, mounted(){ this.columnDefs=[ {field:'FIRST_NAME',headerName: 'First name'}, {field:'LAST_NAME',headerName: 'Last name'}, {field:'PARTY_TYPE',headerName: 'Party Type'}, {field:'PRIMARY_NO',headerName: 'Main number'}, {field:'WHATSAPP_NO',headerName: 'Whatsapp number'}, {field:'EMAIL_ID',headerName: 'Email ID'}, {field:'PREFERRED_CONTACT_METHOD',headerName: 'Preferred contact'}, ]; axios.get('http://127.0.0.1:8000/request1') .then(response=>this.rowData=response.data) }, } </script> <style scoped> .ag-theme-alpine { --ag-foreground-color: rgb(2, 1, 2); --ag-background-color: rgb(245, 244, 243); --ag-header-foreground-color: rgb(204, 245, 172); --ag-header-background-color: rgb(64, 103, 209); --ag-odd-row-background-color: rgb(0, 0, 0, 0.03); --ag-header-column-resize-handle-color: rgb(236, 230, 236); --ag-font-size: 17px; --ag-font-family: monospace; } </style> Leads table <template> <div class="tasks_container"> <div class="tasks_content"> <h1>Lead table</h1> <ag-grid-vue style="width: 1330px; height: 850px" class="ag-theme-alpine" … -
AttributeError 'datetime.date' object has no attribute 'utcoffset'
Sorry if Im not making complete sense, but I'm relatively new with Django I have a models.py file with such attributes: from datetime import * from django.db import models def return_date_time(): now = datetime.now() return now + timedelta(days=10) class Job(models.Model): lastDate = models.DateTimeField(default=return_date_time) createdAt = models.DateTimeField(auto_now_add=True) I am able to create new database on /admin, but when editing I get This error AttributeError at /admin/job/job/2/change/ 'datetime.date' object has no attribute 'utcoffset' There was a very similar post here : https://stackoverflow.com/questions/51870088/django-attributeerror-datetime-date-object-has-no-attribute-utcoffset but I was not able to solve the problem The Traceback is as below Environment: Request Method: GET Request URL: http://localhost:8000/admin/job/job/2/change/ Django Version: 4.1.7 Python Version: 3.10.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'django.contrib.gis', 'django_filters', 'job.apps.JobConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 'datetime.date' object has no attribute 'utcoffset' 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors … -
The task in my Django asynchronous view is not executed
Django asynchronous views can respond immediately, while tasks run asynchronously,but in fact the task cannot continue. async def task_async(): print('task begin') await asyncio.sleep(2) print('task run success') async def view_async(request): print('async begin') loop = asyncio.get_event_loop() loop.create_task(task_async()) print('return') return HttpResponse("Non-blocking HTTP request") I expect the task to continue running after the http response returns, but the result is: async begin return task begin Using uvicron is ok, but manage.py is not。