Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do we combine multiple tables to create a report table displaying all the columns with an auto-incrementing, regex defined ID of its own?
I have 3 models: class Student(models.Model): roll_number=models.IntegerField(primarykey=True) name=models.CharField(max_length=50) email=models.EmailField(max_length=60) city=models.CharField(max_length=20) class Course(models.Model): roll_number=ForeignKey(Student, on_delete=CASCADE) course=ForeignKey(CourseChoices, on_delete=CASCADE) class Fee(models.Model): roll_number=ForeignKey(Student, on_delete=CASCADE) total_fee=models.DecimalField(max_digits=7, decimal_places=2, default=0) discount=models.DecimalField(max_digits=5, decimal_places=2, default=0) Final_amount=models.DecimalField(max_digits=5, decimal_places=2, default=0) Amount_received=models.DecimalField(max_digits=5, decimal_places=2, default=0) Balance=models.DecimalField(max_digits=5, decimal_places=2, default=0) batch=models.CharField(validators=[batch_pattern]) Now, whatever data these tables hold, I want to display them together as: Track ID--Roll No.--Name--Email--City--Course--Total Fee--Discount--Final Amount--Amount Received--Balance--Batch These are the Column heads I want. The 'Track ID' should be the report's own primary key which I want to define using regex. Also, I want every instance to appear in this report with different Track ID. For example, if a student pays a partial fee, it will get recorded in a row with a Track ID. Whenever he/she pays the rest of the amount, should get recorded with the relevant Track ID as per its place in the sheet. I hope I'm explaining well what I intend to achieve here. If I'm not clear, kindly let me know and I'll explain everything with an example or something. Hope I get some help on this here. -
User-specific home page Django
I am trying to create a user-specific home page for my Django site (i.e., go directly to the logged-in user's page when the site is loaded). I am having trouble figuring out how to add the username to the URL path from the get-go. This is how I've typically created the path to the home page: urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), But essentially what I think I want to do is this: urlpatterns = [ path('admin/', admin.site.urls), path('<username>/', include('blog.urls')), So that the default home page when I run the server would be something like this : http://127.0.0.1:8000/someusername Is there a way to access the logged-in user by default automatically? -
Function call in another file not working in Django rest framework
I am using Django signals to trigger a task (sending mass emails to subscribers using Django celery package)when an admin post a blogpost is created from Django admin. The signal is triggered but the task function in the task file is not called. It's because I put a print function which is not printing inside the task function. My signlas.py file: from apps.blogs.celery_files.tasks import send_mails from apps.blogs.models import BlogPost,Subscribers from django.db.models.signals import post_save from django.dispatch import receiver def email_task(sender, instance, created, **kwargs): if created: print("@signals.py") send_mails.delay(5) post_save.connect(email_task, sender=BlogPost,dispatch_uid="email_task") My task.py file from __future__ import absolute_import, unicode_literals from celery import shared_task # from celery.decorators import task from apps.blogs.models import BlogPost,Subscribers from django.core.mail import send_mail from travel_crm.settings import EMAIL_HOST_USER from time import sleep @shared_task def send_mails(duration,*args, **kwargs): print("@send_mails.py") subscribers = Subscribers.objects.all() blog = BlogPost.objects.latest('date_created') for abc in subscribers: sleep(duration) print("i am inside loop") emailad = abc.email send_mail('New Blog Post ', f" Checkout our new blog with title {blog.title} ", EMAIL_HOST_USER, [emailad], fail_silently=False) Here. the print("@send_mails.py") is not executed but print("@signals.py") in signals.py file is executed. Hence, signals is received after the Blogpost model object is created but the function inside task.py which is send_mails is not executed. I have installed both celery … -
serve react from django
i'm trying to serve react from django and when i try to connect react with django api give me this message App.js:25 POST http://localhost:8000/api/try/ net::ERR_BLOCKED_BY_CLIENT this the APP.js import React, {useEffect} from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router , Switch, Link, Route} from "react-router-dom"; import Home from './Home' import Login from './Login' import axios from 'axios'; import API from "./endpoint" // import {API_URL } from "../constants"; const App=()=>{ const getData=async()=>{ const res=await fetch(API+'api/try/', { method :"POST", headers :{ "Content-Type": "application/json" }, body :JSON.stringify({ email :"mohamed" }) }) const data=await res.json(); console.log(data) } useEffect(()=>{ getData(); }) return ( <Router> <Link to="/login">login</Link> <Link to="/home">Home</Link> <Switch> <Route path="/home" component={Home} /> <Route path="/login" component={Login}/> </Switch> </Router> ) } export default App; and i havn't put proxy:"localhost:8000" in package.json and Procfile of django is web:gunicorn backend.wsgi -log-file- -
form.is_valid(): -- with ModelForm instead of form- User specific data - Django
So I am integrating user-specific data in my Django website and I have gotten it to kind of work. Right now it is working on a model called ToDoList with one field called "name" and a (form.Form) in my forms.py file. It works but now I need to change it to work with a different model called Sheet_Building that has many fields and more importantly a new form called SheetForm_Building that is a (form.ModelForm). Problem: I can't get my view in my views.py file to be able to support a form.ModelForm instead of a form.Form. Ill link my form and HTML below but it all works except for when I try to integrate the new ModelForm into the view. views.py def adddata_building(response): if response.method == "POST": form = CreateNewList(response.POST) if form.is_valid(): n = form.cleaned_data["name"] t = ToDoList(name=n) t.save() response.user.todolist.add(t) return HttpResponseRedirect("/front_page/sheets/list_data_building/") else: form = CreateNewList() return render(response, 'sheets/add_data/add_data_building.html', {'form': form}) models.py class ToDoList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", null=True) name = models.CharField(max_length=200) def __str__(self): return self.name CURRENT FORM IN forms.py class CreateNewList(forms.Form): name = forms.CharField(label="Name ", max_length=300) FORM NEEDED TO USE IN forms.py class CreateNewList(forms.ModelForm): class Meta: model = ToDoList fields = '__all__' create HTML <h3>Create a New To Do … -
Django identify if the last reply/comment is not by post author
I am trying to develop a blog site for myself. I have developed comment reply module successfully. But i am facing issue to notify blog author a unanswered comment or unanswered reply of a comment. Here is my Comment model- class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) reply = models.ForeignKey('Comment', null=True, related_name='replies', on_delete=models.DO_NOTHING) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}' . format(self.post.title, str(self.username)) Which produce a table a bellow- | id | content | timestamp | post_id | reply_id | username_id | | -- | ------- | --------- | ------- | -------- | ----------- | | 1 | Comment 1 | 2021-07-18 03:12:54.015803 | 2 | NULL | 1 | |2|Reply 1 to Comment 1|2021-07-18 03:12:59.940654| 2| 1| 1| |3| Reply 2 to Comment 1| 2021-07-18 03:13:07.965133| 2| 1| 1| |4| Reply 3 to Comment 1 | 2021-07-18 03:13:21.053474| 2| 1| 1| |5| Comment 2| 2021-07-18 03:15:21.765414| 2| NULL| 1| I want the "Comment 2" and "Reply 3 to Comment 1" what is not replied by post author. Best Regards, Samrat -
Django LOGGING exception handling
In my Django application I have below logging. The class common.loghandler.kafkaloghandler is used as logging handler. I would like to know how to handle the case where the kafkaloghandler itself produces the exception. It is part of third party application and I cannot change the code there. I would like to take care of that at my end. Due to the exception my rest of the code block did not work. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'common.loghandler.kafkaloghandler', 'filename': '/path/to/django/debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } -
Virtualenv for django in VS Code not working, What am I doing wrong?
I've been following a tutorial on how to start using django and creating a virtual env on VS Code, but it doesn't work.. For what it shows in the tutorial, it's supposed to create a folder called ".vscode" with a json file inside called "settings.json" that contains the python path to the python interpreter.. But in my case, none of those files appear.. I THINK there might be sth wrong with the path where it creates the virtual env, but since I'm pretty new at this, I can hardly say.. This are the steps I followed: C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON>cd DJANGO C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO>mkdir storefront C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO>cd storefront C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO\storefront>pipenv install django C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO\storefront>code . C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO\storefront>pipenv shell (storefront-vT5YbUlq) C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO\storefront>django-admin startproject storefront . (storefront-vT5YbUlq) C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO\storefront>pipenv --venv ** So the command prompt returns me this: C:\Users\Usuario.virtualenvs\storefront-vT5YbUlq I'm supposed to copy that line to "Enter interpreter path" in VSCode, and after that it should create those vscode folder and json file.. but that doesn't happen, so I can't use the VS terminal to run the server I'm going insane with this, I just can't understand where's the problem I'd really appreciate if someone could help … -
django social share button icons
I'm trying to add the functionality to share a workout post to social media, and found that the django-social-share package is the best. Everything works, but I'm curious how to add an icon over the link, as it currently looks like Post to Facebook! which is very bland. I've seen examples of adding CSS, but since the package works like {% post_to_facebook object_or_url "Post to Facebook!" %} I'm not sure how you could target that with CSS. Any help is appreciated. -
What is the use of apps.py, appconfig in django project. How and why to use it? could someone explain in a simple way
from django.apps import AppConfig class App1Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app1' -
Should I use abstractbaseuser or abstractuser?
My requirement is to create AUTH system which uses email as AUTH token and some extra fields like name, phone etc and get rid of username field: I can achieve this using both the abstract classes ! But confused on which to use I can just use AbstractUser and make "username=None" and then add usernanager ! Or should i use AbstractBaseUser and redo everything ? -
zappa throwing errors after uploading to lambda
Hi I am new to zapper and aws I am getting errors when i use zappa to upload using zappa==0.48.2 python 3.6 Django==3.1.5 see error below [1626571209893] [DEBUG] 2021-07-18T01:20:09.893Z 42b0c70d-dd34-45a2-a844-xxxxxxxxxxyyyyy Zappa Event: {'time': '2021-07-18T01:19:33Z', 'detail-type': 'Scheduled Event', 'source': 'aws.events', 'account': '630589988206', 'region': 'us-west-2', 'detail': {}, 'version': '0', 'resources': ['arn:aws:events:us-west-2:630589988206:rule/appname-dev-zappa-keep-warm-handler.keep_warm_callback'], 'id': '97b022f9-7ece-b2a6-49a0-9b9aa33fbac0', 'kwargs': {}} [1626571209893] [DEBUG] 2021-07-18T01:20:09.893Z 42b0c70d-dd34-45a2-a844-xxxxxxxxxxyyyyy Zappa Event: {} [1626571450446] [DEBUG] 2021-07-18T01:24:10.446Z 66301a7e-0c98-40c1-a54a-5xxxxxxxxxx Zappa Event: {'time': '2021-07-18T01:23:33Z', 'detail-type': 'Scheduled Event', 'source': 'aws.events', 'account': '630589988206', 'region': 'us-west-2', 'detail': {}, 'version': '0', 'resources': ['arn:aws:events:us-west-2:630589988206:rule/appname-dev-zappa-keep-warm-handler.keep_warm_callback'], 'id': '0513b111-9296-e9b6-73fa-fe0bdfa30215', 'kwargs': {}} [1626571450447] [DEBUG] 2021-07-18T01:24:10.447Z 66301a7e-0c98-40c1-a54a-5xxxxxxxxxx Zappa Event: {} -
Django Admin - dynamic select options with foreignkey and manytomanyfields
Here the supplier is related to Supplier model (ForeignKey) and substrate is with Substrate (ManyToManyField). The main model here is SupplierInfo from which we can filter suppliers and get their respective substrate. When ever admin clicks on the dropdown of Arrival_supplier and, SupplierInfo_substrate should be filtered with the supplier name and should be able to receive SupplierInfo_substrate inside Arrival_substrate. The Arrival model, where the filtered SupplierInfo_substrate should be saved. class Arrival(models.Model): submitted_on = DateTimeField(auto_created=True, null=True, blank=False, editable=False) edited_on = DateTimeField(auto_now_add=True) submitted_by = ForeignKey(get_user_model(), on_delete=models.SET_NULL, null=True) supplier = ForeignKey(Supplier, null=True, on_delete=models.SET_NULL) arrival_date = DateField(auto_now_add=True, null=True, blank=False) substrate = ManyToManyField(Substrate, blank=True) The Substrate and Supplier models, which are connected to Arrival and Supplier. class Substrate(models.Model): name = CharField(max_length=299, unique=True, null=True, blank=False) class Supplier(models.Model): name = CharField(max_length=299, unique=True, null=True, blank=False) The SupplierInfo model, from which supplier and its substrate should be filtered. Note: One supplier can have multiple substrates. Simply, filtering supplier returns multiple query set each with a different substrate (ForeignKey) name. class SupplierInfo(models.Model): supplier = ForeignKey(to=Supplier, on_delete=models.SET_NULL, null=True, blank=False) substrate = ForeignKey(to=Substrate, on_delete=models.SET_NULL, null=True, blank=False) mushroom = ForeignKey(to=Mushrooms, on_delete=models.SET_NULL, null=True, blank=False) weight = FloatField(null=True, validators=[MinValueValidator(0.9)],blank=False) yield_min = FloatField(null=True, validators=[MinValueValidator(0.9), MaxValueValidator(100)]) yield_max = FloatField(null=True, blank=True, validators=[MinValueValidator(0.9), MaxValueValidator(100)], ) status = BooleanField(null=True) -
Django: How do I use the result from one function in a model to use in another model's function?
I want to use the total_pages in the Book model to find the remaining_pages. I don't know what to put for ? class Book(models.Model): title = models.CharField(max_length=100) start_page = models.IntegerField() end_page = models.IntegerField() def total_pages(self): total_pages = self.start_page-self.end_page return total_pages class Tracker(models.Model): dateRead = models.DateTimeField('entry date') bookmark = models.IntField() book = models.ForeignKey(Book, on_delete=models.CASCADE) def remainingPages(self): remaining_pages = ? - self.bookmark return remaining_pages -
How to capture certain information in a session from a form using ajax
I am trying to learn Django and I am making an eCommerce site that has sessions. I building the cart app and I intend to capture qty, price and item.id in a session using AJAX. To understand the concept, I am attempting to capture only the itemid from the HTML. Unfortunately after a few attempts I haven't been able to update the session. I know the session is not updating from running manage.py shell after clicking the "add to cart" button on the page by decoding the session info using the method below: from django.contrib.sessions.models import Session s = Session.objects.get(pk='<sessionid from chrome cookies>') s.get_decoded() Result = {'skey': {}} Here is my cart app: class Cart(): def __init__(self, request): self.session = request.session cart = self.session.get('skey') if 'skey' not in request.session: cart=self.session['skey'] = {} self.cart = cart def add(self, item): item_id = item.id if item_id not in self.cart: self.cart[item_id] = {'price':str(item.price)} self.session.modified = True Here is my AJAX script: <script> $(document).on('click'), '#add-button',function (e) { e.PreventDefault(); $.ajax({ type: 'POST', url: '{% url "store_cart:cart_add" %}', data: { itemid: $('#add-button').val(), action: 'post' }, success: function (json) { }, error: function(xhr,errmsg,err) {} }); }) </script> Here is my html form I am dealing with: <form class="cart … -
I have a slight misunderstanding about Django’s user’s authentication system
How does Django create users? Does it create users automatically? For example, when someone opens a Django site, is a user object automatically created? I see in a lot of codebase, they use request.user to access the logged in user in views.py but then again, does a user need to login before the User object is created? I have an application I want to create but then, I wouldn’t want to create a Django login system since most users will be logging in only via some third party OAUTH service, like login with Spotify or something. In this case, is there a way to merge both authentication systems? Can I still access the logged in user using request.user? -
Django formset factory getting error object has no attribute save
Info: I want to upload multiple files while creating new customer. I want to use formset_factory for file update. when i try to submit the form i am getting this error CustomerFileFormFormSet object has no attribute save. can anybody tell me how tell me how can i update multiple files while adding new customer in database? models.py class FileData(models.Model): """Files Model""" customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True) title = models.CharField(max_length=100) file = models.FileField(upload_to='data', blank=True) def __str__(self): return self.title views.py def CustomerCreate(request): """Customer Create View""" customer_form = CustomerForm() customer_file = formset_factory(CustomerFileForm, extra=1) if request.method == 'POST': customer_form = CustomerForm(request.POST) formset = customer_file(request.POST, request.FILES) if customer_form.is_valid() and formset.is_valid(): customer = customer_form.save(commit=False) customer.dealer = request.user customer.save() file = formset.save(commit=False) file.customer = customer file.save() return redirect('/') context = { 'customer_form': customer_form, 'formset': customer_file, } return render(request, "customer/customer-create.html", context) -
handle duplicate attribute in django model fields, looking for best practise
I'm having a senario, where my model have different fields but the share the same attribute for example I have the following model: class Skills(models.Model): pace = models.IntegerField() shooting = models.IntegerField() passing = models.IntegerField() dribbling = models.IntegerField() defending = models.IntegerField() physic = models.IntegerField() gk_diving = models.IntegerField() gk_handling = models.IntegerField() gk_kicking = models.IntegerField() gk_reflexes = models.IntegerField() gk_speed = models.IntegerField() . . . So Is there a way that can let me writing my model in better way? I mean when I want to update, for example, from models.IntegerField() to models.IntegerField(validators=[MaxValueValidator(100),MinValueValidator(1)]). I have to do the update for the whole fields. -
is it possible to pass template variable to django template tag
I created a custom django template tag and it accepts few arguments. Now the problem I am facing is that, the argument that would be passed to template is dynamic and dependent on the value passed from view function. suppose template has value arg1 and I want to pass it to template tag, so I do like {% custom_tag {{arg1}} %} but it doesn't interpret arg1 as variable but a string, any workaround? -
No images nor css showing up on deployed django app heroku
I have launched the this github repository website in this url with Heroku but as you can see there are no images and no .css styling. How is it possible and how to solve this problem? 2021-07-17T21:11:31.115305+00:00 heroku[web.1]: State changed from starting to up 2021-07-17T21:11:32.189726+00:00 app[web.1]: 10.32.150.15 - - [17/Jul/2021:21:11:32 +0000] "GET / HTTP/1.1" 200 8379 "-" "Mozilla/5.0 (Windows NT 10.0; Win 64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" 2021-07-17T21:11:32.191300+00:00 heroku[router]: at=info method=GET path="/" host=dosmusical.herokuapp.com request_id=4ac7c234-855b-4ac4-aaee-56746352ec73 fwd="185.104.137.33" dyno=web.1 connect=1ms service=93ms status=200 bytes=8620 protocol=https 2021-07-17T21:11:32.206068+00:00 app[web.1]: 10.35.232.224 - - [17/Jul/2021:21:11:32 +0000] "GET / HTTP/1.1" 200 8379 "-" "Mozilla/5.0 (Windows NT 10.0; Wi n64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" 2021-07-17T21:11:32.206552+00:00 heroku[router]: at=info method=GET path="/" host=dosmusical.herokuapp.com request_id=72da5619-c34f-4d19-a069-339cc3d38088 fwd="185.104.137.33" dyno=web.1 connect=1ms service=61ms status=200 bytes=8620 protocol=http 2021-07-17T21:11:32.653544+00:00 app[web.1]: 10.32.150.15 - - [17/Jul/2021:21:11:32 +0000] "GET / HTTP/1.1" 200 8379 "-" "Mozilla/5.0 (Windows NT 10.0; Win 64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" 2021-07-17T21:11:32.654864+00:00 heroku[router]: at=info method=GET path="/" host=dosmusical.herokuapp.com request_id=dcf31e75-36a3-4b1e-b7b3-fa9631278f69 fwd="185.104.137.33" dyno=web.1 connect=1ms service=3ms status=200 bytes=8620 protocol=https 2021-07-17T21:11:32.656678+00:00 app[web.1]: 10.35.232.224 - - [17/Jul/2021:21:11:32 +0000] "GET /static/vendor/bootstrap/css/bootstrap.min.css HTTP/1.1" 4 04 179 "http://dosmusical.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537 .36" 2021-07-17T21:11:32.657225+00:00 heroku[router]: at=info method=GET path="/static/vendor/bootstrap/css/bootstrap.min.css" host=dosmusical.herokuapp.com req uest_id=d27178a7-957f-43d6-b882-0aadcbb3a77a fwd="185.104.137.33" … -
getting all records with same foreign key in django
I'm working on my first project in Django/Postgres, an app to track plant breeding projects. I have a Generation model that connects to a Project model with ForeignKey (i.e., each breeding project consists of multiple generations of offspring): class Generation(models.Model): # ... project = models.ForeignKey( Project, related_name="generations", on_delete=models.CASCADE ) I'd like to add a generation_number field that auto-increments based on the associated project - if there are already 3 records with the same foreign key in the Generation table, then the next record created with that FK should get assigned a generation_number of 4. My understanding is that I can't use an AutoField because this is not a primary key, so I'm trying to write a method that counts the number of records with the same FK and adds 1, something like: def increment_gen_number(self): last_count = Project.objects.filter(pk=self.project).count() return last_count+1 gen_number = models.IntegerField(default=increment_gen_number) I'm guessing there are some syntax issues since I'm still new to Python and this feels like a bit of a kludge. How can I get this to work? -
Message: mutate() missing 1 required positional argument: 'file'
I am trying to upload an image using Apollo, GraphQL, and Django. I see the file in my console so it is properly input in the form. I am still getting the error back from the server: Upon pressing submit: const customSubmit = async (data) => { try { const updateResponse = await updateGmProfile({ variables: { email: data.email }, }); const uploadResponse = await uploadFile({ variables: { file: data.proImg[0] }, }); if (updateResponse && uploadResponse) { addToast("Sucessfully updated!", { appearance: "success", autoDismiss: true, }); router.push(getGMDashboard()); } } catch (error) { console.log("updateGMProfile error:", error); addToast(error.message, { appearance: "error", autoDismiss: true }); } }; Upload Query Function const [uploadFile, { uploadData }] = useMutation(uploadFileMutation); Upload Mutation export const uploadFileMutation = gql` mutation uploadFileMutation($file: Upload!) { uploadFileMutation(proImg: $file) { user { id username } } } `; From console: File {name: "logo.gif", lastModified: 1623080829083, lastModifiedDate: Mon Jun 07 2021 11:47:09 GMT-0400 (Eastern Daylight Time), webkitRelativePath: "", size: 5671877, …} Why do I keep getting this error even though the file is present during the mutation? [GraphQL error]: Message: mutate() missing 1 required positional argument: 'file', Location: [object Object], Path: uploadFileMutation -
Django Annotate and aggregate behaviour clarification. Auto filtering?
Im writing an API in DRF and had some questions on the behaviour of annotate and aggregate on query sets. So I essentially have models Product, Producer, and a model inventory. An inventory contains a product fk, producer fk and quantity and price fields, among other unimportant fields. I have a view which lists out all the inventory items, and filters them based on producer. Im trying to annotate the query set to aggregate and sum the quantity of each product among all inventory items. Initially I just referenced the quantity field directly. That way works apparently, however Im suspicious because it works even if I don't specify that it needs to filter entries based on product. For safety, I access the product model from the inventory model, and then did a reverse relationship from product back to inventory, and referenced the quantity to be aggregated. I get the same expected values, and in this way I understand why its working, however it feels inefficient. I need some clarification on why the simple solution works, and if I should use it, since nowhere am I filtering my product, however the aggregated values are aggregated based on product. class Inventory(models.Model): item_ID … -
How i can add product review option in django?
Below i have added and image of it for example, enter image description here -
What is the Best AWS service(Elastic Beanstalk or Lightsail) I can use to deploy django application for large scale usage, or any other than AWS
I want to use AWS to deploy my Django application what would be the best option as I am planning an application that would serve many people around and more than 1 lack.