Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form validation django
I am a beginner,I got this assignment in which I have to create django app. But am not able to understand how to do that ,so below are the requirements of the app. The app should have to form and each form should have proper JavaScript validation. The inputs in the first form say (gender of the applicant) should determine the field shown on the second form. I didn't understood the 2 nd point , do i have to create log in /sign up or what -
Ordering by computed field in admin panel
I'm learning Django and I got stuck on this problem I'm basically trying to order by a computed field in an admin panel view, I've read some "tutorials" like this: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/sorting_calculated_fields.html on google but I can't seem to figure out how it all works (between annotations etc) Here's my classes: class StockAdmin(admin.ModelAdmin): list_display = ("ticker_symbol", "security_name", "current_pretax_yield", "current_aftertax_yield", "displayed_price") search_fields = ("ticker_symbol", "security_name") def current_pretax_yield(self, obj): try: curyield = float(obj.coupon_amount/obj.last_price) return str(round((curyield*100),3)) + "%" except: return "n/a" def current_aftertax_yield(self, obj): try: withholding_tax = 15 at_yield = ((obj.coupon_amount/obj.last_price*100)*(1-(withholding_tax/100))*0.74) return str(round(at_yield, 2)) + "%" except: return "n/a" def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate( _current_aftertax_yield=self.current_aftertax_yield(), _current_pretax_yield=self.current_pretax_yield(), ) current_aftertax_yield.admin_order_field = '_current_aftertax_yield' current_pretax_yield.admin_order_field = '_current_pretax_yield' Basically, I want to get "coupon amount" and "last price" fields from the database, perform the calculations you see in the functions, then display those calculated files in the admin panel and be able to "order by" them The code as I have now errors out with a TypeError: current_aftertax_yield() missing 1 required positional argument: 'obj' I've tried to follow this: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/sorting_calculated_fields.html but I can't quite figure it out on my own.. Any ideas? Is there an easier way of doing this? I used a lot of … -
Authenticate several apps with same Oauth2 provider using one callback url
I currently have a chrome extension which authorizes with an Oauth2 provider and then authenticates with my django rest framework backend using allauth. I want to add two new apps to the same backend; a iOS app and an Android app. They shall both use the same Oauth2 provider. Currently the Oauth provider has stopped the possibility to add new apps, which means I only have the possibility of ONE callback url, which is currently used by the Chrome extension. Is there a way of designing the auth flow to send redirect and callback to the backend for all three (using just one callback url), and somehow be able to send my backends api token back to the apps? -
Uncaught TypeError: Cannot read properties of undefined (reading 'childNode')
hi I am trying to follow the below tutorial for my formset only i find problem in part: container.insertBefore (newForm, addButton) and the error that presents me is the following: calculos.js: 195 Uncaught TypeError: Cannot read properties of undefined (reading 'childNode') I've already tried everything but can't find the childNode JS let parteForm = document.querySelectorAll(".part-form") let container = document.querySelector("#part-form-container") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = parteForm.length-1 // Get the number of the last form on the page with zero-based indexing addButton.addEventListener('click', addForm) function addForm(){ //e.preventDefault() let newForm = parteForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`,'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`) container.insertBefore(newForm, addButton) //parentnode.insertbefore(newnode,elnodoantesdelcualseinsertanewnode) //#part-form-container.insertbefore(div.part-form,) totalForms.setAttribute('value', `${formNum+1}`) } HTML <form method="POST" id="part-form-container"> {% csrf_token %} <div class="row"> <div class="col-12"> <div class="card"> <div class="card-body"> <div class="row mb-3"> <div class="col-md-12"> <div class="mb-3"> <label for="verticalnav-email-input">Summary</label> {{presupuestosparteform.resumen}} </div> </div> </div> <h4 class="card-title">Parts list</h4> <p class="card-title-desc">Add the parts that you need to include.</p> <input type="button" class="btn btn-block btn-default btn-success mb-4" id="add-form" onclick="addForm()" value="+ Add part" /> <div class="table-responsive"> <table class="table table-bordered table-nowrap align-middle" id="childTable1"> <tbody> {{ formset.management_form }} {% for form in formset %} <div class="part-form"> <tr> <td> {{form.codigo}} </td> <td> {{form.descripcion}} </td> </tr> </div> {% endfor %} </tbody> </table> </form> -
xxxx matching query does not exist
I am trying to query data from a csv file to django, this is the code of the query : from django.core.management.base import BaseCommand import pandas as pd from website.models import Product class Command(BaseCommand): help='import booms' def add_arguments(self, parser): pass def handle(self,*args,**options): df=pd.read_excel('tt.xlsx',engine='openpyxl') for P_N,P_P in zip(df.Product_name,df.Price): models=Product.objects.get(Product_Name=P_N,Product_Price=P_P) models.save() here this the code of my models.py : from django.db import models # Create your models here. class Product(models.Model): Product_Name=models.TextField() Product_Price=models.TextField() #Product_Link=models.TextField() def __str__(self): return self.name knowing that my csv file is the following : http://prntscr.com/26cjw4a the error that I'm getting is this "Product matching query does not exist " http://prntscr.com/26cjw9n -
Google Cloud Run: Cant connect to Postgress SQL
I am following this tutorial to upload my existing Django project running locally on sqlite to Google Cloud Run / Postgres. I have the cloud_sql_proxy service running and can sign into Postgres from the command line. I am at the point of running the command python manage.py migrate And I get the error: django.db.utils.OperationalError: connection to server on socket "/cloudsql/cgps-registration-2:us-central-1:cgps-reg-2-postgre-sql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? The answer to that questions is Yes, the server is running locally and accepting connections because I can log in with the Postgres client: agerson@agersons-iMac ~ % psql "sslmode=disable dbname=postgres user=postgres hostaddr=127.0.0.1" Password for user postgres: psql (14.1, server 13.4) Type "help" for help. postgres=> I double checked the connection string in my .env file and it has the correct UN / P Is this scoket not getting created somehow in a previous step? /cloudsql/cgps-registration-2:us-central-1:cgps-reg-2-postgre-sql/.s.PGSQL.5432 -
¿How to iterate through model images in production?
finally i deployed my first blog in heroku, but im stucked at serving each post image since in my local code whas iterating with image.url from the model. Now i have whitenoise configured but i dont know how to get the static image that is specific to each post from the model. This is my code actually: model: class BlogPost(models.Model): class BlogPostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='publicado') options = ( ('borrador', 'Borrador'), ('publicado', 'Publicado') ) categoria = models.ForeignKey(BlogCategoria, on_delete=models.PROTECT,default=1) titulo = models.CharField(max_length=250) excerpt = models.TextField(null=True,max_length=200) contenido = RichTextField() slug = models.SlugField(max_length=250, unique_for_date='publicado',null=False, unique=True) publicado = models.DateTimeField(default=timezone.now) autor = models.ForeignKey(Usuario,on_delete=models.CASCADE,related_name="autor") status = models.CharField(max_length=10,choices=options,default='borrador') imagen = models.ImageField(default= "empty.jpg" ,null=True, blank = True) likes = models.ManyToManyField(Usuario, related_name="blog_post") objects = models.Manager() postobjects = BlogPostObjects() view: class BlogInicio(ListView): template_name = "Blog/blog_inicio.html" model = BlogPost context_object_name = "posts" paginate_by = 6 template: {% for post in posts %} <div class="col-md-4" > <div class="card-content"> <div class="card-img"> {% if post.imagen %} <img src="{{post.imagen.url}}"/> {% else %} <img src="https://archive.org/download/placeholder-image/placeholder-image.jpg" /> {% endif %} <span><h4>{{post.autor}}</h4></span> <span style= "margin-top:43%;"><h4>{{post.categoria}}</h4></span> </div> <div class="card-desc"> <h3>{{post.titulo}}</h3> <p>{{post.excerpt|truncatechars:50}}</p> <a href="{% url 'blog:post_detalle' post.pk %}" class="btn-card">Leer</a> </div> </div> </div> {% endfor %} i know in line 6 from the template i could do a <img src="{% static … -
DJANGO How to know if an object pk is in my request.path
I need to compare an url with if condition in Django html template, to make an options menu selected when I'm on this page. I have this but doesn't works well: {% for vehiculo in vehiculos %} {% if "/calendar/vehicle/{{ vehiculo.pk }}/" in request.path %} <a class="list-group-item list-group-item-action active"> {% else %} <a class="list-group-item list-group-item-action"> {% endif %} {% endfor %} In my url I have this. But doesn't works!!! I don't find any solutions in Django docs or here in stackoverflow, github... Any solution is worth, thanks! -
Django Rest Framework Return on User's Resources in Nested Serializer
I am trying to return just the user's resources in a nested serializer response. My current response looks like this: { "id": 5174, "resourceName": "name here", "moreInformation": [ { "id": 15924, "infoName": "stuff here", "infoDetails": [ { "id": 51, "createdBy": 1, "detail": "detail here", "moreInformation": 15924 }, { "id": 52, "createdBy": 3, "detail": "detail here", "moreInformation": 15924 } ] } ] } I'm trying to make it to where when the user GETs the ResourceName endpoint, that the infoDetails only shows the infoDetails that were createdBy that user. The current response returns all of the infoDetails regardless of the createdBy field. I'm able to only return the infoDetail if the current user's id matches the createdBy id on the ListInfoDetails view, but not on the DetailResourceName view. Is there a way to do this on the serializer, or is it best to do it in the view? Views: class ListInfoDetail(generics.ListCreateAPIView): queryset = InfoDetail.objects.all() serializer_class = InfoDetailSerializer def get_queryset(self): user = self.request.user return user.infodetail_set.all() class DetailResourceName(generics.RetrieveAPIView): queryset = ResourceName.objects.all() serializer_class = ResourceNameDetailSerializer Serializers: class InfoDetailSerializer(serializers.ModelSerializer): class Meta: model = InfoDetail fields = ['id', 'created_by', 'mnemonic_picture', 'block'] class MoreInformationSerializer(serializers.ModelSerializer): info_details = InfoDetailSerializer(source="infodetail_set", many=True, read_only=True) class Meta: model = MoreInformation fields = ['id', … -
ValueError at /index.............The QuerySet value for an exact lookup must be limited to one result using slicing
I'm building a socialmedia website in django.While I tried to list all the comments in the index page, i am getting this error, The QuerySet value for an exact lookup must be limited to one result using slicing. what should i do in this case views.py.... def index(request): if request.user.is_authenticated: allPost = Post.objects.all().order_by('-created_on').filter(creater = request.user) allBlog = Blogpost.objects.all() comments = PostComment.objects.filter(post=allPost) context = {'allPost' : allPost, 'allBlog' : allBlog, 'comments' : comments} return render(request, 'index.html', context) else: return render(request, "signoption.html") models.py.... class PostComment(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.sno) + '.....comment By.....' + str(self.user) index.html.... {% for comment in comments %} <div class="comment"> <div class="comment-user"> <div class="comment-usr-dp"> <img src="{%static 'img/profile/profile.png'%}" alt=""> </div> </div> <div class="comments-usr-usrname"> <b><h1>{{comment.user.username}}</h1></b> </div> <div class="comment-text"> <h1>{{comment.comment}}</h1> </div> <div class="comment-time"> <h1>{{comment.created_on}}</h1> </div> </div> {%endfor%} -
'QuerySet' object has no attribute 'date_start'. Django rest framework
I am new to Django. In my project I want to filter all the room with available status, then I want start_date to be updated to the current datetime. But I am getting the following error: 'QuerySet' object has no attribute 'start_date' I have the following class in the models.py: class RoomStatus(models.Model): room = models.ForeignKey(Room, on_delete=models.DO_NOTHING) class RoomStatusChoices(models.IntegerChoices): AVAILABLE = 1 UNAVAILABLE = 2 room_status = models.SmallIntegerField(choices=RoomStatusChoices.choices, default=RoomStatusChoices.AVAILABLE) start_date = models.DateTimeField(auto_now=True) In serializers.py I wrote an update with this code available_rooms = RoomStatus.objects.filter(room=room, room_status=RoomStatusChoices.AVAILABLE) print(available_rooms) available_rooms.start_date = max(available_rooms.start_date, datetime.now()) The result of print(available_rooms) is <QuerySet []> Can someone help me? thanks indvance. -
how to grab a data from existing field in Django
I have a web page that I have to connect with Django. So I have an existing form with input and submit button. I have created a model and form. I put {{form}} tag and a little unstyled form appeared. but I want to grab a data from the one in HTML file. The code: form file: class NumberForm(ModelForm): class Meta: model = Number fields = "__all__" HTML: <form action="#" method="post"> {% csrf_token %} {{ form }} <div class="line <input type="text" class="form-control" name="phoneNumber" id="phoneNumber2" value="" placeholder="+7 (___) ___-__-__"> <button class="button_blue">t</button> </div> <label class="container_checkbox"> <input type="checkbox" checked="checked"> <span class="checkmark"></span> </label> </form> -
User.username as foreign key in table - django
My models.py file is having this model with required packages class Userdetails(models.Model): user_id=models.IntegerField(primary_key=True) user_name=models.ForeignKey(User, null=True,on_delete=models.CASCADE)``` I am using User model of Django, I want to store username field of User model to the user_name. When i am trying to access Users.user_name, its giving some integer value instead of username. How to get the username copied to user_name I tried with db_column and to_field but both are showing errors. version iam using is django 4.0 -
reverse for url (*) with keyword arguments not found
I am a django rest/django noob. I am trying to reverse url @action(detail=True, methods=['post'], url_path='request-reset-email', url_name='request-reset-email') def request_reset_password_email(self, request, pk): ... uid64 = urlsafe_base64_encode(smart_bytes(user.id)) token = PasswordResetTokenGenerator().make_token(user) relativeLink = reverse('user-password-reset-confirm', kwargs={'uid64' : uid64, 'token': token}) and I have this other custom action @action(detail=False, methods=['get'], url_path='password-reset/<uid64>/<token>/', url_name='password-reset-confirm') def password_reset_confirm(self, request, uid64, token): pass and this is the urls file router = DefaultRouter() router.register('user', UserViewset, basename='user') urlpatterns = [ path('', include(router.urls)), path('<int:id>', include(router.urls)), ] the error NoReverseMatch at /user/2/request-reset-email/ Reverse for 'user-password-reset-confirm' with keyword arguments '{'uid64': 'Mg', 'token': 'az3s71-eae533db00d974ba7d7fc0dfd5e9e060'}' not found. 4 pattern(s) tried: ['(?P<id>[0-9]+)user/password-reset/<uid64>/<token>\\.(?P<format>[a-z0-9]+)/?$', '(?P<id>[0-9]+)user/password-reset/<uid64>/<token>//$', 'user/password-reset/<uid64>/<token>\\.(?P<format>[a-z0-9]+)/?$', 'user/password-reset/<uid64>/<token>//$'] -
Is there a way to seperate progammatic access to a Django Rest API from React access and what are the alternatives?
This is obviously a design question, and probably me overthinking. I was asked once how to generate API Keys and I explained the process of retrieving tokens( DjangoRest -> React) to which I was responded with "Thats for logging in/authentication, how would you implement 'Generate API key'". If my application is DjangoREST + React, this means my entire application is exposed as RESTful. Is there even a way to control the "frontend" access over being programmatically accessible, since "CLI/Scripting" users can just hit the login endpoint programmatically anyway? It seems like the only thing that can be done here with a React Front and DjangoREST backend is to limit the calls to each of the routes, but control "browser-based" requests vs cli-based requests are nearly impossible. (Unless I blacklist/whitelist by user agent but that seems highly unfeasble) What I am concluding is that the only way to "control" programmatic access effectively in Django is not to use a React Frontend, and then create separate URLs for the api. But then in this case, I am confused on the neccesity of client_IDs and client_secrets (as I have seen on other sites that offer an API), because if I simply blacklist a … -
In Django how to process the file inside request.FILES?
for file in request.FILES: print("") video_input_path = file img_output_path = 'output.jpg' subprocess.call(['ffmpeg', '-i', video_input_path, '-ss', '00:00:00.000', '-vframes', '1', img_output_path]) print("") I'm trying to generate a thumbnail for the File (Video) uploaded via Form, this is pure python solution for generating the thumbnail from any video (works for pictures too but there is a better solution with PIL) video_input_path = file How do I access the file itself here? As far as I know my only options are file = request.FILES['filename'] file.name # Gives name file.content_type # Gives Content type text/html etc file.size # Gives file's size in byte file.read() # Reads file -
How to render and navigate django based web pages with a click of button without refreshing the page (Ajax)
am doing a django project and I would like my navigation bar to be AJAX based in the sense that when I click the link of a particular page, the page is rendered without reloading/refreshing the original page. I have tried to use the django redirect function but without success. your help will be appreciated. -
Android Retrofit upload images and text in the same request
I have an Android app that has a form feature where I collect data, that data contains image answers and text answers and each answer has a question id that I need to send also to know which question to save answer to it in the backend API, I tried to send all answers both images and text in the same request using Retrofit but got some errors, so I thought in another solution, but it's not working anymore here is my code Here is my solution and I need to improve it Retrofit code to send a request with data @Multipart @POST(SUBMIT_FORM) suspend fun submitFormAPI( @Header("Authorization") token: String, @Part("questions_answers") questions_answers: List<QuestionAnswer>, @Part answer_image: MultipartBody.Part?, @Part("question_id") question_id: String?, ): Response<FormResponse> and here is the QuestionAnswer Model, I tried to put answer_image inside it but doesn't work data class QuestionAnswer( val question_id: String, val answer_value: String? = null, ) so in this function, after collecting the data I need to loop through questionImagesAnswers and send a request with the image and its question_id every iteration along with other answers in questionAnswers fun onFormSubmit() { val questionAnswers = mutableListOf<QuestionAnswer>() val questionImagesAnswers = mutableListOf<QuestionModel>() questionImagesAnswers.forEach { questionImagesAnswer -> formViewModel.submitFormAPI( token = token, questionAnswers … -
Avoid Booking past dates with django
I have created an appointment booking system however i want to avoid any past dates being booked before it reaches create booking object which is then saved to the database. Here is my views.py class BookingView(View): def get(self, request, *args, **kwargs): return render(request, "availability.html") def post(self, request, *args, **kwargs): form = AvailabilityForm(request.POST) if form.is_valid(): data = form. cleaned_data bookingList = Appointment.objects.filter(start__lt=data['end_time'], end__gt=data['start_time']) if not bookingList: booking = Appointment.objects.create( name=data["name"], email=data["email"], start=data["start_time"], end=data["end_time"] ) booking.save() name_user = data["name"] start_time = data["start_time"] end_time = data["end_time"] email_user = data["email"] send_mail("Virtual PT Session", f"Thanks {name_user} For Booking Your Appointment with us.\n" + f"Please join the following zoom link on {start_time} \n" + " https://us04web.zoom.us/j/8339571591?pwd=dG9MQy9nUWN6a0F2dUo4L04rQkxPQT09", "engage.fitness.training.1@gmail.com", [email_user], fail_silently=True) return render(request, "success.html", { "booking":booking },) else: name = data["name"] return render(request, "booked.html",{ "name":name, },) -
I am developing an blockchain project using Django and can I know how to resolve this error
Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\USER\Desktop\blockchain\wallet\views.py", line 17, in index live_bitcoin_price = live_price[1].getText() Exception Type: IndexError at / Exception Value: list index out of range #code of that function def index(request): if request.method == 'POST': addr = request.POST['addr'] res2 = requests.get('https://cryptowat.ch/') soup2 = bs4.BeautifulSoup(res2.text, 'lxml') live_price = soup2.find_all('span', {'class': 'price'}) live_bitcoin_price = live_price[1].getText() live_bitcoin_price1 = live_price[1].getText() res = requests.get('https://www.blockchain.com/btc/address/'+addr) if res: soup = bs4.BeautifulSoup(res.text, 'lxml') # bal = soup.find_all('span', {'class': 'sc-1ryi78w-0 bFGdFC sc-16b9dsl-1 iIOvXh u3ufsr-0 gXDEBk'}) bal = soup.find_all('span', {'class': 'sc-1ryi78w-0 gCzMgE sc-16b9dsl-1 kUAhZx u3ufsr-0 fGQJzg'}) bal[4].getText() final_bal = bal[4].getText() final_bal1 = final_bal.replace(" ", "").rstrip()[:-3].upper() transactions = bal[1].getText() total_received = bal[2].getText() total_received1 = total_received.replace(" ", "").rstrip()[:-3].upper() total_sent = bal[3].getText() total_sent1 = total_sent.replace(" ", "").rstrip()[:-3].upper() final_bal1_int = float(final_bal1) total_received1_int = float(total_received1) total_sent1_int = float(total_sent1) live_bitcoin_price1_int = float(live_bitcoin_price1) balance_usd = final_bal1_int*live_bitcoin_price1_int total_received_usd = total_received1_int*live_bitcoin_price1_int total_sent_usd = total_sent1_int*live_bitcoin_price1_int else: return redirect('/') -
Referencing foreign key in Django Python
How to assign a product in ProductInStore to an instance of a Product already in store? Basically i have a scrapper and im looping through all the products and i need to first create the Product instance, and then A ProductInStore instance which is connected to Product via foreignKey. And when i try to put in ProductInStore(product=id) thats how i wanted to reference that Product, i get an error ValueError: Cannot assign "11393": "ProductInStore.product" must be a "Product" instance. Do you have any idea how to reference it? class Product(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) product_category = models.ManyToManyField(EcommerceProductCategory) description = RichTextField(max_length=2000, null=True, blank=True) product_producer = models.ForeignKey('ProductProducer', on_delete=models.CASCADE) creator = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, blank=True, related_name='product_creator') points_from_reviews = models.DecimalField(max_digits=6, decimal_places=2, default=0, help_text='Średnia ocena produktu') unique_id = models.CharField(max_length=256, unique=True) type_of_unique_id = models.CharField(max_length=64) class ProductInStore(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) store = models.ForeignKey('Store', on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places=2, default=0, help_text='Cena w sklepie') currency = models.CharField(max_length=4) url = models.CharField(max_length=200) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) # ADD TO DATABASE try: db_product = Product.objects.create(name=name, slug=slug, product_producer_id=3, unique_id=id, description=description) db_product.product_category.set(parsed_categories) except: print('product already in database') ProductInStore.objects.create(product=,store=1,price=price,currency='PLN',url=url) -
How to fix add to cart functionality in django?
I'm building an ecommerce platform and I want to create the add to cart functionality in the website. But for some reason the Product Id is showing null. Here's the codes: models.py class Products(models.Model): seller = models.ForeignKey(SellerProfile, on_delete = models.CASCADE) title = models.CharField(max_length = 255) product_category = models.CharField(choices = CATEGORY_CHOICES, max_length = 100) description = models.TextField() price = models.FloatField(max_length= 5) class Cart(models.Model): buyer = models.ForeignKey(User, on_delete = models.CASCADE) products = models.ForeignKey(Products, on_delete = models.CASCADE) views.py def add_cart(request): product_id = Products.id new_product = Cart.objects.get_or_create(id=product_id, user=request.user) return redirect('/') When I try to click this link it gives me this error: Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x000002468A4F8550>. Any suggestion will be really helpful. Thank you -
Unable to create a container for a Django app
I was trying to make a basic container as a learning project that should download Django from PyPI and run the default server. For that I made 3 files i.e. docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY /requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ requirements.txt Django==4.0 the command that I used in terminal and the output are given below in the terminal snippet: samar@wasseypur:~/Desktop/project2/telusko$ sudo docker-compose run web django-admin startproject mysite . [sudo] password for samar: Creating telusko_web_run ... done Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "django-admin": executable file not found in $PATH: unknown ERROR: 1 -
Sort a displayed column defined by a custom model method in the Django admin interface
I want to be able to sort a table column defined using a custom method in the Django admin. I narrowed down the problem to this simple example in Django: models.py: from django.db import models class MyObject(models.Model): name = models.CharField(_("name"), max_length=255) layers = models.URLField(_("Layers"), blank=True, max_length=1024) choices = models.TextField( verbose_name=_("Choice values"), blank=True, help_text=_("Enter your choice"), ) class Meta: verbose_name = _("Object config") verbose_name_plural = _("Objects config") def __str__(self): # my custom method return self.name and admin.py: from django import forms from django.contrib import admin class MyObjectAdminForm(forms.ModelForm): """Form""" class Meta: model = models.MyObject fields = "__all__" help_texts = { "layers": "URL for the layers", } class MyObjectAdmin(admin.ModelAdmin): form = MyObjectAdminForm list_filter = ["name",] search_fields = ["name",] # I want the first column (__str__) to be sortable in the admin interface: list_display = ["__str__", ...] # the ... represent some other DB fields but for the moment I cannot sort that first column (it is grayed out, I cannot click on its title): So how could I sort the first column in this admin table as defined by the __str__() method of the MyObject model? (please note that I cannot change the model itself. I'm also brand new to Django, so don't … -
Django ORM aggregate over related array field
I have two models class Record(Model): scorable_entry = models.ForeignKey('Entry', null=True, blank=True, on_delete=models.CASCADE) class Entry(Model): scores = ArrayField(models.IntegerField(), null=True) and I need to sort Records based on the sum of scores on a related Entry model. Unfortunately, this naive code throws an error records .annotate(score_rows=Func(F('scorable_entry__scores'), function='unnest')) .aggregate(scores_sum=sum('score_rows')) .order_by('-scores_sum') django.db.utils.NotSupportedError: aggregate function calls cannot contain set-returning function calls I'm using unnest to convert array to rows first (because otherwise sum wouldn't work). Skipping unnesting doesn't work as sum doesn't operate on arrays django.db.utils.ProgrammingError: function sum(integer[]) does not exist HINT: No function matches the given name and argument types. You might need to add explicit type casts. What is the proper way to order elements by the sum of a related array using ORM? Django 3.1, Postgres 12.9