Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax and django template if condition
is there a way to use ajax to update Django template if condition? to update that the condition is satisfied for example i'm trying react system so i check if the user in the like field, if he's it displays the liked icon and if not it displays the like icon, my question is how to use ajax so when the user press like button it updates the template that the user has satisfied the condition the condition is like this ...{% if request.user in post.like.all %} the liked icon img in html tag {% else %} the like icon img in html tag {% endif %}... so how to use ajax to update the front end that the user is in the field so it displays the liked image -
Django ORM Annotation with another query
# My Database Models ModelA(models.Model): referancer = models.CharField() ... ModelXYZ(models.Model): name = models.CharField() ... I have models like top and function like below. # My Function modelXYZ_subquery = ModelXYZ.objects.filter(name__exact=OuterRef('referancer')).order_by('-id') modelA_dataset = ModelA.objects.filter(**my_custom_filters).annotate( has_XYZ=Exists(modelXYZ_subquery) latest_xyz=Subquery(modelXYZ_subquery.values('id')[:1], output_field=IntegerField) ) for _modelA in modelA_dataset: my_custom_function_1(_modelA) if _modelA.has_XYZ: detected_xyz = ModelXYZ.objects.get(id=_modelA.latest_xyz) # Unnecessary Database hit 1. else: detected_xyz = create_xyz(_modelA) my_custom_function_2(_modelA, detected_xyz) This function is working for too long because of the huge dataset and I want to get rid of the unnecessarry database hit I got there. Is there anyway to use it like below or achiving this goal with prefetch_related or something?. modelXYZ_subquery = ModelXYZ.objects.filter(name__exact=OuterRef('referancer')).order_by('-id') modelA_dataset = ModelA.objects.filter(**my_custom_filters).annotate( has_XYZ=Exists(modelXYZ_subquery) latest_xyz=Subquery(modelXYZ_subquery.values('id')[:1], output_field=IntegerField) ) for _modelA in modelA_dataset: my_custom_function_1(_modelA) if _modelA.has_XYZ: detected_xyz = _model.latest_xyz # No unneccessarry database hit anymore. else: detected_xyz = create_xyz(_modelA) my_custom_function_2(_modelA, detected_xyz) -
Django: check on model with manytomany field if object is in that list with filter
Let's say we have a Notification model with manytomany=ManyToManyField(User) field with User model. How to annotate a field is_in_manytomany to return boolean with True and False only depending on a condition, whether self.request.user is in Notification ManyToMany field or not. This code below returns weird True and False and also None, regardless of the default value of BooleanField. user = User.objects.get(id=1) qs = Notification.objects.all().annotate( is_in_manytomany =ExpressionWrapper( Q(manytomany__in = [user]), output_field=BooleanField(default=True) ) ) for item in qs: print(item.is_in_manytomany) -
problem with NoReverseMatch in Python(Django)
I created a website based on Django, and clicking on the trash displays an error. I can't understand what this is related to. I understand that there is not much information, but if you have any suggestions about what this is related to, please tell me! I attach the error Error Error during template rendering In template C:\Users\User\Desktop\sex\PythonShopDjango\shop\mainapp\templates\base.html, error at line 35 Reverse for 'change_qty' with keyword arguments '{'ct_model': '', 'slug': ''}' not found. 1 pattern(s) tried: ['change\-qty/(?P<ct_model>[^/]+)/(?P[^/]+)/$'] 26 </style> 27 <body> 28 29 <!-- Navigation --> 30 <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> 31 <div class="container"> 32 <div class="sign-wrap-4"> 33 <div class="sign_word">O<span>a</span>s<span>i</span><span>s</span></div> 34 </div> 35 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> 36 <span class="navbar-toggler-icon"></span> 37 </button> 38 <div class="collapse navbar-collapse" id="navbarResponsive"> 39 <ul class="navbar-nav ml-auto"> 40 <li class="nav-item"> 41 <a class="nav-link" style="color: #fffafa" href="{% url 'cart' %}">Корзина<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cart" viewBox="0 0 16 16"> 42 <path d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 … -
How fix the "mega.errors.RequestError: EARGS, You have passed invalid arguments to this command" error
i have make a web application with django and i upload data of user directly on my mega account with mega.py. When i deploy online on pythonanywhere, i got this error while the uploading. "mega.errors.RequestError: EARGS, You have passed invalid arguments to this command" -
How do I return the most sold item given a month and a year?
I need to be able to return the most sold item (and the quantity sold) given a month and a year. For example, if in a month: a) order 23: 2 cakes, 5 cupcakes b) order 21: 3 cupcakes Then I'd need it to return 5 cupcakes. How do I do this? This is the model: class Food(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Order(models.Model): food = models.ManyToManyField('Food', related_name='order', blank=True) def __str__(self): return self.food Ths is the serializer: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' class FoodSerializer(serializers.ModelSerializer): class Meta: model = Food fields = '__all__' -
Django permissions for PasswordResetView
I am using django.contrib.auth.views to provide a reset email page to my users. The page to reset the password is generated as follow : path("user/reset_password/", auth_views.PasswordResetView.as_view(template_name="accounts/reset_password.html"), name="reset_password"), However my users can still access this page when logged in. How can I control the permissions to access the page since I do not have direct access to the view ? -
Python pip raising NewConnectionError while installing django-braces
I am getting the following error when I tried to install django-braces: WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000168673EC2E0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /packages/6d/ce/accaea120b323e62cb3bf8cce26892cdbfbf6b86d1b220fa2432b9b86acb/django_braces-1.14.0-py2.py3-none-any.whl I can install any other libraries without any problem. Questions: Is there any problem with django-braces ? If so, can you recommend an alternative to braces.SelectRelatedMixin ? Versions: python 3.9.2 django 3.1.7 -
Django Form - setting data
I'm improving my English, be patient My form is a ModelForm and all the necessary data is sent by the user, but I want dynamically set the field ["viagem"] with the last object in the queryset. How to set a field after sending the data def cadastro(request): dono = Dono.objects.get(user=request.user) if request.method == "POST": form = VendaForm(dono, request.POST) # Here I get the necessary data to call my qs colocador_id = form["colocador"].value() viagem = Colocador.objects.get(pk=colocador_id).viagem_set.last() # I want something like this form["viagem"] = viagem if form.is_valid(): form.save() else: print('error') print(form.errors) else: form = VendaForm(dono) context = {"form": form, } return render(request, 'dashboard/cadastro.html', context) print(form.errors) => <ul class="errorlist"><li>viagem<ul class="errorlist"><li>This field is required</li></ul></li></ul> -
Django command - django-admin command not working
i have tried to install django using below three command. Now when i execute the django-amdin command then its showing me below error. Even i cant see the django-admin --version. sudo apt install python3.8 sudo apt-get install python3-pip pip3 install Django Error is : Traceback (most recent call last): File "/home/dev/.local/bin/django-admin", line 7, in <module> from django.core.management import execute_from_command_line File "/home/dev/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 13, in <module> from django.apps import apps File "/home/dev/.local/lib/python3.5/site-packages/django/apps/__init__.py", line 1, in <module> from .config import AppConfig File "/home/dev/.local/lib/python3.5/site-packages/django/apps/config.py", line 7, in <module> from django.utils.deprecation import RemovedInDjango41Warning File "/home/dev/.local/lib/python3.5/site-packages/django/utils/deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async File "/home/dev/.local/lib/python3.5/site-packages/asgiref/sync.py", line 114 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax Please help here if anyone have an idea. -
DRF prefetch_related optimization problem
I'm trying to optimize the query I've written, but I can't optimize its menus and sub-menus. The problem is; Queries arise separately for each menu item and its sub-item. I use django-debug-toolbar and when I look at the queries tab I see more than 10 queries count Queries; SELECT ••• FROM "xxx_settings" (1 query) SELECT ••• FROM "xxx_menu" WHERE "xxx_menu" (1 query) SELECT ••• FROM "xxx_menuitem" INNER JOIN "xxx_menuitem" (8 similar queries) Models.py class Menu(models.Model): name = models.CharField(max_length=128, null=True, blank=True) class MenuItem(models.Model): menu = models.ForeignKey(Menu, on_delete=models.CASCADE) name = models.CharField(max_length=128) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='subitems') class Settings(models.Model): homepage_title = models.CharField(max_length=255) header_menu = models.ForeignKey(Menu, null=True, blank=True, on_delete=models.SET_NULL, related_name='HeaderMenu') Serializer.py class SettingsSerializer(serializers.ModelSerializer): header_menu = MenuSerializer(read_only=True) class Meta: model = Settings fields = '__all__' class MenuSerializer(serializers.ModelSerializer): menuitem_set = MenuItemSerializer(read_only=True, many=True) class Meta: model = Menu fields = '__all__' depth = 1 @staticmethod def setup_eager_loading(queryset): queryset = queryset.prefetch_related('menuitem_set') return queryset class MenuItemSerializer(serializers.ModelSerializer): subitems = serializers.SerializerMethodField() class Meta: model = MenuItem fields = '__all__' def get_subitems(self, obj): serializer_context = {'request': self.context.get('request')} children = MenuItem.objects.select_related('parent').prefetch_related('parent__menu__menuitem_set').filter( parent=obj) serializer = MenuItemSerializer(children, many=True, context=serializer_context) return serializer.data queryset queryset = Settings.objects.select_related('header_menu',).prefetch_related( 'header_menu__menuitem_set__subitems', 'header_menu__menuitem_set',) -
How can I pass an array to a Django form
I am trying to pass an array to my form that needs to be displayed as a select in my template, but the code I tried isn't working. def __init__(self,*args,**kwargs): self.categs = kwargs.pop('categs') super(CheckForm,self).__init__(*args,**kwargs) CHOICES = [(1,'Drop'),(2,'Mean'),(3,'Max'),(4,'Min')] missing = forms.ChoiceField(label = 'Please indicate how you want to handle missing values', widget=forms.RadioSelect, choices=CHOICES) nametar = forms.CharField(label = 'Please indicate the name of the prediction') dropcol = forms.ArrayField(choices = categs, label = 'Please select the column you want to drop')``` -
Django Extensions - Jupyter Not working. Django: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async
I have done many times in my career to jupyter notebook in Django projects. Today I don't know why its NOT Working. I have installed Django 3.0, Python 3.8.9, MySQL. Might be issue with version of Django or python. I put django-extensions in my installed apps. also put this settings file. import os os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" -
add new form whene click on button in javascripts and django
I'm new at using javascripts with Django I'm trying to create an html page that contains 2 button one click on one of them it add a form to the page, and if I click on the other button it add another form this is the html page <body> <div class="container"> <form action="{% url 'create_appointement' %}" method="post"> {% csrf_token %} <button type="submit" name="type" class="button1" id="button1">register patient</button> <button type="submit" name="type" class="button2" id="button2">non register patient</button> </form> <div id='form'> </div> </div> <script language="javascripts" type="text/javascripts" src="static/js/onclick.js"> </script> </body> and this is me trying to create this script, but it did not work document.addEventListener('DOMContentLoaded', function showAppointementForm() { document.getElementById("button1").onclick = function() { document.getElementById("form").innerHTML = ` <form action="{% url 'create_appointement_non_register_patient' %}" method="POST"> {{ form.media }} {{ form.as_p }} {% csrf_token %} <button type="submit" value="create_appointement_non_register_patient"> ok </button> </form> ` } document.getElementById("button2").onclick = function() { document.getElementById("form").innerHTML = ` <form action="{% url 'create_appointement_register_patient' %}" method="POST"> <p> <label for="patients">select a patient</label> <select name="patients" id="patients"> <option value="">-- select a patient --</option> {% for patient in patients %} <option value="{{patient}}">{{patient}}</option> {%empty%} <option value="nothing">nothing</option> {% endfor %} </select> </p> {{ form.media }} {{ form.as_p }} {% csrf_token %} <button type="submit" value="create_appointement_register_patient"> ok </button> </form> ` } }) is something wrong with my code in … -
i want inverse all the produts uploaded from the django admin panel?
here is the code how i am fetching them {% for category in smartphone_banners %} {% for product in category.product_detail_set.all %} <div class="swiper-slide py-2"> <a href="product/{{product.name}}/{{product.id}}" style="text-decoration: none;"> <img src="{{product.imageURL}}" alt="" style="width: 80%; margin: 0 auto;"> <h6 class="mt-1">{{product.name}}</h6> <p>₹{{product.price}}</p> </a> </div> {% endfor %} {% endfor %} |slice:"0::-1" how can I inverse them I hope you can help me if there is any another way then please tell me -
Error when creating user from custom model
I am relatively new to Django, but just finished creating a custom user model rather then using the base. When running createsuperuser im getting the following error stack: File "C:\Users\adamt\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\base_user.py", line 66, in save super().save(*args, **kwargs) TypeError: save() got an unexpected keyword argument 'user' My custom model and create_user and create_superuser are: def create_user(self, email, username, FirstName, Surname, password=None): if not email: raise ValueError("Users must have an Email Address") if not username: raise ValueError("Users must have a Username") if not FirstName: raise ValueError("Users must have a First Name") if not Surname: raise ValueError("Users must have a Surname") user = self.model( email=self.normalize_email(email), username=username, FirstName=FirstName, Surname=Surname, ) user.set_password(password) user.save(user=self._db) return user def create_superuser(self, email, username, FirstName, Surname, password): user = self.create_user( email=self.normalize_email(email), username=username, FirstName=FirstName, Surname=Surname, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(user=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name ="email", max_length=60, unique=True) username = models.CharField(max_length=100, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) DateofBirth = models.DateField(verbose_name="Date of Birth") MarketingOptIn = models.BooleanField(verbose_name="Marketing Opt In", default=False) FirstName = models.CharField(verbose_name="First Name", max_length=100) Surname = models.CharField(verbose_name="Surname", max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','FirstName','Surname', ] objects = … -
Image fields or Boolean fields in django forms widgets?
I am trying to add an image field in the widgets dictionary but I don't know what is the property for forms to do that. like forms.TextInput what should I use for an image field or a Boolean field? here the code is giving me error in image property of widgets dictionary. class CreateProductForm(ModelForm): class Meta: model = Product fields = ['name', 'price', 'category', 'description', 'image'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'price': forms.NumberInput(attrs={'class': 'form-control'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'class': 'form-control'}), 'image': forms.ImageInput(attrs={'class': 'form-control'}), } -
How can i set a custom values in models.py (Python - Django)
I'm beginner in python django and i want to put "test" in the "name" field of the "games" table with the class models.py. I read some documentation but it's complicated and i don't understand how can i do it. Thanks for help. from django.db import models from django.utils import timezone class games(models.Model): name = models.TextField(max_length=255) -
show list in django without html file
i have 2 models but i want to show name of artist in my output class Musician(models.Model): name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): name = models.CharField(max_length=100) artist = models.ForeignKey(Musician, on_delete=models.CASCADE) num_stars = models.IntegerField() i want to show artist name by HttpResponce funcction class Musician_list(View): def get(self, request): persons = Album.objects.all().values_list("artist__name").order_by("artist__name") return HttpResponse(persons) but this code dont show any things please help me. -
Django throwing attribute error and i dont know why it is happening
I am trying to take image input from user in Django first the code was working fine but when I tried to run this code after a week it is giving me an attribute error and I don't why it is happening I tried to search on the internet but they only say it is because of the wrong syntax. The line, where the error arises, is file_type = file_type.lower() and line will be at last in the product_details function views.py from django.shortcuts import render from django.http import HttpResponse from datetime import datetime from machine_website.models import contact_detail from machine_website.models import product_data from machine_website.forms import product_Form # Create your views here. def homepage(request): descp1 = product_data() descp1.disc = ' this is the discription' descp1.img = '2.jpg' descp2 = product_data() descp2.disc = ' this is the discription 2' descp2.img = '2.jpg' descp3 = product_data() descp3.disc = ' this is the discription 3' descp3.img = '5.jpg' descp = [descp1, descp2,descp3] return render(request,'homepage.html', {'descp': descp}) def contact(request): if request.method=="POST": name = request.POST.get('name') email = request.POST.get('email') desc = request.POST.get('desc') contact = contact_detail(name=name , email=email, desc=desc, date=datetime.today()) contact.save() return render(request,'contact.html') def services(request): return render(request,'services.html') def index(request): return HttpResponse("this is index page") def more(request): info = product_data.objects.all() … -
How to return object details and Aggregated data under the same Django Rest API
I want to return Object details and Aggregated data under the same Django rest api. Can it be possible from ModelViewSet? If not what is the correct way of doing this? Here is my Code. #Tin class TinTable(CoreModel): tin=models.CharField(unique=True, max_length=30) assessee_name=models.CharField(max_length=500) def __str__(self): return self.tin # Financial Year class FinancialYear(CoreModel): financial_year = models.CharField(max_length = 50) class Meta: ordering = ["start_year"] def __str__(self): return self.financial_year Ledger Class # Ledger class Ledger(CoreModel): UNDISPUTED = 0 APPEAL = 1 TRIB = 2 HC = 3 ONE_SEVENTY_THREE = 4 ONE_TWEENTY_ONE = 5 ADR = 6 Ledger_SECTION_CHOICES = ( (UNDISPUTED, 'Undisputed'), (APPEAL, 'Appeal'), (TRIB, 'Tribunal'), (HC, 'High Court'), (ONE_SEVENTY_THREE, '173'), (ONE_TWEENTY_ONE, '121/A'), (ADR, 'ADR') ) tin=models.ForeignKey(TinTable, on_delete = models.CASCADE) financial_year = models.ForeignKey(FinancialYear, on_delete = models.CASCADE) demand = models.FloatField(default = 0.0 ) #demand disputed_demand = models.FloatField(default=0.0) payment = models.FloatField(default = 0.0 ) #payment balance = models.FloatField(default = 0.0 ) status = models.PositiveSmallIntegerField( choices=Ledger_SECTION_CHOICES, default=UNDISPUTED) comment = models.CharField(max_length=500, blank=True) def __str__(self): return self.tin.tin Serializer of Ledger class LedgerSerializer(serializers.ModelSerializer): financial_year = serializers.PrimaryKeyRelatedField( queryset=FinancialYear.objects.all(), source='financial_year', write_only=True ) tin = serializers.PrimaryKeyRelatedField( queryset=TinTable.objects.all(), source='tin', write_only=True ) assessee_name = serializers.ReadOnlyField( source='tin.assessee_name' ) class Meta: model = Ledger fields = ('tin','assessee_name','financial_year','demand','disputed_demand', 'payment','status') View of Ledger class LedgerView(viewsets.ModelViewSet): serializer_class = LedgerSerializer queryset = Ledger.objects.active() … -
DRF: Functional view not returning Response as expected
In the Django Rest Framework, I am looking to have my view return a personalised message using the following line: return Response({"Message":f"Post {pk} successfully {prefix}liked by {destination}"}) What I expect it to return: {'Message': 'Post 130 successfully liked by 8'} What is actually returned: <Response [200]> Why is this happening? How can I return the expected message? Here is the full view if it helps: @api_view(['POST']) def like_view(request, pk, destination): #destination is the user_id post = Posts.objects.get(pk=pk) if post.is_expired == True: print("expired") return Response({"message":"post expired"}) if check_self_action(destination,post): return Response({"message":"cannot like own post"}) liked = check_like(destination, post) prefix = "" if liked: post.likes.remove(destination) prefix = "un" else: post.likes.add(destination) return Response({"Message":f"Post {pk} successfully {prefix}liked by {destination}"}) -
Django sets model time field three hour less from my current local time
I'm following the Django tutorial part 2 and have some troubles applying my local time to the models I've created. This is my time config from settings.py: TIME_ZONE = 'Europe/Kiev' USE_I18N = True USE_L10N = True USE_TZ = True These are models of my app. I suppose that an issue is somehow related with an error message that Pyright gives. But this code have been just copied and pasted from official Django tutorial. This picture shows actually my problem: time of record creating three hour less than my actual time -
not able to access uploaded media files in django
This is the error i am getting template does not exist This is my settings file I have added media root and media directory in settings.py -
display python function result in html django
I made a web application with django that execute a python function . this function runs every 5 second and prints results in console and I want to show the result in html page and the results extend to prior results in html file . the problem is when I press the button to start service, the function starts but the page is always in reloading and doesn't redirect to new page to show the function results in new page : this is my code : def index(request): login_form = LoginForm(request.POST, request.FILES) context = { "form": login_form, } if login_form.is_valid(): ip = login_form.cleaned_data.get('IP') port = login_form.cleaned_data.get('port') username = login_form.cleaned_data.get('username') password = login_form.cleaned_data.get('password') handle_uploaded_file(request.FILES["certificate"]) request.session['ip'] = ip request.session['port'] = port request.session['username'] = username request.session['password'] = password return redirect('monitor/', request.session) return render(request, "index.html", context) def monitor(request): ip = request.session['ip'] port = request.session['port'] username = request.session['username'] password = request.session['password'] p = sp.Popen(monitoring(ip, port, username, password), stdout=sp.PIPE, stderr=sp.PIPE) output, errors = p.communicate() return render(request, "monitor.html",{'output':output}) this is my html : html page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> </head> <body> <h3>{{ output }}</h3> </body> </html>