Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Many-Many nested serializer create method does similar n+1 queries
I have a many-many relation between User model and my custom Team model. Where i can add multiple users to my team. I have used prefetch_related on my team model so the get (list) operation is optimized, whereas the post (create) operations does query every time for a user. Below is my code. models.py class Team(models.Model): team_name=models.CharField(max_length=50,blank=False,null=False) user=models.ManyToManyField(User,related_name='user') def __str__(self) -> str: return self.team_name serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] def to_representation(self, instance): return [instance.id ,instance.username] def to_internal_value(self, data): try: return User.objects.get(id=data) # this queries the db for every user except Exception as e: print(e) raise serializers.ValidationError("User does not exists") class TeamSerializer(serializers.ModelSerializer): user=UserSerializer(many=True) class Meta: model=Team fields=('team_name','user') def create(self, validated_data): users = validated_data.pop('user') team = Team.objects.create(**validated_data) for user in users: team.user.add(user) return team views.py class TeamView(viewsets.ModelViewSet): queryset=Team.objects.all().prefetch_related('user') serializer_class=TeamSerializer as it can be seen, for 7 users added to the team, it does 7 queries. how can this be optimized ? Any help is appreciated. -
uwsgi worker hangs on exit, but only if it used async trio module
I have a Django site that uses the trio_cdp package to generate PDFs using a headless Google Chrome. This package is async, but my Django project is sync, so it has to run inside trio.run() It's also using uwsgi locks so that only one client can generate a PDF at a time (headless Chrome loads the page in a single virtual tab, so it can only do one at a time) Here is the code: import trio import base64 import requests from django.conf import settings from trio_cdp import open_cdp, page, target try: import uwsgi have_uwsgi = True except ModuleNotFoundError: have_uwsgi = False async def render_pdf_task(url, params): r = requests.get(url=settings.CDP_URL) if r.status_code == 200: out = r.json() ws_url = out[0]['webSocketDebuggerUrl'] else: return None async with open_cdp(ws_url) as conn: targets = await target.get_targets() target_id = targets[0].target_id async with conn.open_session(target_id) as session: async with session.page_enable(): async with session.wait_for(page.LoadEventFired): await page.navigate(url) await trio.sleep(0.5) pdf = await page.print_to_pdf(**params) pdfdata = base64.b64decode(pdf[0]) await conn.aclose() return pdfdata def render_pdf(url, params): if have_uwsgi: uwsgi.lock(1) pdfdata = trio.run(render_pdf_task, url, params) if have_uwsgi: uwsgi.unlock(1) return pdfdata Annoyingly, any uwsgi worker that has run this particular task will later hang on exit until it is forcibly killed. If uwsgi runs and … -
Django, DRF: To remove a specific field of the serializer only on the first page
How can I remove field3 and field4 only on the first page? I need something that can be dynamically reused as I plan to use it in multiple views. class CustomSerializer(serializers.ModelSerializer): class Meta: model = Model fields = ('field', 'field2', 'field3', 'field4') class CustomView(ListAPIView): serializer_class = CustomSerializer -
django delete post noReverseMatch
Trying to delete a post, but somehow getting a NoReverseMatch views.py @login_required def task_detail(request, slug): ''' Detailed view of all tasks on given project ''' context = {} checklist = get_object_or_404(Checklist, slug=slug) context.update({'checklist':checklist}) form = NotesForm(request.POST or None) if request.method == "POST": if form.is_valid(): print("\n\n for is valid") author = Profile.objects.get(user=request.user) new_note = form.save(commit=False) new_note.user = author new_note.checklist = checklist new_note.save() return redirect('task_detail', slug=slug) context.update({ 'form': form, 'title': checklist, }) return render(request, 'projects/checklist.html', context) @login_required def delete_notes(request, note_id = None): del_note = Note.objects.get(id = note_id) del_note.delete() return redirect('teams') My urls.py urlpatterns = [ path('projects/', teams, name='teams'), path('projects/project/<slug>/', projects, name='projects'), path('projects/tasks/<slug>/', project_detail, name='project_detail'), path('projects/checklist/<slug>/', task_detail, name='task_detail'), path('projects/checklist/delete_notes/', delete_notes, name='delete_notes'), ] in the html I have just a href with the url to delete <a class="dropdown-item text-danger" href="{% url 'delete_notes' notes.id %}">Delete</a> Getting; Reverse for 'delete_notes' with arguments '(14,)' not found. 1 pattern(s) tried: ['projects/checklist/delete_notes/\Z'] Not really sure what is missing, thought the slug from checklist was already passed? -
Django-channels: why message sends to everyone, instead of one user?
everyone. I am building a WebRTC videochat app. I have a function of holding user on a line, which work great: I press a button, signal goes to server, servers sends it to user using self.channel_layer.send(), user gets alert() and puts on hold. But when I want to unhold him, server sends signal to everyone in room, despite all the parameters are the same as in "hold" function. Holding user: if action == 'onhold': #holding user await self.channel_layer.send( list(usersChannels.keys())[list(usersChannels.values()).index(message['peer'])], #channel to hold { 'type': 'channel_message', 'action': 'onhold', 'room': 'room', 'message': {message['peer']: '1'}, } ) return Unholding user: if action == 'unhold': # unholding user await self.channel_layer.send( list(usersChannels.keys())[list(usersChannels.values()).index(message['peer'])], # channel to unhold { 'type': 'channel_message', 'action': 'unhold', 'room': 'room', 'message': {message['peer']: '1'}, } ) return Full code here: https://pastebin.com/CicsUhy4 (sorry for "dirtiness") I am very new in Channels, so every hint would be a blessing. Sorry for bad english. Thank you. -
TemplateSyntaxError at /course
I am trying to include my views url on my html navbar and when i loaded the page i got this error saying; Could not parse the remainder: ''courses:course_list' from ''courses:course_list' here is my urls for the courses` from django.urls import path from . import views app_name = "courses" urlpatterns = [ path('', views.course_list, name='course_list'), path('<int:id>/<slug:slug>/', views.course_detail, name='course_detail'), path('save_review/', views.SaveReview.as_view(), name='save_review'), path('load_more_review/', views.load_more_review, name='load_more_review'), path('create_user_library/', views.UserCourse.as_view(), name='user_library'), path('<str:username>/user_library/', views.user_library, name='user_library'), path('pay_for_courses/', views.AjaxCoursePayment.as_view(), name='pay_for_courses'), path('<int:id>/print_course_pdf', views.CoursePdf.as_view(), name='print_course_pdf'), path('search_more_courses/', views.search_more_courses, name='search_more_courses'), path('search_courses/', views.search_courses, name='search_courses') ] and here is my views for the courses def course_list(request, slug=None): category = None categories = Category.objects.all() courses = Courses.objects.filter(available=True) if slug: category = get_object_or_404(Category, slug=slug) courses = courses.filter(category=category) return render(request, 'courses/content/list.html', {'category': category, 'categories': categories, 'courses': courses}) and here is the my base.html -
group by week and get values with week start date and week end date in django
Here is my model Model: class Order(models.Model): buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE) value = models.FloatField(null=True, blank=True) date = models.DateField(null=True, blank=True) I need a query to show weekly data with the start date of the week and the end date of the week. expected table: --------------------------------------------- | week | start date | end date | Value | --------------------------------------------- | 1 | 01-01-2022 | 07-01-2022 | 5400 | --------------------------------------------- | 2 | 08-01-2022 | 14-01-2022 | 6000 | --------------------------------------------- -
Django can't save userprofile instance during saving forms
I am getting this error Cannot assign "<QuerySet [<UserProfile: UserProfile object (131)>]>": "BlogComment.userprofile" must be a "UserProfile" instance. during saving my forms. Here is my code: if request.method == "POST": if comment_form.is_valid(): isinstance = comment_form.save(commit=False) name = request.POST['name'] email = request.POST['email'] if request.user.is_authenticated: user_profile = UserProfile.objects.filter(user=request.user) isinstance.blog = blog isinstance.user = request.user isinstance.name = name isinstance.email = email isinstance.userprofile = user_profile isinstance.save() models.py class BlogComment(models.Model): userprofile = models.ForeignKey(UserProfile,on_delete=models.CASCADE,null=True,blank=True) #others fields.... In my models I have foreignkey named userprofile so I am trying to save this instance like this isinstance.userprofile = user_profile where I am doing mistake? using this queary user_profile = UserProfile.objects.filter(user=request.user) for getting current user profile -
Djnago superuser is not created properly?
Super user is creating when i removed one of the seeting AUTH_USER_MODEL & in models AbstractBaseUser, PermissionsMixin and added (models.Model) otherwise it is not creating the superuser.. models.py ============= import django from django.db import models import django.utils.timezone from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.base_user import BaseUserManager from rest_framework_simplejwt.tokens import RefreshToken from django.core.validators import RegexValidator import datetime,calendar import uuid class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given mobile and password. """ if not email: raise ValueError('The given email must be set') # email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) -
Passing additional information to View
I am trying to handle Django form in a more gentle way and actually, I have no idea how to push further this topic. I have a View which is responsible for displaying a Form, in If form.is_valid() condition I am looking for free parking spots, if I found nothing then I would like to show an Error to the user or pass to context additional data. Fist part I've covered easily but I have no idea how to show an error or something similar. class BookParkingSpot(FormMixin, generic.ListView): template_name = 'parking/book_spot.html' form_class = BookParkingSpotForm model = ParkingBooking def post(self, request, *args, **kwargs): form = BookParkingSpotForm(self.request.POST) if form.is_valid(): parking_spot_list = ParkingSpot.objects.all().exclude( parkingbooking__booking_time_start__lte=form.instance.booking_time_end, parkingbooking__booking_time_end__gte=form.instance.booking_time_start ) if parking_spot_list.exists(): random_spot = random.choice(parking_spot_list) reservation = ParkingBooking.objects.create( car=form.instance.car, booking_owner=self.request.user, spot=random_spot, booking_time_end=form.instance.booking_time_start, booking_time_start=form.instance.booking_time_end, ) return redirect(reservation.get_absolute_url()) else: # this part doesn't work context = self.get_context_data(**kwargs) return render(self.request, self.template_name, context) Any idea how to improve it? -
Django Get full url path from app_name
there is a way to get full url from app_name ? like get_url('myapp:bio') from django.urls import include, path app_name = 'myapp' urlpatterns = [ path('index/', views.index, name='main-view'), path('bio/<username>/', views.bio, name='bio'), ] -
Vs Code settings.json missing
have the Vim VsCode extension. Where can I set custom mappings? Already searched for it but everyone says I have to do it in the settings.json But there isn't anything related to vim \settings.json { "editor.hover.enabled": false, "security.workspace.trust.untrustedFiles": "open", "workbench.startupEditor": "none", "editor.formatOnSave": true, "workbench.iconTheme": "Monokai Pro (Filter Machine) Icons", "workbench.colorTheme": "Atom One Dark", "liveServer.settings.donotVerifyTags": true, "editor.fontSize": 13, "terminal.integrated.shellArgs.windows": ["-ExecutionPolicy", "Bypass"], "editor.minimap.maxColumn": 300, "editor.minimap.renderCharacters": false, "editor.minimap.showSlider": "always", "liveServer.settings.donotShowInfoMsg": true, "liveSassCompile.settings.formats":[ { "format": "expanded", "extensionName": ".css", "savePath": "/assets/css" }, { "format": "compressed", "extensionName": ".min.css", "savePath": "/assets/css" } ], "php.validate.executablePath": "C:/xampp/php/php.exe", "editor.cursorBlinking": "smooth", "editor.cursorSmoothCaretAnimation": true, "explorer.confirmDelete": false, "editor.renderWhitespace": "none", "vim.startInInsertMode": true, } Already tried to just append something like this in the settings.json, it also does not work { "vim.insertModeKeyBindingsNonRecursive": [ { "before": ["j", "k"], "after": ["<ESC>"] } ], } -
Want to load second element list on selection on first element in Django forms
How do I load university list based on selected country. In the attached image I am getting all the country universities. Forms.py countries_list=list(Countries.objects.all().values_list('id','name')) universities_list=list(Universities.objects.all().values_list('id','name')) class ConsolidatedSheetDownloadForm(forms.Form): countries = forms.ChoiceField(choices=countries_list, required=True,error_messages={'required': 'Select country to proceed'}) universities = forms.MultipleChoiceField(choices=universities_list, required=True,error_messages={'required': 'Select university to proceed'}) https://i.stack.imgur.com/8ANvb.png -
Deploy Django app to Heroku end with Error
Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tailenter code here Log file: 2022-01-25T09:56:52.826338+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 242, in handle_chld 2022-01-25T09:56:52.826405+00:00 app[web.1]: self.reap_workers() 2022-01-25T09:56:52.826413+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2022-01-25T09:56:52.826514+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2022-01-25T09:56:52.826544+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2022-01-25T09:56:53.005213+00:00 heroku[web.1]: Process exited with status 1 2022-01-25T09:56:53.060263+00:00 heroku[web.1]: State changed from starting to crashed 2022-01-25T09:56:58.000000+00:00 app[api]: Build succeeded 2022-01-25T09:57:06.746469+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sheikhshahed.herokuapp.com request_id=5096cca5-60ee-4038-b90a-30ab5d4b13fe fwd="106.0.54.74" dyno= connect= service= status=503 bytes= protocol=https 2022-01-25T09:57:07.638428+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sheikhshahed.herokuapp.com request_id=245c9fab-4633-4387-805b-3255291496c6 fwd="106.0.54.74" dyno= connect= service= status=503 bytes= protocol=https -
Django: User login not works for some users
I'm currently learning django. Here is my problem: user created using terminal with createsuperuser can log in to the website, but users created with my register page are not. Users created using my registration appear in the admin panel and all fields match the entered data. I guess the problem is somewhere in CustomUserManager(before creating it login worked properly) models.py class CustomUserManager(BaseUserManager): def create_superuser(self, email, username, first_name, bio, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError("Superuser must be assigned staff to True") if other_fields.get('is_superuser') is not True: raise ValueError("Superuser must be assigned superuser to True") return self.create_user(email, username, first_name, bio, password, **other_fields) def create_user(self, email, username, first_name, bio, password, **other_fields): if not email: raise ValueError("You must provide an email.") email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, bio=bio, **other_fields) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=200, null=True, verbose_name="Имя") username = models.CharField( max_length=50, null=True, verbose_name="Никнейм", unique=True) email = models.EmailField(null=True, unique=True) bio = models.TextField(null=True, blank=True) avatar = models.ImageField(null=True, default="avatar.svg", blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','username','bio'] def __str__(self): return self.username views.py def loginPage(request): page = 'login' if request.user.is_authenticated: return redirect('home') if request.method == … -
how do I transfer data from a form to another page immediately?
Help, please! I'm writing a simple donation site in Django. I want to use LiqPay payment system. I've described a form which takes data from user (def donation), but I can't figure out how to pass this data to another function (class PayView, def get) I've tried creating a user and then taking the 'amount' field from it, but I don't want to force users to register. 'PayView' is rendered immediately after 'submit' in 'def donation' My code: views.py def donation(request): if request.method == 'POST': form = CheckoutForm(request.POST) if form.is_valid(): Donation.objects.create(**form.cleaned_data) return redirect('pay_view') else: form = CheckoutForm() return render(request, 'donation/donation.html', {'form': form}) class PayView(TemplateView): template_name = 'donation/pay.html' def get(self, request, *args, **kwargs): liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) params = { 'action': 'pay', 'amount': '1', 'currency': 'UAH', 'description': 'Допомога фонду', 'order_id': 'order_id_1', 'version': '3', 'sandbox': 1, # sandbox mode, set to 1 to enable it 'server_url': '', # url to callback view } signature = liqpay.cnb_signature(params) data = liqpay.cnb_data(params) return render(request, self.template_name, {'signature': signature, 'data': data}) forms.py from django import forms class CheckoutForm(forms.Form): amount = forms.IntegerField() first_name = forms.CharField() last_name = forms.CharField() phone = forms.CharField() email = forms.EmailField() Sorry for the silly question. I am very new to this. Thanks! -
Downgrade django version from 3.2 to 1.8 [closed]
my project is developed on django 3.2 now i want to downgrade it to version 1.8 because it needed. What would be the best course of action for achieving that? I tried by changing version in requirement.txt got compatibility error of django with other module. -
Why am i getting this error when i run python manage.py shell in terminal? [closed]
File "c:\users\hp\appdata\local\programs\python\python39\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to <undefined> -
Why can't I see my NGINX log's when my app is deployed to Azure app services, but it works fine locally?
I have a Dockerized Django application, which I'm orchestrating with Supervisor, which is not optimal but needed when hosting on Azure app services as their multi-app support with docker-compose is still in preview mode (aka. beta). According to best-practises I have configured each application within supervisord to emit the logs to STDOUT. It works fine when I create the Docker image locally, run it and check the docker logs. However, when I have deployed it to Azure app services and check the logs, my web-application (Gunicorn) is logging as expected, however, the logs from NGINX don't appear at all. I have tried different configurations in my Dockerfile for linking the log files generated by NGINX (linking to both /dev/stdout and /dev/fd/1 for example) and I have also gone into the the nginx.conf config and trying to log out directly to /dev/stdout. But whatever I do it work fine locally, but on Azure the logs don't show any NGINX-logs. I've pasted relevant configuration files, where you can see the commented lines with the options I've tried with. Hope someone can help me figure this one out. Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 ################### # PACKAGE INSTALLS ################### RUN apt-get update RUN … -
How to resolve django-q qcluster type error?
I'm trying to set up scheduled tasks in my django server using qlcuster following this tutorial. Some objects in my database have an expiration date field that is set for each new object, so I want to have a worker checking every day for the objects past their expiration date and remove them. My task is written as follows : from datetime import datetime from .models import MyObject def delete_expired_objects(): """ Deletes all objects expired """ expired_obj = MyObject.objects.filter(expirationDate__lte=datetime.today()) expired_obj.delete() The schedule is set no problem, but when running the scheduler it throws some errors saying that the type is incorrect as it is apparently not expecting a string : Message: TypeError('unsupported type for timedelta seconds component: str') Arguments: ('Traceback (most recent call last):\n File "/usr/local/lib/python3.10/site-packages/django_q/cluster.py", line 345, in pusher\n task_set = broker.dequeue()\n File "/usr/local/lib/python3.10/site-packages/django_q/brokers/orm.py", line 64, in dequeue\n tasks = self.get_connection().filter(key=self.list_key, lock__lt=_timeout())[\n File "/usr/local/lib/python3.10/site-packages/django_q/brokers/orm.py", line 14, in _timeout\n return timezone.now() - timedelta(seconds=Conf.RETRY)\nTypeError: unsupported type for timedelta seconds component: str\n',) Is there a way to give it an int while still checking if the date is older than today ? -
how to save a model object in another model save method
I have user model that has a one to one relation with two other models. these are my models: class User(AbstractUser): id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) isPreRegistered = models.BooleanField(default=False) username = models.CharField(unique=True, max_length=13) first_name = models.CharField(max_length=32, null=True, default=None) last_name = models.CharField(max_length=64, null=True, default=None) progress_level = models.CharField(max_length=25, null=True, choices=USER_PROGRESS_LEVELS) class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) final_assessment = models.TextField(null=True, blank=True) is_interviewed = models.BooleanField(default=False) class PsychologicInfo(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) final_assessment = models.TextField(null=True, blank=True) is_interviewed = models.BooleanField(default=False) I want to update the user's progress_level if PsychologicInfo.is_interviewed and ScientificInfo.is_interviewed are both True. So I thought I should override the save method and added this to the user model: def save(self, *args, **kwargs): if self.scientificinfo.is_interviewed == True and self.psychologicinfo.is_interviewed == True: self.progress_level = USER_PROGRESS_LEVELS[1][0] return super(User, self).save(*args, **kwargs) But I have to save the User object one more time to see some results. how can I update my progress level field when PsychologicInfo and ScientificInfo get saved? -
Strange module behavior djangoql
We use djangoql for easy search in our django admin panel. The mixin DjangoQLSearchMixin has been added to some of our models in the admin panel. And sometimes after deployment we get an error in the handler application_name/model_name/introspect/ Error: FieldDoesNotExist at /admin/user/user/introspect/ Model_name has no field named 'field_name' After the reboot, the error disappears. The error cannot be reproduced locally. -
Django filter JSONField when key is a number
node_status is JOSNField, how to filter node_status of queryset has key '2'==True >>> instance.node_status {'cat': '1', '2': True, 'dog': True} >>> qs.filter(node_status__cat=1) Yeah got result >>> qs.filter(node_status__has_key='dog') Yeah got result >>> qs.filter(node_status__2=True) <QuerySet []> node_status__2=True got empty queryset. -
how to use Django channels in another clients?
I have created a chat program with Django channels I want to use this program on another client such as Android or desktop With JavaScript, we can create sockets, connect chat programs, and send and receive messages I want to know how can I use the chat program on another client? Do I need to create an api for the chat app? Or is everything created in a client program like JavaScript? Do I need to create an api for my app? -
Is request available inside django to_representation serializer method?
I am trying to perform a request check inside the to_representation serializer method in django but the self.context is always empty. Any ideas why? class TwitterAccountsListsSerializer(serializers.ModelSerializer): class Meta: model = TwitterAccountsList fields = ["id", "name", "created_at", "is_private", "accounts"] extra_kwargs = { "accounts": {"write_only": True}, } def to_representation(self, instance): import pdb; pdb.set_trace() # self.context is always an empty dict here {} return super().to_representation(instance)