Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript regex to solve fill in the words
I'm looking for a way to solve hangman puzzles automatically. Let's say my input is ___o_ and I have a word bank of "llaory" just to make it easy. I'll look through a big list of all english words and use a regex to search for anything that matches. What I have so far that works is this. import raw from "./static/wordlist.txt"; let reg = new RegExp( "\\b" + letters.replace( /_/g, `[${bank}]` ) + "\\b", "g" ); fetch(raw) .then((r) => r.text()) .then((text) => { if (text.match(reg)) { console.log(text.match(reg)); } }); Bank is the word bank so in this case it is llaory. The results from this are 2 words ['alloy', 'alloo']. The correct and only option should be alloy but alloo is an option because the code can't recognize that only 1 o can be used. How can I make it so that the regex knows that letters can only be used as much as there are in the bank? I've seen this post Regex with limited use of specific characters (like a scrabble bank of letters) but it doesn't seem to work when there is a letter already present as shown with the ___o_ -
Activate function every <tr>>javascript | django [duplicate]
I'm not a JS expert, and i'm facing some struggles to activate a function on every table row in a django aplication. I would like that, in every time that i click on the item_total it calculates the inputed value from the item_value * item_qt, but when i try it out, it only work for the first row That's my table: <tbody> {% for item in contract_items %} <tr> <td>{{ item }}</td> <td><input type="number" style="width: 90px;" placeholder="Item value" id="item_value"></td> <td><input type="number" style="width: 90px;" placeholder="Item qt" id="item_qt"></td> <td><input type="number" style="width: 90px;" placeholder="Item total" id="item_total" onclick="calculateForm();"></td> </tr> {% endfor %} </tbody> And that's my script: var calculateForm = function () { document.getElementById("item_total").value = ( Number(document.getElementById("item_value").value) * Number(document.getElementById("item_qt").value) ) }; -
Django sign in form, the stylizing with Bootstrap is not doing anything
I am having some troubles with Django. So, I wanted to use Bootstrap´s sign in template and use it in my project. So, I have been able to do it correctly, except the username and password fields, which are showing up as regular {{form.username}} even though I have used the form-control class. Let me show you: forms.py from django import forms from django.forms import TextInput, PasswordInput class LogINFO(forms.Form): username= forms.CharField(label= 'Usuario: ', max_length=20, widget=forms.TextInput(attrs={"placeholder": "Username", 'style': 'width: 300px;', "class": "form-control"})) password=forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'style': 'width: 300px;', 'class': 'form-control'})) and my login.html {% csrf_token %} <div class="form-floating"> {{form.username}} </div> <div class="form-floating"> {{form.password}} </div> Well, it apparently omits everything and it just shows up as a regular form input. I am not using model as I am using the auth application. Every little bit of help is appreciated! -
Assertion Error when trying to create a view to update one field in model
I have a model that looks like this class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) profile_pic = models.ImageField(upload_to='profile/%Y/%m/%d', default='media/placeholder.png', blank=False, null=False) is_online = models.BooleanField(default=False) is_active = models.BooleanField(default=False) I would like to create an API endpoint to update specifically the is_active field. This is what I have in my views to cater for this class UpdateProfileActive(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer lookup_field = 'profile.is_active' def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data='profile.is_active', partial=True) if serializer.is_valid(): serializer.save() return Response({"message": "user is active field has been updated"}) else: return Response({"message": "failed", "details": serializer.errors}) Here is my serializer: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = serializers.CharField(source='profile.city', allow_blank=True, required=False) country = serializers.CharField(source='profile.country', allow_blank=True, required=False) profile_pic = Base64ImageField(source='profile.profile_pic', max_length=None, use_url=True, required=False) is_online = serializers.BooleanField(source='profile.is_online', required=False) is_active = serializers.BooleanField(source='profile.is_active', required=False) # serializers.ImageField(source='profile.profile_pic', use_url=True, required=False) class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'profile_pic', 'is_online', 'is_active'] # fields = UserDetailsSerializer.Meta.fields + ('city', 'country') extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False}, 'profile_pic': {'required': False}, 'is_online': {'required': False}, … -
Sendgrid not sending email: 401 Unauthorized Django
I'm trying to send the email using SendGrid and I'm using django-sendgrid-v5 to send the email but I don't why it throws me the error. error HTTP Error 401: Unauthorized" settings.py EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY') view.py from django.core.mail import send_mail send_mail('Here subject', 'Here is the message.', 'from_email', ['to_email'], fail_silently=False) -
Correct working thousand separator with locale awareness in Django 4.04
I'm looking for any possibility to humanize values not in general but for some selected values. To be more specific, it's about thousand separator. Enabling thousand separator like this: settings.py USE_L18N = True USE_THOUSAND_SEPARATOR = True views.py def test (request): return render (request, 'example.html', {'example_context_int': 1000}) example.html #... {% load_humanize %} {{ example_context_int }} generates 1.000 as output. This is followed by at least two problems: using any integer given by context as reference for creating links (e.g. passing object id) leads to something like link-to/1.000/ instead of link-to/1000/. pre-populating forms with any integer > 999 forces conversion to a float instead of an integer after submit (e.g. pre-populated 1.000 becomes 1 instead of 1000). This is a known issue. I got two possibilities to solve this: using |stringformat:"s" for any variable which shall not be humanized or converting every integer which is not allowed to be humanized into a string like str (example_context_int). Both methods have pros and cons and I don't prefer any of these. What I would prefer is to explicitly humanize values instead of this implicit conversion of all integers and floats. Following documentation on that, |intcomma have to be used on specific variables instead of … -
Django 4.0. Updating field once every day
Hello I am new to Django and was stuck. I have a Book model that has a integer field count which is the number of users that have this book in their readlist. Users can add a book to their ReadList model (many to many field). I want to update the count in the book model once a day...how should I go about doing this? Will be using this to displaying trending books and book rank based on user count. Book Model: class Book(models.Model): name = models.CharField(max_length=150, unique=True) description = models.TextField() user_count = models.IntegerField() pages = models.IntegerField() genres = models.ManyToManyField(Genre) def __str__(self): return self.name ReadList Model: class ReadList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) readlist = models.ManyToManyField(Book, related_name='readlist', blank=True) def __str__(self): return self.user.username Any help is appreciated, thank you. -
How to update a many to many field in DRF
So in my project, I have a User model and a School model. My user model has a schools field that has an M2M relation with the School model. Now what I want to know is, how can I create a view that can take the email of a user and the school Id, and add the school or delete it from the schools that a user belongs to. Here is my user model: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) schools = models.ManyToManyField("School", related_name="members") USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } School: class School(models.Model): name = models.CharField(max_length=300, verbose_name='school name', ) principal = models.ForeignKey("User", related_name="my_schools", on_delete=CASCADE) address = models.CharField(max_length=200) class Type(models.IntegerChoices): PUBLIC = 1, "Public" PRIVATE = 2, "Private" type = models.PositiveSmallIntegerField(choices=Type.choices, default=Type.PUBLIC) class Level(models.IntegerChoices): NATIONAL = 1, "National" EXTRACOUNTY = 2, "Extra County" COUNTY = 3, "County" SUBCOUNTY = 4, "Subcounty" level = models.PositiveSmallIntegerField(choices=Level.choices, default=Level.COUNTY) def __str__(self): return self.name Here is the serializer to enroll the members: class EnrollSchoolMembersSerializer(): class … -
How to check the data of related fields for compliance with the user before creating a record in django rest framework?
Good evening, I need help. I recently started using django rest framework. I have an application in which the user model has a "company" field, so several users can be in the same company and work with common data. Each company can have one or more warehouses in which goods are stored (each company has its own) There is a page in which data is collected from forms in json and sent to the server via api [ { "id": 9, "doc_type": 1, "warehouse": 5, "date": "2022-06-07", "number": 98, "contragent": 3, "comment": "", "items": [ { "product": 7, "buy_price": "1689.00", "sell_price": "2000.00", "quantity": 1 } ] }, Problem: If the user somehow gets this api and changes the id for example of the "warehouse" field to the id of the warehouse of another company, then the document will be created anyway, also if the user replaces the id of the "product" field Question: How can I check the data for compliance with the user's company before creating it? Here is my code #models.py Class CustomUser(AbstractUser): ... company = models.ForeignKey(Company, on_delete=models.PROTECT, null=True) ... class Company(models.Model): name = models.CharField(max_length=50) ... class Warehouse(models.Model): name = models.CharField(max_length=200) company = models.ForeignKey(Company, on_delete=models.CASCADE) #serializers.py class ConsignmentNoteSerializer(serializers.ModelSerializer): … -
Am I on the right track to implementing multiple native and studying languages in a user signup form?
I am trying to create a simple digital flashcard-like learning platform, where a user can select their native languages and the languages they are studying. As you can imagine, there can be people who speak several languages at a native level, and I am sure there are people out there than are studying a bunch of languages. To outline my problem, let's just say a user is studying 20 languages and can speak 3 languages fluently. Eventually down the road, I would like to use the user's languages (both studying and native) and use them as a filtered drop-down choices. For example, they could attach one language to a card, but the language selection drop-down would show all their studying languages. I am not quite sure what I should be googling to figure out my language selection problem during user signup. I know I could easily accomplish this by hard-coding the fields in my User model, but that breaks the DRY principle and would probably become a mess to maintain, and then tried to accomplish this using the ArrayField, but in my admin the choices are not showing up and it's just a blank CharField. (Hard coded) Terrible Implementation I … -
Django DRF how to restrict access normal user to browsable api page and prevent unauthorized post request
I have an contact forms api for unauthenticated user. I integrated my api in reactjs. But anyone can view the json data if he directly visit the api url. Anyone can also submit post request using POSTMAN using the api url. How to restrict anyone to view the api page and also prevent unauthorized post request. here is my code: settings.py: REST_FRAMEWORK = { # Only enable JSON renderer by default. 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', ], 'DEFAULT_THROTTLE_RATES': { 'anon': '10/minute', } } views.py api_view(['POST', 'GET']) def farhyn_api(request): if request.method == 'POST': data = request.data serializer = ContactSerializer(data=data) if serializer.is_valid(): serializer.save() print(serializer.data) return Response({ 'status': True, 'message': 'sucess' }) return Response({ 'status': False, 'message': serializer.errors }) if request.method == "GET": contact = Contact.objects.all() serializer = ContactSerializer(contact, many=True) return Response(serializer.data) I used AnonRateThrottle but still now anyone can submit POST request using the api url. How to prevent it? and also how to restrict access view api page? -
Is Django and ftplib connection posible?
I am trying to upload a file from a Django server to another FTP Server using ftplib This is what I am trying to do in views.py @background(schedule=1) def uploadToFTP(folder): """ Async function to upload the images to FTP Server. """ print("-------------------Start FTP ----------------------------") #establish ftp connection ftp = FTP(conf_settings.FTP_DOMAIN,conf_settings.FTP_USER, conf_settings.FTP_PASSWORD) file = os.path.join(folder, filename) ftp.storbinary('STOR ' + filename, file,102400) # send the file I am getting all sorts of errors like this: ftp.storbinary('STOR ' + filename, file,102400) File "/opt/anaconda3/lib/python3.8/ftplib.py", line 489, in storbinary buf = fp.read(blocksize) AttributeError: 'str' object has no attribute 'read' So I have tried many methods, but nothing works. Is this even posible. -
Wondering about the type of Django projects I will be asked to construct in the interview?
Could you please give me some suggestions for django projects that have are being asked by interviewers or you have been asked to construct before? -
A Django model that only has many to many fields?
I am trying to store a User's ID and the ID of a Listing in a table. I am new to web development and to me, this seems like a good time to use a ManyToManyField: class Watchlist(models.Model): id = models.AutoField(primary_key=True) user = models.ManyToManyField(User) listing = models.ManyToManyField(Listing) When I try to save a new entry in the database, by doing this: listing_id = self.kwargs['pk'] item = Listing.objects.get(id=listing_id) user_object = self.request.user add_to_watchlist = Watchlist(user = user_object, listing = item) add_to_watchlist.save() I get the error: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead. I am not sure what I am doing wrong, I have followed the example in the documentation as much as possible. -
CREATE list from two Fields in Django
I don't know if there a possibilty to create a field model from two fields different model. for example, I have this two real model : class BaseOil(models.Model): BaseoilName = models.CharField(max_length=150) class Additif(models.Model): AdditifName = models.CharField(max_length=150) BaseoilName contain some composant and AdditifName contain some compostant too and different of BaseoilName, so I want to create a list from this two compostant in one list in another model exactly in Compostant field, like: class Fabrications(models.Model): Fab_fiche_Grade = models.ForeignKey(Lesfiches, on_delete=models.CASCADE) Composant = models.ForeignKey(BaseOil, on_delete=models.CASCADE, null=True, blank=True) I tried some tutorial from Youtube and from Django Project document, but I didn't succeed to have my objective. so thank you for helping to get it, and I will be very thankfull -
Duplicate check in list Django Python
Hi i have to check the overlapping and duplicate of string from the data , i could do it can anyone help me to find the duplicate of string . def overlap(a, b) -> bool: a_start, a_end, _ = a b_start, b_end, _ = b return a_start < b_end and b_start < a_end ls = [(100, 350,"a"), (125, 145,"a"), (200, 400, "d"), (0, 10, "a")] overlaps = set() for idx_a in range(len(ls)): for idx_b in range(len(ls)): if idx_a != idx_b: if overlap(ls[idx_a], ls[idx_b]): overlaps.add(ls[idx_a]) overlaps.add(ls[idx_b]) print(f"Number of overlaps: {len(overlaps)}") -
Django Rest Reverse Nested Relationships in Serializers
I am working on creating a GET only endpoint that shows the standings of a given season for a sports league. Honestly, at this point I have tried nearly everything with no luck. All other Serializers work fine so far and there is no issue with the way my database is setup. I have omitted many fields and tables due to the complexity, but anything relevant to the question is included below. First, let me show you the rough format of how I want to JSON to be returned. Sample Response (The end goal) { divisions: [ { "divisionName": "WEEKNIGHT B", "divisionId": "ee68d8ab-2752-4df6-b11d-d289573c66df", teams: [ { "teamId": "b07560bc-aac2-4c6c-bbfe-11a368137712", "statsId": "53852698-9b78-4f36-9a2e-4751b21972f9", "teamName": "FNA", }, { "teamId": "406eb5aa-6004-4220-b219-59476a3136d1", "statsId": "a96ebf10-87c5-4f19-99c3-867253f4a502", "teamName": "COPENHAGEN ROAD SODAS", }, ] }, { "divisionName": "WEEKNIGHT C", "divisionId": "4e1469ae-2435-4a3d-a621-19a979ede7c1", teams: [ { "teamId": "ebc7e632-073e-4484-85f9-29c0997bec25", "statsId": "cd6373a7-4f53-4286-80f2-eb3a8a49ee3a", "teamName": "HAWKS", "gamesPlayed": 29, }, { "teamId": "d8cda7a6-15f4-4e8f-8c65-ef14485957e4", "statsId": "4492a128-763a-44ad-9ffa-abae2c39b425", "teamName": "DUISLANDERS", }, ] } ] } Through the URL I am passing in the Season ID, so everything is based off the season id. Below is an example of how I can replicate the type of response I want, by iterating through some queries which I know is rather messy, but … -
Django-How to activate new env
i have an issue with activating my virtual env. I added the django library but cannot activate my django library. What should i do next ? https://i.stack.imgur.com/N9hCu.png -
Is there a way to change the set of languages for a field in django-translated-fields
I currently have a model which has a field called title which should have a translation to Japanese (JP). I am currently using a separate field for this translated version, but the django-translated-fields documentation says that there is a way of adding extra languages. My model actually looks like this: class MyModel(model.Model): title_en = models.CharField(max_chars=100) title_jp = models.CharField(max_chars=100) My settings actually look like this: LANGUAGES = [ ("en", "English"), ("es", "Spanish") ] The documentation says that there is a way to do this, but does not describe how. It is also possible to override the list of language codes used, for example if you want to translate a sub- or superset of settings.LANGUAGES. Combined with attrgetter and attrsetter there is nothing stopping you from using this field for a different kind of translations, not necessarily bound to django.utils.translation or even languages at all. The thing is I need to have a jp and an en translation, but not an es translation. Is there a way to completely change the languages used for the title field? -
my modal data remains same while I'm clicking different grids
In my Django project I'm trying to establish software showcasing through on click modal appearance. But the issue is I'm trying to get specific data on modal appearance while clicking on something, but it is showing similar data every time. help me on that buddy, thanks in advance. <div class="container software-showcase-trio"> <div class="row"> {% for maritime_content in maritime_project_content %} <div class="col-lg-3 col-md-3 col-sm-6"> <a href="#" class="text-decoration-none" data-bs-toggle="modal" data-bs-target="#maritime-software-modal"> <div class="software-block-trio" style="background-image:url({{media_url}}{{maritime_content.cover_image}});"> <div class="software-block-hover-trio"> <h1>{{maritime_content.title}}</h1> </div> </div> </a> <!-- Modal --> <div class="modal fade" id="maritime-software-modal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <div class="modal-header"> <h6 class="modal-title" id="exampleModalLabel"></h6> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body maritime-software-modal-body"> <div class="maritime-modal-title"> <h1 class="fw-bold display-5">{{maritime_content.title}}</h1> </div> <img src="{{media_url}}{{maritime_content.cover_image}}" height="500" width="1000" alt=""> <div class="maritime-fields-title"> <div class="maritime-project-details"> <h3 class="fw-bold">Project Details</h3> <p class="">{{maritime_content.project_details}}</p> </div> <div class="maritime-problem-details"> <h3 class="fw-bold">Problem</h3> <p>{{maritime_content.problem_details}}</p> </div> <div class="maritime-solution-details"> <h3 class="fw-bold">Solution</h3> <p>{{maritime_content.solution_details}}</p> </div> <div class="maritime-technology-list"> <h3 class="fw-bold">Technologies</h3> <p>{{maritime_content.technology_list}}</p> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- modal --> </div> {% endfor %} </div> </div> -
Sending email with Django using Gmail not working
I'm new to Django and I want to send the email through my Django server using my Gmail account but unfortunately, I'm getting an error while sending emails even though I've put all credentials correctly there is one thing more in my Gmail account which is "less secure apps" that has to be enabled but this feature is no longer available in Gmail so now how can I send the emails in Django? error while sending the email b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials f14-20020a05600c4e8e00b0039c5642e430sm4688852wmq.20 - gsmtp' -
React.js doesn't display fetched image from Django
My component successfully fetches info (texts and images) from the Django backend but fails to display the images. related: react.js doesn't display fetched image I removed file 192png from manifest.js and HTML and it didn't work so I put them back again as advised. import React, { useState, useEffect, Fragment} from 'react'; import axios from 'axios'; import Carousel from 'react-elastic-carousel'; import './Schools.css'; import Test from '../assets/images/back.jpg'; const schoolBreakPoints = [ {width: 1, itemsToShow: 1 }, {width: 550, itemsToShow: 2 }, {width: 768, itemsToShow: 3 }, {width: 1200, itemsToShow: 4 }, ]; function Schools() { const [languageCenters, setLanguageCenters] = useState ([]); useEffect(() => { const config = { headers: { 'Content-Type': 'application/json' } }; const getLanguageCenters = async () => { try { const res = await axios.get(`${process.env.REACT_APP_API_URL}/api/partners/list/`, config); setLanguageCenters(res.data); } catch (err) { } }; getLanguageCenters(); }, []); const getAllLanguageCenters = () => { let allLanguageCenters = []; let results = []; languageCenters.map(languageCenter => { console.log(languageCenter.photo) return allLanguageCenters.push( <Fragment key={languageCenter.id}> <div className='school__display'> <img className='school__display__image' src={languageCenter.photo} alt='school logo' /> </div> <h3 className='school__language__center'>{languageCenter.name}</h3> <p className='school__course'>{languageCenter.country}</p> <p className='school__course'>{languageCenter.language}</p> <p className='school__course'>{languageCenter.course}</p> <p className='school__about'>{languageCenter.note}</p> </Fragment> ); }); for (let i = 0; i < languageCenters.length; i += 20) { results.push( <div key={i} className='school__card__row'> <Carousel breakPoints={schoolBreakPoints}> … -
Email is not sending from django using gmail
I want to send the email through my Django server using my Gmail account but unfortunately, I'm getting an error while sending emails even though I've put all credentials correctly there is one thing more in my Gmail account which is "less secure apps" that has to be enabled but this feature is no longer available in Gmail so now how can I send the emails? error b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials f14-20020a05600c4e8e00b0039c5642e430sm4688852wmq.20 - gsmtp' -
'function' object has no attribute 'collection'
I am new to google firestore, I followed their documentations to create connection to the database: import firebase_admin from firebase_admin import credentials from firebase_admin import firestore cred = credentials.Certificate("serviceAccountKey.json") firebase_admin.initialize_app(cred) db = firestore.client when i run the above code once is it fine, but for one more time it brings error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [2], in <cell line: 5>() 3 from firebase_admin import firestore 4 cred = credentials.Certificate("serviceAccountKey.json") ----> 5 firebase_admin.initialize_app(cred) 6 db = firestore.client File ~\anaconda3\envs\simulationtrackit\lib\site-packages\firebase_admin\__init__.py:71, in initialize_app(credential, options, name) 68 return app 70 if name == _DEFAULT_APP_NAME: ---> 71 raise ValueError(( 72 'The default Firebase app already exists. This means you called ' 73 'initialize_app() more than once without providing an app name as ' 74 'the second argument. In most cases you only need to call ' 75 'initialize_app() once. But if you do want to initialize multiple ' 76 'apps, pass a second argument to initialize_app() to give each app ' 77 'a unique name.')) 79 raise ValueError(( 80 'Firebase app named "{0}" already exists. This means you called ' 81 'initialize_app() more than once with the same app name as the ' 82 'second argument. Make sure you provide … -
summing up the values of a column in django framework
I have a model in my django web app and I have been trying to query the model in such a way that I can sum up values in the quantity column. I already have data in this model so I just need to add up all the values in the quantity column. class ProductInstance(models.Model): product=models.ForeignKey(Product,on_delete=models.RESTRICT,related_name='product') quantity=models.IntegerField() warehouse=models.ForeignKey(Warehouse,on_delete=models.RESTRICT,related_name='warehouse') I tried "ProductInstance.objects.sum(quantity)". It didnt work