Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiform nested data
Hey there i am trying to serialize the multiform nested data but i have tried everything but nothing works for me and also i did not get any kind of help from internet. enter image description here and i am getting data from frontend like that: <QueryDict: {'product_name': ['aa'], 'category': ['electronics'], 'description': ['aaa'], 'price': ['12'], 'inventory': ['[{"size":"Small","color":"Black","quantity":"4"}]'], 'images': [<InMemoryUploadedFile: Screenshot 2023-11-16 131611.png (image/png)>]}> please give some solution I have tried different libraries for parsing nested multiparse data but did not get a solution -
AWS Django NGINX timeout and async errors
I have a view in which I try to upload an excel sheet via a form. The excel that I upload isn't that big but the processing of the data in that excel is causing nginx time out issues resulting in a 502 Bad Gateway error. I do not have this problem when testing locally but it pops up on AWS EC2 when testing it on that environment. I increased the time out periods in nginx via (as suggested here): proxy_read_timeout 300s; proxy_connect_timeout 300s; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; And that did improve things somewhat since I can see more results but it was not sufficient. Curiously it timed out again before the 300s were up. Incidentally, if it used all 300s it should complete the process. It was also suggested I use async to make the processing independent of the upload process and that it run the processing in the background. However in attempting I keep running into this error: "object HttpResponseRedirect can't be used in 'await' expression" This error occurs when I try to load the page even before I try to upload the excel file which is the only time I have a redirect, which … -
Why aren't media files autogenerated in Django?
So i create same project which accepts input from the user in the form of an image. I followed Django step documentation and this. The result I got was correct, I received input from the terminal if the 'POST' method was successful by returning status code 200. But why is the media folder in the root directory not created? I've changed the settings.py with this code cartoon/views.py from django.shortcuts import render, redirect from django.http import HttpResponseServerError, HttpResponse from .forms import CartoonImageForm import cv2 import numpy as np from django.http import JsonResponse def cartoon (request): return render(request, 'cartoon/cartoon.html') def image (request): if request.method == 'POST': form = CartoonImageForm(request.POST, request.FILES) if form.is_valid (): form.save() return redirect('success') else: form = CartoonImageForm() return render(request, 'cartoon/cartoon.html', {'form': form}) def success(request): return HttpResponse('successfully uploaded') This urls.py # cartoon/urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import path from .views import cartoon, image app_name = 'cartoon' urlpatterns = [ path('cartoon/', cartoon, name='cartoon_page'), path('result/', image, name='cartoon_result') ] ## MEDIA if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) cartoon/forms.py from django import forms from .models import CartoonImage class CartoonImageForm(forms.ModelForm): class Meta: model = CartoonImage fields = ['image_upload'] directory root settings.py # Build paths inside the project like this: … -
Model property object not showing up
I try to calculate the average rating for my user. I triede to define property so it calculates and shows automatically. Models.py class User(AbstractUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=40, unique=True, default='undefinedusername') email = models.CharField(max_length=255, unique=True,null=True,blank=True) @property def average_rating(self): return self.usercomments.all().aggregate(Avg('rate')).get('rate__avg', 0.00) class UserComment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) profile = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='usercomments') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='usercomments_author') rate = models.IntegerField(default='0') Serializers.py class UserSerializer(serializers.ModelSerializer): rating_count = serializers.SerializerMethodField(read_only=True) usercomments_set = UserCommentSerializer(source='usercomments', required=False, many=True) class Meta: model = User fields = '__all__' def get_rating_count(self, language): return language.usercomments.count() def validate(self, attrs): attrs = super().validate(attrs) if attrs.get('id') == self.context['request'].user.pk: return attrs raise ValidationError('Unauthorized Request') Here is my result: { "count": 1, "next": null, "previous": null, "results": [ { "id": "8b0efd7e-06ac-4d57-a347-e9ffe79c3c31", "usercomments_set": [ { "id": "61c5b21e-3456-4a13-83c4-4557cd621af6", "rate": 4, "profile": "8b0efd7e-06ac-4d57-a347-e9ffe79c3c31", "author": "f474d116-ec1d-498b-a166-7af3fa8cfd59" } ], "rating_count": 1, "username": "undefinedusername", "email": "testmail@gmail.com", }, } Everything else except average_rating shows up. What is the issue?Where did I make the mistake? -
In the file in Django, the venv file does not appear. Please respond\في الملف في دجانجو لا يظهر ملف venv ارجو الرد [closed]
The venv file is not supposed to appear as the first file?\ليس من المفترض ان يظهر ملف venv اول ملف ؟ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -
Issues with Django Import-Export: Validation Errors during CSV Import
I am currently working on a Django project where I'm using the django-import-export library to import CSV data into my models through the Django admin interface. I have set up resources, models, and made necessary changes in the admin, but I'm facing validation errors during the import process. I have the following structure in my Django project: models.py: Contains the definitions of various models like PlayStyles, Coaches, Stadiums, Leagues, Teams, Players, Matches, and Statistics. resources.py: Includes corresponding ModelResource classes for each model. admin.py: Configures the Django admin interface to use the ModelResource classes for data import/export. CSV Files: I have CSV files for each model with data to be imported. Despite setting up the resources correctly, I am encountering issues when importing CSV files for certain models, specifically for Teams. The error message mentions validation errors related to foreign key fields (stadium, coach, and league). Here's a snippet of my relevant code: models.py: # ... (models for PlayStyles, Coaches, Stadiums, Leagues, etc.) class Teams(models.Model): name = models.CharField(max_length=100) established_year = models.IntegerField() stadium = models.ForeignKey(Stadiums, on_delete=models.CASCADE) coach = models.ForeignKey(Coaches, on_delete=models.CASCADE) league = models.ForeignKey(Leagues, on_delete=models.CASCADE) number_of_titles = models.IntegerField() resources.py: # ... (resources for PlayStyles, Coaches, Stadiums, Leagues, etc.) class TeamsResource(resources.ModelResource): class Meta: model … -
You're accessing the development server over HTTPS, but it only supports HTTP.(DJANGO)
I have a Django app in which I make an object name Bin via forms. But when I try to POST the requested for the form it says '"GET /creatBin HTTP/1.1" 200 4503 [11/Dec/2023 10:29:01] code 400, message Bad request version ('ÚÚ\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x01\x00\x01\xad') [11/Dec/2023 10:29:01] You're accessing the development server over HTTPS, but it only supports HTTP. [11/Dec/2023 10:29:01] code 400, message Bad request version ('\x00\x02\x01\x00\x00') [11/Dec/2023 10:29:01] You're accessing the development server over HTTPS, but it only supports HTTP.' now my views function is: def creatBin(request): if request.user.is_authenticated: if request.method == 'POST': form = Bins(request.POST) if form.is_valid(): refresh_stats = form.cleaned_data['refreshStats'] last_refresh = form.cleaned_data['lastRefresh'] fill_up = form.cleaned_data['fillUp'] area = form.cleaned_data['Area'] city = form.cleaned_data['City'] qr_data = form.cleaned_data['qr_data'] print(qr_data) qr_data_json = json.loads(qr_data) lat = qr_data_json['Lat'] lon = qr_data_json['Lon'] bin_id = qr_data_json['BinID'] if fill_up >= 70: status = 'HIGH' form.refreshStats = 'Due' elif fill_up >= 40: status = 'MID' form.refreshStats = 'Due' else: status = 'LOW' form.refreshStats = 'Done' # Now you have individual variables for each form field # You can use these variables as needed, for example, save them to the database bin_instance = BinsStats( BinID=bin_id, status=status, refreshStats=refresh_stats, lastRefresh=last_refresh, fillUp=fill_up, Lat=lat, Lon=lon, Area=area, City=city, ) bin_instance.save() messages.success(request, 'Bin added successfully!') else: messages.error(request, … -
Django template next item show with infinite scroll
i have some code wrong and run nex item show with infinite scroll,How to resolve.TKs i made a countdown on the template var eventBox = document.getElementById('event-box') console.log(eventBox.textContent) var countdownBox = document.getElementById('countdown-box') console.log(countdownBox.textContent) var eventDate = Date.parse(eventBox.textContent) setInterval(()=>{ var now = new Date().getTime() var diff = eventDate - now var d = Math.floor(eventDate / (1000 * 60 * 60 * 24) - (now / (1000 * 60 * 60 * 24))) var h = Math.floor((eventDate / (1000 * 60 * 60 ) - (now / (1000 * 60 * 60 ))) % 24 ) var m = Math.floor((eventDate / (1000 * 60 ) - (now / (1000 * 60 ))) % 60 ) var s = Math.floor((eventDate / (1000) - (now / (1000))) % 60 ) if (diff>0) { countdownBox.innerHTML = d + " 天, " + h + " 時, " + m + "分, " + s + "秒" } else { } }, 1000) def all_emp(request): emps = Employee.objects.filter(end_date__gt=Now()).all() context = { 'emps': emps } print(context) return render(request, 'view_all_emp.html', context) enter image description here -
Reverse Relationship in Django Rest Framework
I have Course and CourseComment models. In Course details view I should return details of Course, and also comments by user. I've made serializer for Course details and Course comments. But coursecomment_set field is empty. I wrote several comments for Course. Here is my models, serializers and models # views.py ---> Course Details API View class CourseDetailsView(generics.RetrieveAPIView): queryset = models.Course.objects.select_related('category') serializer_class = serializers.CourseDetailSerializer lookup_field = 'slug' # models.py ---> Course model class Course(BaseModel): LEVEL_TYPES = ( ('beginner', 'Beginner'), ('intermediate', 'Intermediate'), ('advanced', 'Advanced'), ) LANGUAGES = ( ('uz', 'O`zbek tili'), ('en', 'Ingliz tili'), ('ru', 'Rus tili'), ) title = models.CharField(max_length=128) author = models.CharField(max_length=128) price = models.PositiveIntegerField(default=0) level = models.CharField(choices=LEVEL_TYPES, max_length=16) description = models.TextField() category = models.ForeignKey('CourseCategory', on_delete=models.CASCADE) lessons_count = models.PositiveIntegerField(default=0) language = models.CharField(choices=LANGUAGES, max_length=2, default='uz') rating = models.DecimalField(max_digits=2, decimal_places=1, default=0) slug = models.SlugField(unique=True, blank=True) # Comments model class CourseComment(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) body = models.TextField() rating = models.DecimalField(decimal_places=1, max_digits=2) # serializers.py ---> Course Comments Serializer class CourseCommentSerializer(serializers.ModelSerializer): class Meta: model = CourseComment fields = ('user', 'body', 'rating') # Course details class CourseDetailSerializer(serializers.ModelSerializer): coursecomment_set = CourseCommentSerializer(many=True, read_only=True) class Meta: model = Course fields = "__all__" View returning response, but comments are empty, I've several comments in database … -
Restrict user access to pages
I want users to be able to see only their profile information and not have acccess to others users information. I am using a test_func to check if the user login trying to access the profile information is the owner of the information. The problem is that for some reason it always returns true, and when i go to my page an change the id on the link trying to access others users information it somehow automatically login with the user due user account and then return the information, it is, if i'm logged in as "lerton" with id 1 and i try to access the information of user "maguia" with id 2 it automatically log in as "maguia" and return me the information of "maguia" urls.py path('profile/<int:pk>/', ProfileView.as_view(), name='profile'), View.py class ProfileView(LoginRequiredMixin, DetailView, UserPassesTestMixin): model = get_user_model() template_name = 'profile.html' context_object_name = 'user' def test_func(self): user = self.get_object() return user == self.request.user I tried to compare in the test_func the other properties like id, username, etc, of the users but didn't work -
Show only the seasons related to the current course in Django Admin Panel
hi guys i have a 3 model: class Course(models.Model): title = models.CharField(max_length=30) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="courses") class Season(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course_season") name = models.CharField(max_length=40) class CourseVideo(models.Model): title = models.CharField(max_length=30) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course_videos") season = models.ForeignKey(Season, on_delete=models.CASCADE, related_name="season", null=True, blank=True) video = models.FileField(upload_to="vid/course_video") and this is my admin file : class DetailAdmin(admin.TabularInline): model = models.CourseVideo class SeasonAdmin(admin.TabularInline): model = models.Season @admin.register(models.Course) class CourseAdmin(admin.ModelAdmin): inlines = (SeasonAdmin, DetailAdmin) list_display = ("title", "price") now my problem is in the django`s admin panel when i have created forexample 2 seasons for each course and i want to create some videos when i wanna choose a season for a video , it shows all the seasons which is created but i just want it to show the seasons who are related to the course . what should i do ? -
Create django filter choices based on current queryset
I have a table with a number of category columns and I want to provide a choice filter for each category column based on the current set of values, not based on all possible values. year category_a category_b 2020 x a 2021 y b 2022 z b Given the above the initial choices for category_a would be x,y,z and category_b would be a,b. This I can achieve by using something like self.parent.queryset.distinct('category_a'). However once the user applies a filter like category_b=b, the choices should only be y,z, i.e. something like self.parent.qs.distinct('category_a'). This however runs into recursion. I'm looking through the execution path of FilterSets, since it seems to me that they must be used twice in a request, once to apply the current filter data and a second time to render the filter widgets for the response, but choices is evaluated as part of the initial set validation, hence the recursion. Is there a way to defer the computation of choices until the widget is rendered? -
How to read csv file into django project?
I'm using csv(txt) file to make graphs, but Django doesn't want to find it. So I can't understand, where should I create a file. def get_plot(): df = pd.read_csv('jobibi.txt', sep=',', encoding='utf-8') And the output on the web page: FileNotFoundError at /analytics/ [Errno 2] No such file or directory: 'jobibi.txt' -
How to send nested array of object using formdata from react js and save in django rest framework
when i send array of object in json it work perfectly but it was not work using form data.. when isend this {"name":"arijit","age":"30","singerimg":null,"songs":[{"title":"abc","duration":"5"}]} it work perfectly but var formData = new FormData(); formData.append('name', $('#name').val()) formData.append('age', $('#age').val()) formData.append('singerimg', $('#image')[0].files[0]? ($('#image')[0].files[0]):("")) formData.append('songs[0][title]', 'abc') formData.append('songs[0][duration]', '50') it's not work model.py class singer(models.Model): name = models.CharField(max_length = 25, null=True, blank = True) age = models.CharField(max_length = 4, null=True, blank = True) singerimg = models.ImageField(upload_to="photos", max_length = 100, null = True, blank = True ) def __str__(self): return self.name class songs(models.Model): singer = models.ForeignKey(singer,related_name = 'songs', on_delete=models.CASCADE) title = models.CharField(max_length = 25, null=True, blank = True) duration = models.CharField(max_length = 25, null=True, blank = True) serializers.py class soSerializer(ModelSerializer): class Meta: model = songs fields = ['id', 'title', 'duration'] class singerSerializer(ModelSerializer): songs = soSerializer(many=True) class Meta: model = singer fields = ['id', 'name', 'age','singerimg', 'songs'] def create(self, validated_data): song = validated_data.pop('songs') sin = singer.objects.create(**validated_data) for song_data in song: songs.objects.create(singer=sin, **song_data) return sin -
remove /admin in admin panel url of django project and access to pdf file in browser
Good Day! I can not acces to a uploaded file in browser through admin panel, after removing /admin in urls.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) files are kept in /media/ which is shown in setting.py of project #STATIC_URL = 'static/' STATIC_URL = '/static/' import os STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Admin panel view url If I try to open this file by clicking in browser it is not openening it is showing this error on page But if I return admin/ in urls.py as it was before, it is opening a file in browser urlpatterns = [ path('admin/', admin.site.urls), ] can anyone help on this please? -
Sending Email in Django Fail without any Error
Hello I am begginer with django and I tring to send email with my django app and i use my domain Email in my console i see Email is Sending Without any Error iam Sure my Email information is correct i see this in the console: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject of the email From: my host email To: my email Date: Mon, 11 Dec 2023 05:19:39 -0000 Message-ID: <170227197998.14276.5037629317653964065@DESKTOP-V6VG9GG> Test email i use this settings in setting.py : EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = "bahman.pws-dns.net" EMAIL_PORT = 465 EMAIL_USE_TLS = True EMAIL_HOST_USER = "my domain email" EMAIL_HOST_PASSWORD = "my password" DEFAULT_FROM_EMAIL = EMAIL_HOST_USER and i use this function to send Email : from django.core.mail import EmailMessage, get_connection def send_email(user): try: with get_connection( host=settings.EMAIL_HOST, port=settings.EMAIL_PORT, username=settings.EMAIL_HOST_USER, password=settings.EMAIL_HOST_PASSWORD, use_tls=settings.EMAIL_USE_TLS ) as connection: subject = 'Subject of the email' email_from = settings.EMAIL_HOST_USER recipient_list = [user.email] message = "Test email" email = EmailMessage(subject, message, email_from, recipient_list, connection=connection) email.send() except Exception as e: # Log the exception logging.error(f"Error sending email to {user.email}: {e}") where is the problem -
Hello. I can't upload pictures in my django project using Pydroid3. The picture file is uploaded in my 'media/images' folder but they all show 0kb [closed]
The error message that arrise is File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.11/site-packages/django/core/files/locks.py", line 126, in unlock fcntl.flock(_fd(f), fcntl.LOCK_UN) OSError: [Errno 38] Function not implemented I tried to upload images in my project to show on my website, but the images do not show. The images are loaded in the 'media/images' folder in my project root directory, but they all show 0kb. -
Django 4 by examples - Blog - send email issues
I was working on Django by Examples. Under Blog/share I am unable to send the email. Sharing all relevant blocks of code here. This is a copy paste of the code provided in the book, but I am still getting an error This is the views.py file def post_share(request, post_id): post = get_object_or_404(Post, id = post_id, status = 'Post.Status.PUBLISHED') sent = False if request.method == 'POST': form = EmailPostForm(request.POST) if form.is_valid(): cd = form.cleaned_data post_url = request.build_absolute_uri( post.get_absolute_url()) subject = f"{cd['name']} recommends you to read " \ f"{post.title}" message = f"Read {post.title} at {post_url}\n\n" \ f"{cd['name']}\'s comments: {cd['comments']}" send_mail(subject, message, 'anupam.iitm@gmail.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent}) url patterns from django.urls import path from . import views app_name = 'blog' urlpatterns = [ # post views path('', views.post_list, name = 'post_list'), ## path('', views.PostListView.as_view(), name='post_list'), ## this is the same as above but using classes. However, some error and it is not working as expected path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name = 'post_detail'), path('<int:post_id>/share/', views.post_share, name = 'post_share'), ] share.html {% extends "blog/base.html" %} {% block title %}Share a post{% endblock %} {% block content %} {% if sent %} <h1>E-mail successfully … -
cannot install mod_wsgi on windows over wampserver 3.3.2 6rbit
I have been trying to install mod_wsgi using pipenv install mod_wsgi on windows machine over a wampserver, but I get this error. I searched google for info on proceeding getting a Django app hosted over Apache, but couldn't find any information (or a resolution). They all mention to install mod-wsgi using "pip install mod-wsgi", as it is tried and tested, but each time I try it, I get this error below. Any suggestions to overcome this would be helpful. Thanks. (spolls-JBTzETyl) C:\spolls\polls>pipenv install mod_wsgi Installing mod_wsgi... Resolving mod_wsgi... Added mod-wsgi to Pipfile's [packages] ... Installation Succeeded Installing dependencies from Pipfile.lock (d0acbf)... [pipenv.exceptions.InstallError]: Collecting mod-wsgi==5.0.0 (from -r c:\users\ti-main1\appdata\local\temp\pipenv-lo438x_j-requirements\pipenv-itch8i1s-hashed-reqs.txt (line 1)) [pipenv.exceptions.InstallError]: Using cached mod_wsgi-5.0.0.tar.gz (497 kB) [pipenv.exceptions.InstallError]: Preparing metadata (setup.py): started [pipenv.exceptions.InstallError]: Preparing metadata (setup.py): finished with status 'done' [pipenv.exceptions.InstallError]: Building wheels for collected packages: mod-wsgi [pipenv.exceptions.InstallError]: Building wheel for mod-wsgi (setup.py): started [pipenv.exceptions.InstallError]: Building wheel for mod-wsgi (setup.py): finished with status 'error' [pipenv.exceptions.InstallError]: Running setup.py clean for mod-wsgi [pipenv.exceptions.InstallError]: Failed to build mod-wsgi [pipenv.exceptions.InstallError]: error: subprocess-exited-with-error [pipenv.exceptions.InstallError]: [pipenv.exceptions.InstallError]: × python setup.py bdist_wheel did not run successfully. [pipenv.exceptions.InstallError]: │ exit code: 1 [pipenv.exceptions.InstallError]: ╰─> [33 lines of output] [pipenv.exceptions.InstallError]: running bdist_wheel [pipenv.exceptions.InstallError]: running build [pipenv.exceptions.InstallError]: running build_py [pipenv.exceptions.InstallError]: creating build [pipenv.exceptions.InstallError]: … -
self referenced table prefetching takes time
I have self referenced model pattern and i am prefetching nested self references to avoid N+1 query problem. in the end I avoid that problem. but this time it takes time (depends on the data load) def get_prefetched_queryset(self, queryset, statuses): fr_query = Q(status__in=statuses, content__space__id=self.space_id) selects = ["field_extra_data", "field_reference__field", "content_reference", "media", "lang", "field_reference"] extra_data = FieldReferenceExtraData.objects.select_related(*selects).filter( content__space__id=self.space_id, lang__key=self.lang_key ) fr_selects = ["field", "field_reference", "content", "field__master_field"] field_references = FieldReference.objects.select_related(*fr_selects).filter(fr_query).prefetch_related( # Prefetch("field_references", queryset=FieldReference.objects.filter(fr_query)), Prefetch("extra_data", queryset=extra_data), ) queryset = queryset.prefetch_related( Prefetch( "field_references", queryset=field_references.filter(field_reference__isnull=True).prefetch_related( Prefetch( "field_references", queryset=field_references.prefetch_related( Prefetch( "field_references", queryset=field_references.prefetch_related( Prefetch( "field_references", queryset=field_references.prefetch_related( Prefetch( "field_references", queryset=field_references ), ) ), ), ), ), ), ), ), ) print(queryset.explain()) print(connection.queries) print(len(connection.queries)) return queryset if I remove the nested prefetching, response time improves. but prefetching or not explain information and query contents are same. but of course query 8 -> 15 (that's vies around ) counts are changes. I need nested prefetching for fixing N+1 problem, but adding it makes the response time slower. is it possible to fix issue? below is the explain info. Unique (cost=181.02..219.35 rows=697 width=1669) -> Sort (cost=181.02..182.76 rows=697 width=1669) Sort Key: users_userlastupdatedby.updated_at DESC, contents_content.id, contents_content.user_id, contents_content.model_id, contents_content.status, contents_content.created_at, contents_content.updated_at, contents_content.published_at, contents_content.hide_at, contents_content.publish_schedule_at, contents_content.hide_schedule_at, models_model.space_id, models_model.order_num, models_model.name, models_model.type, models_model.luid, models_model.preview_url, models_model.publish_url, models_model.description, models_model.created_at, models_model.updated_at … -
How to save hashed password and send_mail using django and django restframework?
I am using django restframework to build an endpoint and i have Modelserializer to serialize and send email activation token using django's email backend via console.But the serializer saves some part of the fields ignoring hashed password, sending email using send_mail() and also any print or logging statements.and it give me 201 response.Here are the codes Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = [ "first_name", "last_name", "email", "phone_number", "address", "zip_code", "company_name", "gender", "birthdate", "referral_code", "city", "district", ] read_only_fields = [ "is_active", "is_staff", "is_superuser", "is_email_verified", "is_address_verified", "is_company_verified", "created_at", "updated_at", "login_attempts", ] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): BASE_URL = "http://127.0.0.1:8000/api/p/users/" UID = urlsafe_base64_encode(force_bytes(user.pk)) TOKEN = account_activation_token.make_token(user) sender_mail = "313delivery@gmail.com" mail_subject = "Activation link has been sent to your email id" traceback.print_exc() print("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr") city1 = City.objects.get(pk=validated_data.pop("city")) district1 = District.objects.get(pk=validated_data.pop("district")) user = CustomUser( first_name=validated_data["first_name"], last_name=validated_data["last_name"], email=validated_data["email"], phone_number=validated_data["phone_number"], zip_code=validated_data["zip_code"], company_name=validated_data["company_name"], gender=validated_data["gender"], birthdate=validated_data["birthdate"], referral_code=validated_data["referral_code"], city=validated_data["city"], district=validated_data["district"], ) user.set_password(validated_data["password"]) # send OTP to user via email domain = (BASE_URL + "activate/" + UID + "/" + TOKEN,) logger.info("before sending email ------") email = send_mail( subject=mail_subject, message=domain, from_email=sender_mail, recipient_list=validated_data["email"], fail_silently=False, ) user.otp = TOKEN email.send() logger.info("after sending email ------") user.save() return user View class UserCreateView(APIView): def post(self, request): serializer = UserSerializer(data=request.data) if … -
Resetting Primary Key (pk) Sequence in Django Factory Boy for Each Test
I'm trying to figure out how to reset the factory model's primary key (pk) sequence in Django when using FactoryBoy for testing. Consider the following sample model and tests: class Profile(DjangoModelFactory): class Meta: model = Profile Now I want to test it: class FirstTest(TestCase): @classmethod def setUpClass(cls): super(UserScoresTest, cls).setUpClass() Profile.create() Profile.create() class SecondTest(TestCase): @classmethod def setUpClass(cls): super(UserScoresTest, cls).setUpClass() Profile.create() Profile.create() After running these tests, the Profiles' primary keys (pk) in SecondTest have values 3 and 4, respectively. I want to reset the pk sequence before each test. What should I do? -
How to connect Django project to containerized PostgreSQL database
I'm trying to connect my local django project to a Postgres DB container. I am not sure why I get this error "django.db.utils.OperationalError: connection failed: :1), port 5432 failed: FATAL: role "demo" does not exist". Could you please help me figure out where I went wrong? Here is my .env file: POSTGRES_USER=demo POSTGRES_PASSWORD=demo POSTGRES_NAME=demo Here is my docker-compose.yml: volumes: postgres_data: services: db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env ports: - "5432:5432" And here is the databases section of my settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": env('POSTGRES_NAME'), "USER": env('POSTGRES_USER'), "PASSWORD": env('POSTGRES_PASSWORD'), "HOST": "localhost", # set in docker-compose.yml "PORT": 5432, # default postgres port } } -
PANIC: unprotected error in call to Lua API (zlib library version does not match - header: 1.2.11, library: 1.3) when deploying app to Railway
I currently have Django code that compiles a LaTeX file using lualatex. It works locally in my virtual environment, but when I deploy my project to Railway, I am getting the following error: PANIC: unprotected error in call to Lua API (zlib library version does not match - header: 1.2.11, library: 1.3) I attempted to install zlib version 1.3 (and I also tried 1.2.11) manually with nixpacks in a railway.json file, but the error still persists when I try to compile a LaTeX file on my deployed web app. Here is my railway.json file: { "$schema": "https://schema.up.railway.app/railway.schema.json", "build": { "builder": "NIXPACKS", "nixpacksPlan": { "phases": { "setup": { "aptPkgs": ["...", "texlive-full", "wget"], "cmds": [ "wget https://zlib.net/current/zlib.tar.gz && tar -xzf zlib.tar.gz && cd zlib-1.3 && ./configure && make && sudo make install" ] } } } }, "deploy": { "startCommand": "python manage.py migrate && python manage.py collectstatic --noinput && gunicorn layoutGenerator.wsgi", "restartPolicyType": "ON_FAILURE", "restartPolicyMaxRetries": 10 } } and here is my requirements.txt created from my virtual environment: asgiref==3.7.2 Django==5.0 et-xmlfile==1.1.0 gunicorn==21.2.0 numpy==1.26.2 openpyxl==3.1.2 packaging==23.2 pandas==2.1.3 pdf2image==1.16.3 Pillow==10.1.0 python-dateutil==2.8.2 pytz==2023.3.post1 six==1.16.0 sqlparse==0.4.4 tzdata==2023.3 Everything else seems to work on the web app other than this LaTeX compilation. Any help would be much appreciated! -
How can I get data for a specific element, id in Django?
views.py from datetime import datetime import numpy as np import pandas as pd from django.apps import apps from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.views import LoginView, LogoutView from django.db import transaction from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import redirect, render from django.urls import reverse, reverse_lazy from django.utils.decorators import method_decorator from django.views import View from django.views.generic import ( CreateView, DetailView, ListView, TemplateView, UpdateView, ) @method_decorator(login_required(login_url=reverse_lazy("core:login")), name="dispatch") class HomePageView(TemplateView): template_name = "home.html" def get_queryset(self): model_names = [ model.__name__ for model in apps.get_app_config("core").get_models() ] return model_names @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(HomePageView, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["models_list"] = self.get_queryset() return context class LoginView(LoginView): template_name = "login.html" def form_valid(self, form): messages.info( self.request, f"You are now logged in as {form.cleaned_data['username']}" ) return super().form_valid(form) def form_invalid(self, form): messages.error(self.request, "Invalid username or password.") return super().form_invalid(form) class LogoutView(LogoutView): next_page = reverse_lazy("core:home") template_name = "logout.html" class ModelDetailsView(DetailView): template_name = "list_datas.html" context_object_name = "model_data" def get_object(self, queryset=None): model_name = self.kwargs["model_name"] Model = apps.get_model("core", model_name) return Model.objects.filter(is_active=True) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) model_name = self.kwargs["model_name"] Model = apps.get_model("core", model_name) instances = Model.objects.filter(is_active=True) field_names = [ field.name for field in Model._meta.get_fields() if field.name not in [ "is_active", "created_by", "last_modified_by", "last_modified_on", "created_on", …