Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are the differences between boolean user types and groups in Django?
I am mapping out a Django project and am wondering what are the differences between using boolean user types versus users added to groups in Django? Are their security issues with the boolean user types? Example of what I mean by boolean user type: class User(AbstractUser): is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) Compared to a custom user which is added to a group: class User(AbstractUser): first_name = models.CharField(_('First Name of User'), blank = True, max_length = 20) last_name = models.CharField(_('Last Name of User'), blank = True, max_length =20) class Meta: permissions = (("can_upload_videos", "Can upload videos")) A few things I see off-the-bat: The latter can be added to custom groups within the Admin panel so it seems that this is probably the way that Django was intended to be used. Does the boolean user type allow for changes to be made within the admin panel? Boolean user types allow for easy implementation of authorization in templates while the users added to groups tend to be easier to add authorization decorators to views. Is there one that will be able to accomplish both of these tasks? If both - which is more secure? Which is easier? What … -
Django model self doesn't count as instance?
I'm trying to resolve a ValueError: Cannot query "X": Must be "Y" instance. issue. The problem is, my X definitely seems to be a Y instance. In my case, X is self within a UserAccount model. Here are some code snippets: from other.thing import do_something class UserAccount(...): # eventually subclasses from Django's user model @property def is_weekly_email_enabled(self): # import pdb; pdb.set_trace() # Debugging entrypoint return do_something(self) class UserPreference(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) # This points to UserAccount name = models.CharField(max_length=255) # In other/thing.py : def do_something(user): return UserPreference.objects.get(user=user, name="some_preference") I've set a pdb breakpoint in is_weekly_email_enabled() to confirm things. Actual exception with testing output: ValueError: Cannot query "user1": Must be "UserAccount" instance. (Pdb) self <UserAccount: user1> (Pdb) type(self) <class 'accounts.models.UserAccount'> (Pdb) isinstance(self, UserAccount) True What is going on here? -
How can I use Django Channels v2 to show a queryset
I have a model "Service": class Service(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200, unique=True) active = models.BooleanField(default=True) class Meta: ordering = ['active', 'name'] I have a DRF API endpoint set up that allows CRUD operations on this model. I want to show my user a list of all currently active Services and am trying to use Django Channels to achieve this. -
Django - how to get all models bound to post_save receivers?
I'm working on a script which finds all Django pre_save and post_save signals and comments overwritten save methods so programmer is aware of all signals affecting the workflow. For Example There are two receivers: @receiver(pre_save, sender=MyModel) def sig_mymodel_pre_save(instance, sender, created, **kwargs): ... @receiver(post_save, sender=MyModel) def sig_mymodel_post_save(instance, sender, created, **kwargs): ... And model MyModel: class MyModel(..): ... def save(self,*args,**kwargs): ... super().save(...) .... I want the script to modify MyModel code to look like this: class MyModel(..): ... def save(self,*args,**kwargs): ... # SIGNAL pre_save | myapp.models.sig_mymodel_pre_save super().save(...) # SIGNAL post_save | myapp.models.sig_mymodel_post_save .... So the first thing I'm going to do is to list all receivers of post_save and pre_save signals: def get_signals() -> {}: result = {} for signal in [pre_save, post_save]: result[signal] = signal.receivers return result def comment_signals_to_save_methods(): for signal, receivers in get_receivers(): for receiver in receivers: models = ??? And here is the problem - I can't get models for the receiver. There is no such method or attribute. Do you know how to do it? -
Failed to send request: Only unicode objects are escapable. Got None of type <class 'NoneType'>
I deployed my django app to a RHEL 8 server following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 The internal django webserver works great with python manage.py runserver 0:8000 Whatever, the guniserver doesn't. 500 internal server error in debug false, otherwise following issue: TweepError at / Failed to send request: Only unicode objects are escapable. Got None of type <class 'NoneType'>. Request Method: GET Request URL: http://18.234.162.216/ Django Version: 2.2.5 Exception Type: TweepError Exception Value: Failed to send request: Only unicode objects are escapable. Got None of type <class 'NoneType'>. Exception Location: /home/ec2-user/django_sentiment/env/lib/python3.7/site-packages/oauthlib/oauth1/rfc5849/utils.py in escape, line 57 Python Executable: /home/ec2-user/django_sentiment/env/bin/python Python Version: 3.7.4 Python Path: ['/home/ec2-user/django_sentiment', '/home/ec2-user/django_sentiment/env/bin', '/home/ec2-user/.pyenv/versions/3.7.4/lib/python37.zip', '/home/ec2-user/.pyenv/versions/3.7.4/lib/python3.7', '/home/ec2-user/.pyenv/versions/3.7.4/lib/python3.7/lib-dynload', '/home/ec2-user/django_sentiment/env/lib/python3.7/site-packages'] Server time: Thu, 19 Sep 2019 23:30:33 +0000</i> TRACEBACK Environment: Request Method: GET Request URL: http://18.234.162.216/ Django Version: 2.2.5 Python Version: 3.7.4 Installed Applications: ['twitter.apps.TwitterConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/ec2-user/django_sentiment/env/lib/python3.7/site-packages/tweepy/binder.py" in execute 189. proxies=self.api.proxy) File "/home/ec2-user/django_sentiment/env/lib/python3.7/site-packages/requests/sessions.py" in request 519. prep = self.prepare_request(req) File "/home/ec2-user/django_sentiment/env/lib/python3.7/site-packages/requests/sessions.py" in prepare_request 462. hooks=merge_hooks(request.hooks, self.hooks), File "/home/ec2-user/django_sentiment/env/lib/python3.7/site-packages/requests/models.py" in prepare 317. self.prepare_auth(auth, url) File "/home/ec2-user/django_sentiment/env/lib/python3.7/site-packages/requests/models.py" in prepare_auth 548. r = auth(self) File "/home/ec2-user/django_sentiment/env/lib/python3.7/site-packages/requests_oauthlib/oauth1_auth.py" in __call__ 88. unicode(r.url), unicode(r.method), None, r.headers) File "/home/ec2-user/django_sentiment/env/lib/python3.7/site-packages/oauthlib/oauth1/rfc5849/__init__.py" in sign 313. ('oauth_signature', self.get_oauth_signature(request))) … -
Django deployment i google cloud error (pywin32 problem )
I developed a Django application, it works perfectly fine in local, when I tried to deploy it in google cloud I got following error https://files.pythonhosted.org/packages/74/68/d87d9b36af36f44254a8d512cbfc48369103a3b9e474be9bdfe536abfc45/python_dateutil-2.7.5-py2.py3-none-any.whl (225kB) Step #1 - "builder": Saved /tmp/tmpvTXqe6/wheel/python_dateutil-2.7.5-py2.py3-none-any.whl Step #1 - "builder": Collecting pytz==2018.7 (from -r requirements.txt (line 57)) Step #1 - "builder": Downloading https://files.pythonhosted.org/packages/f8/0e/2365ddc010afb3d79147f1dd544e5ee24bf4ece58ab99b16fbb465ce6dc0/pytz-2018.7-py2.py3-none-any.whl (506kB) Step #1 - "builder": Saved /tmp/tmpvTXqe6/wheel/pytz-2018.7-py2.py3-none-any.whl Step #1 - "builder": Collecting pywin32==224 (from -r requirements.txt (line 58)) Step #1 - "builder": Step #1 - "builder": INFO `pip_download_wheels` had stderr output: Step #1 - "builder": Could not find a version that satisfies the requirement pywin32==224 (from -r requirements.txt (line 58)) (from versions: ) Step #1 - "builder": No matching distribution found for pywin32==224 (from -r requirements.txt (line 58)) Step #1 - "builder": Step #1 - "builder": ERROR error: `pip_download_wheels` returned code: 1 Step #1 - "builder": INFO pip_download_wheels took 21 seconds Step #1 - "builder": INFO build process for FTL image took 26 seconds Step #1 - "builder": INFO full build took 26 seconds Step #1 - "builder": ERROR `pip_download_wheels` had stderr output: Step #1 - "builder": Could not find a version that satisfies the requirement pywin32==224 (from -r requirements.txt (line 58)) (from versions: ) Step #1 - "builder": No matching … -
Django Models not showing in template
I am finding it quite difficult to display django models in template. The Model does not show at all in the template. Any help will indeed be appreciated. models.py from django.db import models from django.urls import reverse from datetime import datetime class Blog(models.Model): name= models.CharField(max_length = 200) company= models.CharField(max_length = 200) post = models.CharField(max_length = 200) author= models.ForeignKey('auth.User', on_delete = models.PROTECT) mantra= models.CharField(max_length = 200, help_text='make it short and precise') photo= models.ImageField(upload_to='photos/jobs/%Y/%m/%d/', blank=False, null=False) publish = models.BooleanField(default =True) def __str__(self): return self.name def get_absolute_url(self): return reverse('index') views.py from django.shortcuts import render from django.views.generic import TemplateView,ListView from django.views.generic.edit import CreateView from .models import Blog class Home(ListView): model = Blog context_object_name = 'test' template_name='test.html' fields = ['name', 'company', 'post', 'author', 'mantra', 'continent', 'photo'] urls.py from django.urls import path from .views import Home urlpatterns=[ path('', Home.as_view(), name='index'), ] Template <p>{{test.name}}</p> <p>{{test.author}}</p> <p>{{test.post}}</p> -
Trim text in a cell of bootstrap table
How can I trim text in a cell of bootstrap table? Example: In bootstrap table below I have big names in 'stock name' column, this messes formatting of my entire table for example (check columns like invested amount, gains etc). Can I give fixed length to content in stock name column ? By default it can show "Ajanta Ph...", OnHover of a cell it can show full name. I am injecting this page from Django template. <tr id="port_row_{{row.stock}}_{{index}}"> {% if row.stock == 'TOTAL'%} <td> {{row.stock}}</td> {% else %} <td> <a target="_blank" style="color:blue;" href="https://www.google.com/finance?q=NSE:{{ row.stock }}">{{row.stock}}</a></td> {% endif %} <td>{{row.name}}</td> <td>{{row.monday_open_price|intcomma}}</td> <td>{{row.previous_close|intcomma}}</td> <td> {% if row.price >= row.previous_close %} <div style="color:green"> {{row.price|intcomma}} </div> {% else %} <div style="color:red"> {{row.price|intcomma}} </div> {% endif %} </td> <td> &#x20b9; {{row.investment_amount|intcomma}}</td> <td> {% if row.weekly_gain >= 0 %} <div style="color:green"> {{row.weekly_gain|intcomma}} <i class="fa fa-arrow-up"></i> </div> {% else %} <div style="color:tomato"> {{row.weekly_gain|intcomma}} <i class="fa fa-arrow-down"></i> </div> {% endif %} </td> <td> {% if row.daily_gain >= 0 %} <div style="color:green"> {{row.daily_gain|intcomma}} <i class="fa fa-arrow-up"></i> </div> {% else %} <div style="color:tomato"> {{row.daily_gain|intcomma}} <i class="fa fa-arrow-down"></i> </div> {% endif %} </td> <td> &#x20b9; {{row.current_market_value|intcomma}}</td> </tr> -
Django Initial Page Load Slow After Python 2 to 3 Upgrade
I run Django 1.11.20. I have just (finally) made the jump from Python 2.7 to 3.7. I've noticed that since upgrading to Python 3, the very first page load after clearing the cache is very slow. So far I only have my Python 3 environment on my development machine, so I'm experiencing this when using ./manage.py runserver and the FileBasedCache backend. I don't know if I will experience the same thing on a production stack (nginx, uwsgi, redis, etc). I'm using Django Debug Toolbar, which gives me some hints as to what the problem isn't, but I'm not sure where I should look to see what the problem is. The times given by the debug toolbar run loading a simple page with an empty cache in the Python 2.7 environment on my development machine are: CPU: 4877.89ms SQL 462.41ms Cache: 1154.54ms The times given by the debug toolbar run loading the same page with an empty cache in the Python 3.7 environment on my development machine are: CPU: 91661.71ms SQL 350.44ms Cache: 609.65ms (I'm using the file based caching on this development machine, so when I say "with an empty cache" I just mean that I rm -r cache before … -
Use php to call django view - best way
i have a PHP script from a payment provider that can receive payment notifications (Instant Payment Notification - IPN). The problem is that my web application used django. Now i try to find a solution to handle the received data with django and store them to the database. My first idea was to send the received data within the php script via post to a django view (via normal url) with a function like cURL. But is that the best way? Or can i call a django function/view directly from php? My django web application run under apache2 with mod_wsgi -
In Django, how do I query that all of the related objects have the same value for a certain field?
Let's say I have the following models in Django: class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, related_name='children', null=True) foo = models.CharField(max_length=5, blank=True, null=True) How would I query the Parent model to find all Parent records where ALL of it's children have a value of 'ABC' for foo? If I run: Parent.objects.filter(children__foo='ABC'), it returns Parent objects where at least one of it's children has a value of 'ABC' for foo, which is not what I want. Any help is appreciated, thank you. -
Django schedule framework doesn't work like it's supposed to
I'm trying to get to work the schedule framework for django but it doesn't look right and it's functually broken as well, although only in the front-end. A pop-up to show an event doesn't work either f.e.. This is how it is supposed to look like vs this is how it actually looks like Does anybody have an Idea what the Problem might be? Any help would be much appreciated. -
How to calculate all the consummation of a client?
I'm working on a project of managing payments of a restaurant, but I'm new in django and I need help to calculate the total consummation of a client. I tried to sum to sum a consommation, but can't sum all consommations for a client class Consommation(models.Model): .... vipcustomer = models.ForeignKey(VipCustomer, models.CASCADE, null=True, blank=True, verbose_name='Client prestigieux', related_name='vip_consommations') def total_consommation(self): get_price = Consommation.get_price return get_price(self.entree) + get_price(self.food) + get_price(self.dessert) + get_price( self.boisson) + get_price(self.autres) Thanks in advance. -
Dajngo gets error when overriding save method
I overriding model's save() method to do some work with directory. My overrided save() method looks like this: def save(self, *args, **kwargs): book_dir = os.path.join(MEDIA_ROOT, self.title) # check that at least one file is loading if all([self.pdf, self.fb2, self.epub]): raise ValidationError("At least 1 file should be uploaded!") # create book's directory if it not exists if os.path.exists(book_dir): raise ValidationError("This book is already exists!") else: os.mkdir(book_dir) # assign uploading files storage for x in [self.image, self.pdf, self.fb2, self.epub]: x.storage = book_dir super().save(*args, **kwargs) # Call the "real" save() method. Everything goes well until last line. Django gives me AttributeError: 'str' object has no attribute 'save' error. -
Why my overwriting on labels and widgets from UserCreationForm on Django doesn't work?
Although I found how to work around the problem (cf. at the bottom of the page), I do not understand why my overload of UserCreationForm doesn't work without erase parent attributs. Yet, I did a lot of research. In particular on this doc forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.utils.translation import gettext, gettext_lazy as _ from . import models class SignUpForm(UserCreationForm): """ Form for sign up in training app """ email_confirmation = forms.EmailField() # password1 = forms.CharField(label='Mot de passe') def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) print(self._meta.labels) print(self._meta.fields) # self._meta.labels = { # 'username': 'Nom d`\'utilisateur', # 'password1': 'Mot de passe', # 'password2': 'Confirmation du mot de passe', # 'email': 'Adresse e-mail', # 'email_confirmation': 'Confirmation de l\'adresse e-mail', # } class Meta(UserCreationForm.Meta): model = User fields = ( "username", "password1", "password2", "email", "email_confirmation", ) labels = { 'username': _('Nom d\'utilisateur'), 'password1': _('Mot de passe'), 'password2': _('Confirmation du mot de passe'), 'email': _('Adresse e-mail'), 'email_confirmation': _('Confirmation de l\'adresse e-mail'), } # UserCreationForm.Meta.labels = { # 'username': _('Nom d\'utilisateur'), # 'password1': _('Mot de passe'), # 'password2': _('Confirmation du mot de passe'), # 'email': _('Adresse e-mail'), # 'email_confirmation': _('Confirmation de l\'adresse e-mail'), # } widgets … -
Class object value not displaying properly
I have implemented a counter in my Django program. It is not displaying as intended. From Views class PostDetail(DetailView): model = Post def get_context_data(self, **kwargs): data = super(PostDetail, self).get_context_data(**kwargs) self.object.view_count = F('view_count') + 1 self.object.save() return data I know this works because if I comment out the method From HTML Page <small class="text-muted">{{ object.view_count }}</small> How ever when I try to use the method it prints, F(view_count) + Value(1) Instead of a number as intended. I'm not sure what else to try as I am new to Django. I attempted to research how to fix it but couldn't find anything. -
A better syntax for switch-like conditions in Django Template
Does anyone know a less bulky way of performing a switch-like evaluation in Django Template than the one below? <div class="alert {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}alert-danger {% elif message.level == DEFAULT_MESSAGE_LEVELS.WARNING %}alert-warning {% elif message.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %}alert-success {% elif message.level == DEFAULT_MESSAGE_LEVELS.INFO %}alert-info {% elif message.level == DEFAULT_MESSAGE_LEVELS.DEBUG %}alert-dark {% else %}alert-light{% endif %} alert-dismissible fade show" role="alert"> {{ message }} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> -
JavaScript & HTML changes not appearing through Django server
I recently began a new job working on a Django server, and for some reason, the server stubbornly keeps refusing to propagate my updates. This seems to be getting worse; sometimes I can make a change. I've done a bunch of research and can't seem to get any closer to the problem. It is NOT due to my cache. I've been consistently clearing my cache, closing my browser, and even occasionally restarting the computer. It's NOT due to server cache, either. I've been stopping and starting the service with each test. It's not due to static files being updated. I've even gone and changed all the static files manually, and I've repeatedly run manage.py collectstatic both with and without the -c flag. I tried appending a number to the JS url (adding "?rand=23423423" to the end of the script src links), as that was recommended to fix the JS problem, and that's when I found that the HTML wasn't updating either. Changes made to .py files and CSVs always consistently work the first try. Only JS and HTML files have not been propagating. I'm working with Python 3.7, Django 2.1.5, Google Chrome 77.0.3865.90 and macOS (which I'd never worked with … -
Using field as row in django tables
I'm using the django_tables2 library and I don't see anywhere in the documentation to use the fields as rows instead of columns. class PizzaTable(tables.Table): class Meta: model = PizzaInstance fields = ("pizza", "type", "size", "price") attrs = {"class": "mytable"} Can I use pizza and type as rows in django_tables2 library? -
How to integrate Blockchain using Django
The Blockchain code is written in python and to use it in Django framework what imports we need and in which section ? -
Any way to update a ManyToMany field via a queryset?
Suppose I have an object: survey = Survey.objects.all().first() and I want to create a relationship between it and a group of objects: respondents = Respondent.objects.all() for r in respondents: r.eligible_for.add(survey) where eligible_for is an M2M field in the Respondent model. Is there any way to do it in one pass, or do I need to loop over the queryset? -
My sign up form is not working with django python
I have a problem with my application the sign up is not creating profiles on the backend. I have tried to use the django forms but I didnt like how they render so I wanted to use custom form but once I click button submit, nothing happens and I check on backend there's no profile. My forms.py file looks like this from django.forms import ModelForm from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Gig class GigForm(ModelForm): class Meta: model = Gig fields = ['title','category','description', 'price', 'photo', 'status'] class SignUpForm(forms.ModelForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password' ) Models.py File like this class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.CharField(max_length=500) about = models.CharField(max_length=500) location = models.CharField(max_length=30, blank=True) def __str__(self): return self.user.username - Views.py ```python def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() user.refresh_from_db() username = form.cleaned_data.get('username') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('home.html') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) signup.html looks like this <div class="container1"> <img src="{% … -
Django: Overwriting a form. how to shortening the mapping of the fields?
i am testing forms and model nesting in django. Due to a ManyToMany Relation in my form i have to use a custom save function. So far it works. But i asked myself if there is a way to shorten the code? So here is my my... forms.py GuestForm(forms.ModelForm): dish = forms.ModelChoiceField(queryset=None) # --- Input for meal.table table_input = forms.IntegerField(widget=forms.NumberInput) class Meta: model = Guest fields = [ 'name', 'dish', 'table_input', 'city', 'department' ] # --- Dish names from dish.model def __init__(self, *args, **kwargs): super(GuestForm, self).__init__(*args, **kwargs) self.fields['dish'].queryset = Dish.objects.all() def save(self): # --- save the new Meal.object data = self.cleaned_data mealData = Meal(table=data['table_input'], dish=data['dish']) mealData.save() # --- save the new Guest.object guestData = Guest(name=data['name'], city=data['city'], department=data['department']) guestData.save() # --- add a m2m relation between Guest.object and Meal.object guestData.meals.add(mealData) guestData.save() return guestData Question My Question is especially related to the mapping of all fields after i saved mealData.save(). # --- save the new Guest.object guestData = Guest(name=data['name'], city=data['city'], department=data['department']) guestData.save() Because in bigger Projects it could mean a lot of work, to map every field afterwards, just because i needed tableand dishto save in a extra model. Or in other Words is there some Kind of Selection Method? Something like … -
Cross checking and validating two input fields in django
I am new to python and Django, i wanted to know how below thing can be possible? input field 1 - Enter name - abc@yoyo.com input field 2 - Enter Url - www.yoyo.com Submit button so I want to validate the email domain and the URL name is same. Suppose if abc@yoyo.com is not similar to the URL field (www.yo.com) so show an error. else if it's same then proceed. How can this be implemented in Django? -
How to get the amount for one specific client (vipcustomer)'s consommation in my detail view?
I want to get what each customer has as consommation in money, in my detail view, have problems in finding the way to render it, I'm new in django. this is the model for consommation class Consommation(models.Model): entree = models.ForeignKey(Entree, models.CASCADE, verbose_name="L'entree", null=True, blank=True) food = models.ForeignKey(Meals, models.CASCADE, verbose_name='Plat de resistance', null=True, blank=True) dessert = models.ForeignKey(Dessert, models.CASCADE, verbose_name='Dessert', null=True, blank=True) boisson = models.ForeignKey(Boisson, models.CASCADE, verbose_name='Boisson', null=True, blank=True) autres = models.ForeignKey(Autres, models.CASCADE, verbose_name='Snacks', null=True, blank=True) consomme_le = models.DateTimeField(default=timezone.now, editable=False) vipcustomer = models.ForeignKey(VipCustomer, models.CASCADE, null=True, blank=True, verbose_name='Client prestigieux', related_name='vip_consommations') @staticmethod def get_price(item, _default=0): if item: return item.price return _default def total_consommation(self): get_price = Consommation.get_price return get_price(self.entree) + get_price(self.food) + get_price(self.dessert) + get_price( self.boisson) + get_price(self.autres) the client: class VipCustomer(models.Model): ... I have used the related_name to get all the consommations for a specific vipcustomer, but in addition of that I want to calculate the total of those consommations for that vipcustomer. Thanks in advance.