Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - SubQuery e function F()
I have 2 models (author and book). I want to annotate in the author model the highest book price for every authors (in order to manipulate it later). I would like to make a query with an internal sub-query using the F() function but the problem is that the F() is refered to the book model but I would like to refer it to the author model. I'll show that with an example. The models are shown below: class author: authorID = models.AutoField(primary_key = True, auto_created = True, unique = True) name = models.CharField(max_length=100) surname = models.CharField(max_length=100) class book: ownerID = models.ForeignKey(author, on_delete = models.CASCADE, related_name='hook') title = models.CharField(max_length=100) price = models.IntegerField() The query in question is as follows: value = author.objects.annotate(maxPrice = (book.objects.filter(ownerID = F('authorID')).order_by('-price') [0])) F('authorID') is refered to the book DB and so Django returns an error but I want to refer it to the author DB to achieve my goal. How can I do that? Thanks -
TypeError at /vendor/add-Menuproduct/ __init__() takes 2 positional arguments but 3 were given
form.py from django.forms import models from django.forms import ModelForm, Textarea from product.models import Product,MenuProducts from django import forms class ProductForm(ModelForm): class Meta: model = Product fields = ['category', 'image', 'title', 'description', 'price','stock'] class MenuProductForm(ModelForm): # Time = models.DateTimeField(widget=forms.DateInput(attrs={'class': 'form-control'})) class Meta: model = MenuProducts fields = [ 'YourProduct', 'Stock', 'Day', 'Time','city', 'address', 'ingredientA', 'ingredientB', 'ingredientC', 'PriceRange','city'] def __init__(self, user, **kwargs): super(MenuProductForm, self).__init__(**kwargs) self.fields['YourProduct'].queryset = Product.objects.filter(vendor__name=user) # widgets = { # 'Time': forms.DateInput(attrs={'class': 'form-control'}) # } form.py @login_required def add_Menu_product(request): if request.method == 'POST': print("Add Menu Product") print(request.user.vendor) form = MenuProductForm(request.POST, request.FILES) if form.is_valid(): Menuproduct = form.save(commit=False) # Because we have not given vendor yet Menuproduct.vendorfk = request.user.vendor # Menuproduct.slug = slugify(Menuproduct.title) Menuproduct.save() #finally save return redirect('vendor:vendor-admin') else: print("Form ") form = MenuProductForm(user=request.user.vendor) print(request.user.vendor) return render(request, 'vendor/add_menu_product.html', {'form': form}) What should be done in order to resolve this issue TypeError at /vendor/add-Menuproduct/ init() takes 2 positional arguments but 3 were given What should be done in order to resolve this issue TypeError at /vendor/add-Menuproduct/ init() takes 2 positional arguments but 3 were given -
query to get every user data belong
I want to write Query Set that show every User Access To Own IP and Asset_Name from django.db import models from django.contrib.auth.models import User class Asset(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) IP = models.GenericIPAddressField() Asset_name = models.CharField(max_length=255) I want every user see details(IP,Asset_Name) in own user Profile The problem comes when trying to query the database, and using a string compared to an auth.User object. I do not know how to get around this? -
How to create model object that via user foreignkey, FOREIGN KEY constraint failed?
In my view I am creating the object, and in this model that I am creating is one field, name=models.ForeignKey(User, on_delete=models.CASCADE). And I am using ForeignKey because in this oject can be made multiple time by a single user. And I get an error django.db.utils.IntegrityError: FOREIGN KEY constraint failed Here is the model: from django.contrib.auth.models import User ... class Customer_status(models.Model): name = models.ForeignKey(User, null=True, on_delete=models.CASCADE) creation_date = models.CharField(max_length=28) status=models.CharField(max_length = 8) def __str__(self): return str(self.name) + '_' +str(self.id) And in this view I am creating this model: def status_create(request): Customer_status.objects.create ( name=request.user, creation_date=datetime.datetime.now(), status='Pending' ) The thing is that I had OneToOne field on name and I had Unique integrity error, after I changed it to ManyToMany I have the this error django.db.utils.IntegrityError: FOREIGN KEY constraint failed. I am thinking that the error is causing the "name=request.user" in creating step -
How can I implement delete action in viewset in django?
Here is my view file. import json from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.parsers import JSONParser from django.http import JsonResponse from django.core import serializers from .serializers import TodoSerializer from .models import Todo # Create your views here. class TodoView(APIView): def post(self, request): serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.save() print(serializer.data) return JsonResponse(serializer.data, status=200) def get(self, request): obj_list = [] for item in Todo.objects.all(): if item.todo_delete is False: obj_list.append({"todo_id": item.todo_id, "todo_desc": item.todo_desc, "todo_complete": item.todo_complete, "todo_delete": item.todo_delete}) return JsonResponse({"todo": obj_list}, status=200) def update(self, request): return Response("Hello") def delete(self, request): print (request.data) return Response("Hello") I am going to implement delete action for specific todo by passing id. Front End Part is here. try { const res = await axios.delete(`${BASE_URL}/api/todo/${id}/`) } catch (e) { return { success: false, error: e } } And url file is here path('todo/', TodoView.as_view()), But I can see this error Not Found: /api/todo/e709750f-5bb6-4dba-b6b1-966beeeb9c3d/ How can I fix this error? How to set correct delete endpoint and get id from client? -
Django - How to redirect users without hard-coding URLS
I am creating Django Application. We want user to be redirected to new screen on button click, but we don't want to have to hardcode URL. We have a top level screen, and we want to redirect user to screens after they click a button on the Level screen, However, we have multiple level screens so it would't make sense to hardcode each URL for each section of the Level screen. Here is the view for the Level1 Screen as an example: def level1(request): return render(request, 'Levels/level/Welcome1.html') As you can see, we render out Welcome1.html, however, we also have other Welcome screens assosiated with level 1, like Welcome2.html and Welcome3.html. This is the URL for level 1: path('levels/level1/', views.level1, name = "level1") Again, it would't make sense for us to have a URL for each level (level 1, level2) and then all the subscreens for them such as Welcome1, Welcome2. How can I make it so I can associate different screens with a URL and not have to render them out individually? I am not sure how to go about doing this problem. We are working on big project and can give part of budget to someone who helps solve. -
Printing username on stdout with Django + Gunicorn Application
Right now my Django + Gunicorn app is printing only this info: [03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 If request is authorized, I would like to show also user (username/email) behind the status code, something like: [03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 - useremail@outlook.com If the request is not authorized then write UNAUTHORIZED: [03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 - UNAUTHORIZED How can I achieve this with a combination of Django and Gunicorn? Thank you -
Django-filter package how to render fields choices value dynamically?
I'm using Django-filter,I hard coded the model fields choices: models.py MSG_TYPE_CHOICES = ( ('success','success'), ('error','error'), ('warning','warning'), ) class Mymodel(models.Model): typeLevel = models.CharField(max_length=50, blank=True, null=True,verbose_name='MSG TYPE',choices=MSG_TYPE_CHOICES) # eg:exception Notice:the value of MSG_TYPE_CHOICES are the same as the values in typeLevel ,it means value of typeLevel are:success,error,warning . filter.py: class MyFilter(django_filters.FilterSet): class Meta: model = Mymodel fields = ['typeLevel'] views.py: def product_list(request): f = MyFilter(request.GET, queryset=Product.objects.all()) return render(request, 'my_app/template.html', {'filter': f}) template: <form method="get"> {{ filter.form}} </form> My question is instead of hard coded the MSG_TYPE_CHOICES in models.py ,is there any way I can get those value dynamically from the model filed typeLevel ,because I need the value of MSG_TYPE_CHOICES always keep the same with fields typeLevel ,if the value of typeLevel changes ,the MSG_TYPE_CHOICES need change too. -
How to change visibility on div multiple times with javascript and css?
I have a popup in my app: <div id="modal"></div> let modal = document.getElementById('modal') modal.innerHTML = ` <button class="close-button" onclick="close_modal()">Close</button> ` #modal{ width: 30em; height: 24em; overflow: hidden; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); visibility: hidden; } When I click certain button function is triggered which has modal.classList.add('open-modal') in it. .open-modal{ visibility: visible !important; } close_modal function is: function close_modal(){ modal.classList.add('close-modal') } CSS: .close-modal{ visibility: hidden !important; } It works just fine once(i can open and close popup but when I try to open it second time it doesn't. Why is this happening and how to fix it? -
a music app ,where i was trying to display the album detail once it is newlycreated using reverse...recieving the below mentioned error please assist
Traceback (most recent call last): File "C:\Users\Sanath\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 184, in post return super().post(request, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 153, in post return self.form_valid(form) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 136, in form_valid return super().form_valid(form) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 65, in form_valid return HttpResponseRedirect(self.get_success_url()) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 125, in get_success_url url = self.object.get_absolute_url() File "C:\Users\Sanath\Desktop\website\music\models.py", line 12, in get_absolute_url return reverse('music:detail',kwargs = {'pk' : self.pk}) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\urls\base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\urls\resolvers.py", line 828, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with keyword arguments '{'pk': 11}' not found. 1 pattern(s) tried: ['music/(?P<album_id>[0-9]+)/\\Z'] urls.py from django.urls import path from . import views app_name = 'music' urlpatterns = [ #music/ path('', views.index,name = 'index'), #music/71/ path('<int:album_id>/', views.detail,name = 'detail'), path("register/",views.UserFormView.as_view(),name = 'register'), path("album/add/",views.albumcreate.as_view(),name = 'album-add'), #url pattern for the view albumcreate ] models.py from django.db import models from django.urls import reverse # Create your models here. class album(models.Model): #inherit from models.Model artist = models.CharField(max_length=250) #when migrated to db it will … -
django query with manytomany as list
I'm working with django (4.1) and I have a problem with a QuerySet. models.py class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ['title'] def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) class Meta: ordering = ['headline'] def __str__(self): return self.headline python manage.py shell >>> from many2many.models import Article, Publication >>> qsA = Article.objects.values("id","headline","publications") >>> qsP = Publication.objects.values("id","title") >>> for a in qsA: ... print(a) ... {'id': 1, 'headline': 'A', 'publications': 1} {'id': 1, 'headline': 'A', 'publications': 2} {'id': 2, 'headline': 'B', 'publications': 3} {'id': 2, 'headline': 'B', 'publications': 4} >>> for a in qsP: ... print(a) ... {'id': 1, 'title': 'tA1'} {'id': 2, 'title': 'tA2'} {'id': 3, 'title': 'tB1'} {'id': 4, 'title': 'tB2'} >>> I'd like to have a QuerySet that returns the "headline" of the Articles, and the list of the "title" of the Publication. Something like {'headline': 'A', 'list_publications': 'tA1 tA2'} {'headline': 'B', 'list_publications': 'tB1 tB2'} -
How to translate the route system in django 1 to django 2,3?
In tutorial the author used an old version of urls.py in urlpatterns and I cannot translate url(r'^image/(?P<width>[0-9]+)x(?P<height>[0-9]+)/$') this into path() Thanks a lot I would like to resolve this issue -
! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/mighty-island-82287.git' error
I enter git push heroku main and so: Total 0 (delta 0), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: Traceback (most recent call last): remote: File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> remote: r = f.read().strip() remote: File "/usr/lib/python3.10/codecs.py", line 322, in decode remote: (result, consumed) = self._buffer_decode(data, self.errors, final) remote: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte remote: /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 9: warning: command substitution: ignored null byte in input remote: ' is not available for this stack (heroku-22). remote: ! For supported versions, see: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 50c9a488b59502f133b3cce812e40e89000d2414 remote: ! remote: ! We have detected that you have triggered a build from source code with version 50c9a488b59502f133b3cce812e40e89000d2414 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different … -
when I want to deploy my djnago project to aws elastic beanstalk it gives me error
when I want to deploy my Django project to AWS elastic beanstalk it gives me the error this is my error and I do not know how to fix it -
How to implement async await function in Django application when retrieving information from remote database
I have a Django application where I am retrieving information from remote Oracle database and I populate those information in chart using Chart.js. As you can see in my code, I am calling two times connection to database since I am popul.ating two charts The point is that process of retrieving information sometimes is taking so much time, and I read there is option to include async await option , where I can decrease I/O time. (attach and gngp_ntp is query that I am taking from other .py file) Can someone help me how to make simple async below function. def index(request): cursor1=connections['default'].cursor() cursor1.execute(attach) // execute the query r1= dictfetchall(cursor1) cursor2=connections['default'].cursor() cursor2.execute(gngp_ntp)// execute the query r2= dictfetchall(cursor2) return render(request,'app_sins/ps_capacity.html', {"all_post" : r1,"jokso" : r2}) -
django-imagekit - do not crash when source file does not exist
I have a Django model that has an image and an autogenerated thumbnail: img = ImageField(upload_to=..., max_length=64) img_thumbnail = ImageSpecField([ResizeToFit(width=64, height=64)], source='img') For a number of reasons, the img field may contain a filename that is no longer present in the filesystem. When the file is not there, the view crashes with a FileNotFoundError - No such file or directory: '....png' Is it possible to configure the img_thumbnail field / django-imagekit to fail silently? Also without writing having to catch the exception in the view. -
API Query in Django Rest Framework
I have created an API from Database, I can view the API but I am unable to do a query via URL for example: 127.0.0.1:8000/author?author_id=9, I am not sure where to add the query code. I want to filter using fields. Here is my models.py class AuthorAPI(models.Model): author_id=models.IntegerField() name=models.TextField() author_img_url=models.TextField() title=models.TextField() first_published_at=models.DateTimeField() excerpt=models.TextField() class Meta: db_table = 'view_author' serializers.py from rest_framework import serializers from .models import SortAPI, AuthorAPI class AuthorAPISerializer(serializers.ModelSerializer): class Meta: model=AuthorAPI fields='__all__' views.py from .serializers import APISerializer,AuthorAPISerializer from .models import SortAPI, AuthorAPI from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def getauthor(request): if request.method == 'GET': results = AuthorAPI.objects.all() serialize = AuthorAPISerializer(results, many=True) return Response(serialize.data) -
Django serializer possibility of either creating new object or using an existing
Below is an example input: 'abc_obj': { "comments": string, "ref": string, "customer": 1, "address": { "street": string, "country": string, } } This is the serializer: class ABCObjSerializer(ModelSerializer[ABCObj]): address: AddressSerializer = AddressSerializer(required=False) customer: CustomerSerializer = CustomerSerializer(required=False) class Meta: model = ABCObj fields = "__all__" extra_kwargs = { "created_by": {"read_only": True}, } Is it possible with the existing serializer that I reuse / link the customer with the id=1. And in the next request if there is customer data (like address data in this request) then I create a new customer. The purpose is to enable the user to either create a new record or use an existing one. -
Display selection field in Django template
I 'm trying to find a workable solution for my problem. I have found two similar questions answered before, but still I can't solve it. If we have a class like this: from django.db import models class Consumer(models.Model): SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) name = models.CharField(max_length=60) size = models.CharField(max_length=2, choices=SHIRT_SIZES) And I did in my view and template like this (Learned from one tutorial) ***view with combined queries*** def staff_filter(request): qs = Consumer.objects.all() shirt_size= request.GET.get('size') # I have some other queries in between .... if is_valid_queryparam(size) and size!='Choose...': qs = qs.filter(size=consumer.get_size.display()) return qs def filter(request): qs=admin_staff_filter(request) context={ 'queryset':qs, 'consumer':consumer.objects.all() } return render(request, 'filter.html',context) **template*** <div class="form-group col-md-4"> <label for="size">size</label> <select id="size" class="form-control" name="size"> <option selected>Choose...</option> {% for size in consumer.get_size.display %} <option value="{{ size }}">{{size}}</option> {% endfor %} </select> </div> How should I correct it? Thanks! Display selection field in Django template -
Django model: get QuerySet from OneToOne
Let's say I have this model: class Place(models.Model): name = models.CharField(max_length=50) class Restaurant(models.Model): place = models.OneToOneField(Place, on_delete=models.CASCADE) And I have this QuerySet: <QuerySet [<Place: 123>, <Place: 456>]> I would like to get the list of Restaurants associated with the Place. I tried: restaurant_list = Restaurant.objects.filter(place__in=queryset) but it returns me a QuerySet of Place, not Restaurant: <QuerySet [<Place: 123>, <Place: 456>]> How can I get the Restaurant associated with the Place of my QuerySet? -
Changing the order of django objects in site using javascript
On the html page I have a list of songs {% for comp in composition %} .... <p>{{ comp.title }}<p> .... {% endfor %} also each track has two buttons: up and down. How to make it so that when you press the up or down button, the track changes with the neighboring track and so that the position of the tracks also changes in the django database. -
Difference between multiple gunicorn workers with one server instance and 1 gunicorn worker with multiple server instances
I have a django application running with gunicorn (with the gevent worker type) that is hosted on aws. What would the difference be between having 1 gunicorn worker but with multiple instances of the app hosted and having multiple workers but only with one instance of the app hosted? Or am I completely misunderstanding and these 2 things serve different purposes and is not related at all? -
DJango: AUTO REDIRECT TO DEFAULT LANGUAGE
Hi, I have a strange problem with my Django website. In my settings.py my default LANGUAGE_CODE = 'nl'. When I go to www.example.be with DEBUG = True then I am automatically redirected to www.example.be/nl. When I go to www.example.be with DEBUG = False then I am not redirected to the default language and I get "Server error (500)". Why is this not working when DEBUG = False? I checked for other posts regarding to this problem but I could not find a solution. -
AttributeError: Got AttributeError when attempting to get a value for field `review_rating` on serializer `ReviewSerializer`
i have the following issue error AttributeError: Got AttributeError when attempting to get a value for field `review_rating` on serializer `ReviewSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'review_rating'. This is my model model class Review(models.Model): review_id = models.AutoField(primary_key=True) review_message = models.CharField(max_length=300, blank=True) review_rating = models.IntegerField() serializer class ReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = '__all__' view class ReviewView(APIView): def get(self, request): queryset = Review.objects.all() serializer = ReviewSerializer(queryset) return Response(serializer.data, status=status.HTTP_200_OK) why am i getting this error -
Authenticate a wordpress website user to a django website
I have a pre-existing wordpress website and I am creating a django website which would provide other services to the users of the wp website. Now I want to display the products in the django website but I want to know how could I automatically authenticate the user while he has accessed the wordpress website so that the dynamic content of the website could be shown to him. Earlier I was trying to generate query in the url for the django website by I'm not a php guy and further I came across the idea of generating cookies from the wp website and retrieving it on the django website but I didn't know how to do this.