Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django detail() got an unexpected keyword argument 'pk'
url.py path('detail/<int:pk>', movie.views.detail, name='detail') views.py def detail(request, primary_key): moviedetail = get_object_or_404(movieinfo, pk=primary_key) return render(request, 'movie/detail.html', { 'moviedetail':moviedetail }) moviehome.html <a href="{% url 'detail' movieinfos.movie_id%}"> detail() got an unexpected keyword argument 'pk' Could you please help me?? How do i have to fix it?? -
Django contains on a many to many field
I am trying to get a user that has the skills needed for a shift. This means the user needs to have the exact skills or more. I tried this. But this does not work for relation fields User.objects.filter(skills__contains=skills) The in operator also does not work because I need a user that has all the skills and not a user which has a subset of the skills required. Is there a way to retrieve the user where the asked about skills are a subset of the user skills? -
Setting up and serving static files for Django
I am on the verge of deploying my website but I have to firstly solve the issuer$ of serving static files via a web server for django. I have the following layout that is modifiable but is what I am working with so far website |-> PWEB | |-> exchange | | |-> migrations | | |-> static | | | |-> exchange | | |-> templates | |-> PWEB | |-> static-server | |-> static | | |-> exchange Both static folders right now contain exactly the same files but as I need to know exactly (I have tried various methods before) what to specify and where on how to access the static files. Here is the static definition in the settings.py file: STATIC_URL = '/static/' STATIC_ROOT = '' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) and here is an example of how the files are accessed within a html code: {% load static %} <!DOCTYPE HTML> <!-- Massively by HTML5 UP html5up.net | @ajlkn Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) --> <html> <style> {% block style %} {% endblock style %} </style> <head> {% block head%} {% endblock head %} <meta charset="utf-8" /> … -
'index_together' refers to field 'three' which is not local to model 'Entry'
Why am I getting this error? If remove index_together from the Post class, then everything works, but you can’t do this for certain reasons. class Post(models.Model): one = .. two = .. three = .. class Meta: abstract = True index_together = [ ['one'], ['one', 'two','three'] ] class Comment(Post): pass zinnia.Entry: (models.E016) 'index_together' refers to field 'three' which is not local to model 'Entry'. HINT: This issue may be caused by multi-table inheritance. zinnia.Entry: (models.E016) 'index_together' refers to field 'two' which is not local to model 'Entry'. HINT: This issue may be caused by multi-table inheritance. zinnia.Entry: (models.E016) 'index_together' refers to field 'one' which is not local to model 'Entry'. I do not quite understand, where does Entry. but here is what is class Entry(load_model_class(ENTRY_BASE_MODEL)): """ The final Entry model based on inheritence. """ def load_model_class(model_path): """ Load by import a class by a string path like: 'module.models.MyModel'. This mechanism allows extension and customization of the Entry model class. """ dot = model_path.rindex('.') module_name = model_path[:dot] class_name = model_path[dot + 1:] try: _class = getattr(import_module(module_name), class_name) return _class except (ImportError, AttributeError): raise ImproperlyConfigured('%s cannot be imported' % model_path) ENTRY_BASE_MODEL = getattr(settings, 'ZINNIA_ENTRY_BASE_MODEL', 'zinnia.models_bases.entry.AbstractEntry') ZINNIA_ENTRY_BASE_MODEL = 'apps.blogextra.models.Post' -
Django-crispy-forms with bootstrap4 not showing selected result in browse file field
Attempting to use bootstrap4 with django for forms. Installed crispy forms and and everything seems to work as I expected except for the browse file button selection functionality. When a file selection window comes up and file is choose from expolorer it does not show as selected it the field. However when the form is submitted everything works as expected and the file is uploaded. Am I missing a helper class setting? I could not find one that looked like it addresses this. Any help is appreciated, details below. rendered html Environment: Windows 10 bootstrap4 Python 3.7.4 Django 2.2.5 Django crispy forms 1.8.0 Models.py from django.db import models # Create your models here. class Csvfile_model(models.Model): name = models.CharField(max_length=50) csv_file_name = models.FileField(upload_to='csv_file/') forms.py from django import forms from crispy_forms.helper import FormHelper from .models import * class CsvForm(forms.ModelForm): helper = FormHelper() class Meta: model = Csvfile_model fields = ['name', 'csv_file_name'] views.py def csv_upload(request): if request.method == "POST": form = CsvForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('sucess') else: form = CsvForm() return render(request, 'csv_upload.html', {'form' : form}) def sucess(request): return HttpResponse('sucessfully uploaded') csv_upload.html <!-- templates/home.html --> {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy form form.helper %} {% block title %}Home{% … -
Trying to read a text file in django
Im unable to read the contents of a file from view.py Below is my code: def home_view (request, *args, **kwargs): ksh_test_result=AutomationTestResult.objects.values('tatr2tafmc__jobcommand', 'ksh_completion','ftp_log_abs_path','aftp_log_abs_path').distinct() ksh_drilldown_data=AutomationTestResult.objects.all() for ksh in ksh_test_result: ftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.ftp_log_abs_path, 'r').read() aftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.aftp_log_abs_path, 'r').read() print(ftp_log_file) print(aftp_log_file) context={ "ksh_list" : ksh_test_result, "ksh_drilldown" : ksh_drilldown_data, "ftp_log" : ftp_log_file, "aftp_log" : aftp_log_file } return render(request, "home.html", context) I'm reading the path of the file from a database. When I run this code i get the following error code Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/nmehta/Projects/GATI/src/KTA/dashboard/views.py", line 11, in home_view ftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.ftp_log_abs_path, 'r').read() AttributeError: 'dict' object has no attribute 'ftp_log_abs_path' [20/Nov/2019 14:31:27] "GET / HTTP/1.1" 500 65923 -
How to go from one page to another in django
I'm new to Django and python (infact my first language which I've only been learning for 3 months) I'm creating this website using Django and I'm not able to go from one page to another using the href tag. it throws at me a 404 error saying "current path didn't match any of these" This is my code views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .models import off # Create your views here. def homepage(request): return render(request=request, template_name='main/home.html', context={'toll' : off.objects.all}) def secondpage(request): return render(request = request, template_name = 'main/next.html') main/urls.py from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('',views.homepage,name='homepage'), path('',views.secondpage,name='secondpage') ] templates/mains/home.html <div class="topnav"> <a href="{% url 'next' %}">Link </a> <a href="#">Link </a> <a href="#">Link </a> </div> I also request the helper to simply it for me as I wouldn't be able to handle complex and advanced python terminology Thanks In Advance From a Friend Arvind -
Why get error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet (Django 2.1.5)?
Tell me why I get this error and how to fix it? Tried to write django.setup() at the top of the file, but got a RuntimeError error: populate() isn't reentrant Code of mu model and traceback -
how make a filter or autocomplete in a field in django from html page
I newbie in django, I make a django form and show this in a html, in this form I have a field products, when a user going to select a product in this field shows all products, but to find a product not is easy because the products not can be filter when the user write, then the user have search from all the products in this field How I can make to filter when a user write for the product name -
Django management command with arg.parser and confirm
I' writing a small django management command where I parse user input: class Command(BaseCommand): help = 'Management command to transfer User Data from one user to the other' def add_arguments(self, parser): parser.add_argument( '-o', '--old', dest='old', default='', help="ID of Username from whom data is removed", required=True) parser.add_argument( '-n', '--new', dest='new', default=1086, help="ID of Username of receives data", required=False) ... Later I force a confirm to the user confirm = input('You are about to transfer data from {} to {}. Proceed? (Y/n)').format( old_user.username, new_user.username ) while True: if confirm not in ('Y', 'n', 'yes', 'no'): confirm = input('Please enter either "yes" or "no": ') continue if confirm in ('Y', 'yes'): break else: return Unfortunately this fails with NameError: name 'y' is not defined I think what is happening is that arg.parser tries to parse the value. How can I stop it in my confirm loop? -
why am I not getting the second validation?
I am trying to validate my signup form, but I am getting the desired output from the first, and third, but I try to validate if it's short or too common. I got nothing, but I can have matched validation if(data['message']['email'] == 'Enter a valid email address.' || data['message']['email'] == 'User with this Email address already exists.'){ $("#erroremail").html(data['message']['email'][0]); } if(data['message']['password2'] == 'This password is too short.'){ $("#errorpass").html(data['message']['password2'][0]); } if(data['message']['password2'] == "The two password fields didn't match."){ $("#errorpass").html(data['message']['password2'][0]); } JSON response message: email: ["User with this Email address already exists."] password2: Array(3) 0: "This password is too short. It must contain at least 8 characters." 1: "This password is too common." 2: "This password is entirely numeric." -
Cant render new context to template from another view In Django
I create an app to check how to run background tasks in Django but I catch such error in rendering that I can't explain and I have not found a similar question anywhere. I cant figure up where are an error. There is my views.py from django.shortcuts import render, get_object_or_404, redirect from django.http import JsonResponse from django.http import HttpResponseBadRequest, HttpResponseRedirect, HttpResponse from django.urls import reverse import json import datetime from .models import Simulation, get_simulation from .forms import SimulationForm # Create your views here. def simulation_page(request): context = { "simulations_exists": Simulation.objects.all().exists() } return render(request, 'simulation_page.html', context) def simulate(request): if request.method == 'POST': # data = json.loads(request.body) action = data['action'] # 0 or 1 that mean run or stop sim = get_simulation() if action == "0" and sim.status == True: sim.status = False sim.save() elif action == "1" and sim.status == False: sim.status = True sim.save() context = { "simulations_exists": True, "days_passed": sim.get_simulation_day(), "simulation_today_str": (sim.today).strftime("%d %B, %Y"), # 06/12/18 -> 12 June, 2018 "simulation_status": sim.status } return render(request, "simulation_page.html", context=context) return HttpResponseBadRequest() There is my simulation_page.html template: {% extends "base.html" %} {% block content %} <h1>Simulation</h1> <div id='simulation_info'> simulation_status: {{simulation_status}} </div> <div class='container'> {% if not simulations_exists %} <p><a href="{% url 'simulation:simulation_create' … -
Django - Logging not working in production
This issue is driving me nuts. For the longest time logging was working fine, after I changed the format a little bit and made new sub folders it won't work when running the app in prod mode (with nginx + gunicorn) but logging will work when using "runserver". The Gunicorn Log does not show any issue, the app itself works fine... LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': ">>> %(asctime)s | %(levelname)s | %(name)s:%(lineno)s | %(message)s", 'datefmt': "%Y-%m-%d | %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', # 'class': 'logging.handlers.TimedRotatingFileHandler', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 1024 * 1024 * 15B = 15MB 'filename': LOG_DIR + '/app/WSx.log', 'formatter': 'verbose', # 'interval': 1, # 'when': 'midnight', 'backupCount': 7, }, 'user_file': { 'level': 'DEBUG', # 'class': 'logging.handlers.TimedRotatingFileHandler', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 1024 * 1024 * 15B = 15MB 'filename': LOG_DIR + '/user/User.log', 'formatter': 'verbose', # 'interval': 1, # 'when': 'midnight', 'backupCount': 30, }, 'debug_file': { 'level': 'DEBUG', # 'class': 'logging.handlers.TimedRotatingFileHandler', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 1024 * 1024 * 15B = 15MB 'filename': LOG_DIR + '/debug/WSX_DEBUG.log', 'formatter': 'verbose', # 'interval': 1, # 'when': 'midnight', 'backupCount': 7, }, }, 'loggers': { … -
How is it possible to have inlines inside inlines when using a formset in django
I want to apply in my formset the case of having a form-Case model, and in inlines having Offers - Offer model of inlines also, Yachts - Yacht model. models.py class Case(models.Model): client=models.ForeignKey(Client,null=True,verbose_name="Client",on_delete = models.CASCADE) date_created = models.DateTimeField("Date of Case Creation", null=True,blank=True, default=datetime.datetime.now) comment = models.CharField("Comments",max_length=500, blank=True, null=True) class Offer(models.Model): date_created = models.DateTimeField("Date of Offer creation", null=True,blank=True, default=datetime.datetime.now) notes=models.CharField("Offer Notes",max_length=100, blank=True) case=models.ForeignKey(Case,verbose_name="Case",on_delete = models.CASCADE) class Yacht(models.Model): name = models.CharField(max_length=50, verbose_name="Name") price_per_day=models.DecimalField("Price(€) / Day", max_digits=8, decimal_places=2, default=0,blank=True) passengers = models.IntegerField("Passengers",blank=True,null=True) class OfferHasYacht(models.Model): offer=models.ForeignKey(Offer,null=True,verbose_name="Offer",on_delete = models.CASCADE) yacht=models.ForeignKey(Yacht,null=True,verbose_name="Yacht",on_delete = models.CASCADE) In forms.py the : OfferOfferHasYachtFormSet=inlineformset_factory(Offer,OfferHasYacht,form=OfferHasYachtForm,extra=1) works fine having as form the Offer and as inlines the OfferHasYacht(excluding the offer from OfferHasYachtForm) class OfferHasYachtForm(ModelForm): yacht = ModelChoiceField(required=True,queryset=Yacht.objects.all(),widget=autocomplete.ModelSelect2(url='yacht-autocomplete')) class Meta: model = OfferHasYacht fields = ['yacht'] def __init__(self, *args, **kwargs): super(OfferHasYachtForm, self).__init__(*args, **kwargs) self.fields['yacht'].label = "Choose Yacht" but when trying to declare the formset: CaseOfferHasYachtFormSet=inlineformset_factory(Case,OfferHasYacht,form=OfferHasYachtForm,extra=1) the django complaining that: ValueError: 'intranet.OfferHasYacht' has no ForeignKey to 'intranet.Case'. How is it possible to solve that in order to have a view that I can create or update a case having offers (as inlines) and every offer having yachts (as inlines). -
Memcached works in Django shell but not for view functions
I am trying to implement view based caching using memcached in my django project. I have brew installed it in my machine and also installed python-memcached in my virtual env. Memcache works in python3 manage.py shell. >>> from django.core.cache import cache >>> cache.set('foo', 'bar', 600) >>> cache.get('foo') 'bar' But when I put the cache_page() decorator on my view function and load the view I do not get any set or get logs on memcached -vv. I have the following in my settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } Pardon me, I have very basic understanding of the caching process. I know that memcache stores cached data as key value pairs but how does it pick a key for the decorated view? If I cache the ListView will I be able to query using different filters from the cache? A few comments and links to online resources will be helpful. -
How do I access a complete row through a foreign key in Django?
guys :) Let's say I have the following code: class Model3D(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) settings_of_model = models.ForeignKey('Settings', on_delete=models.CASCADE, null=True) class Settings(models.Model): id = models.AutoField(primary_key=True) extruder_Temperature = models.PositiveIntegerField(null=True) layer_Height = models.DecimalField(max_digits=100, decimal_places=100, null=True) model_id = models.ForeignKey('Model3D', on_delete=models.CASCADE) printer_Name = models.ForeignKey('Printer', on_delete=models.CASCADE, null=True) Every model has one row in table settings with the settings for the model. How can I access this row to get it for an specific model? The following code did not work. def get_settings(id_of_model): settings_of_model = Model3D.objects.filter(id=id_of_model)prefetch_related('Settings') return settings_of_model Can you help? -
uWSGI - never sleep mod?
I have a django app, running with uwsgi behind nginx server, all on same debian and python2.7. On the first start of the application, everything goes very well, the queries are fast. If I never question the application for a long time (> 1h maybe more), the first new query takes a long time to answer and after waiting then everything reworks correctly. As if the service was in standby and make time to respawn. I would never wait, even if the service has not been solicited for several hours. That is possible ? I have tried "cheaper" configuration, same result. My ini file : [uwsgi] logto = $(APP_LOGS_DIR)/uwsgi.log chdir = $(APP_SRC_DIR) manage-script-name = true mount = /=$(APP_SRC_DIR)/wsgi.py plugins = python virtualenv = $(APP_VENV) master = true processes = 4 socket = 0.0.0.0:9001 static-map = /static=$(APP_SRC_DIR)/static/ vacuum = True buffer-size = 8192 vacuum = true cheaper-algo = spare cheaper = 2 cheaper-initial = 3 workers = 4 cheaper-step = 1 and a part my nginx conf : upstream app { server 127.0.0.1:9001; } server { [...] location / { include uwsgi_params; uwsgi_pass app ; } } -
How to write a self referencing Django Model?
I have a Django model "Inspection" which has: InspectionID (PK) PartID SiteID Date Comment Report Signiture I want to be able to have a one to many relationship between the inspection ID and date. So one ID can have inspections at many dates. How would I do this? I currently have the following: class Inspection(models.Model): InspectionID = models.IntegerField(primary_key=True, unique=True) PartID = models.ForeignKey('Part', on_delete=models.CASCADE) SiteID = models.ForeignKey('Site', on_delete=models.CASCADE) Date = models.DateField(auto_now=False, auto_now_add=False) Comment = models.CharField(max_length=255, blank=True) Report = models.FileField(upload_to='docs', null=True, blank=True) Signiture = models.CharField(max_length=255, blank=True) I thought about using models.ForeignKey but I really don't know how to implement that properly in this situation. -
How can redefine attribute in abstract model?
Hello I have two models class A(models.Model): slug = models.SlugField() class Meta: abstract = True class B(models.Model): slug = models.CharField() class Meta: abstract = True I get error AttributeError: Manager isn't available; B is abstract How do can to redefine attribute in abstract class? class A cannot be changedю -
Change Celery task rate limit and apply/reschedule immediately
I have a Django application called api and a rate-limited Celery task called email_slow_track. I use the following command to change the rate limit (on the command line): $ celery -A api control rate_limit email_slow_track 1/s -> celery@a5dac4396c0b: OK new rate limit set successfully Let's say the initial rate limit is 3/m (one every ~20sec), and I have a bunch of jobs in the queue. I then change the rate limit to 1/s. I observed that as a result, old jobs will continue to run roughly every 20 seconds, while new jobs "jump the queue" and sneak in once a second. Is there a way to get existing jobs rescheduled, so that submission order is maintained, and rate limit changes are applied to existing jobs as well? (Ideally, this would be on the command line.) -
Django pagination - for loop in all pages
I have a list of objects that I would like to display in an ul/li. For that I do the code below: <ul id="myUL"> {% for l in lpps %} <li id="lpps"><a href="#">{{ l.codeACL }} {{ l.libelle }}</a></li> {% endfor %} </ul> The problem is that in my view, I ask to display only 15 objects per page. But I want to ignore this and display all the objects on all the pages. Is there something like for l in lpps.page(all)...? -
Translating cards
i am only one month django learning. i wanna do cards with word on eng so user can send translate in form and he will get true or false result so i have card like this: class Cards(models.Model): class Meta: verbose_name = "Карточка" verbose_name_plural = "Карточки" category = models.CharField(max_length=30, db_index=True) word = models.TextField(max_length=100, db_index=True) def __str__(self): return self.title so i need to compare request from user with 'word' i have in my database field and print result so can u tell me what i need to google to do this, because i can find nothing all day -
Inspect list of Celery jobs on command line
In a Celery setup with Django, I registered two tasks, email_slow_track and email_fast_track. I would like to inspect the list of jobs for each task on the command line, but I was unable to find the right command. Here's what I tried (my application name is api): inspect registered: This appears to list registered tasks, not jobs submitted under these tasks. However, it at least shows that the connection is set up properly, and that the tasks are known. $ celery -A api inspect registered -> celery@a5dac4396c0b: OK * api.celery.debug_task * email_fast_track [rate_limit=1/s] * email_slow_track [rate_limit=10/m] inspect query_task <task_name>: Empty result. I'm not sure what this command should do, and whether this is the expected result. $ celery -A api inspect query_task email_slow_track -> celery@a5dac4396c0b: OK {} inspect query_task <task_id>: Empty result. Just thought I'd give it a try ... $ celery -A api inspect query_task cb1ecc1c-5746-4d08-ad50-4bff4d57855b -> celery@a5dac4396c0b: OK {} Note that my tasks do run properly. I'm not trying to fix task execution; the issue here is getting a list of tasks. I am able to see all jobs with Celery Flower, so things are fine in general. But can I get that information from the command line? -
Django - can I do this without a raw query
I am learning Django, and have got quite a long way using the documentation and various other posts on stackoverflow, but I am a bit stuck now. Essentially I want to query the database as follows SELECT w.wname, w.act_owner_id, wi.act_code, wi.act_provider, SUM(ft.quantity) AS "position", prices.Current, prices.MonthEnd, prices.YearEnd, cost.avgcost, sec.securityName AS "security" FROM finance_wrapperinstance as wi INNER JOIN finance_wrapper as w ON (w.id = wi.wrapperType_id) INNER JOIN finance_security as sec ON (ft.security_id = sec.id) left outer JOIN finance_transaction as ft ON (wi.id = ft.investwrapperID_id) left outer Join (SELECT hp.security_id as secid, max(Case when hp.date = '2019-11-18' then hp.price end) as 'Current', max(Case when hp.date = '2019-10-30' then hp.price end) as 'MonthEnd', max(Case when hp.date = '2018-12-31' then hp.price end) as 'yearEnd' FROM finance_historicprice as hp GROUP BY hp.security_id ) AS prices ON (prices.secid =ft.security_id) INNER JOIN (SELECT trans.security_id AS secid, trans.investwrapperID_id as iwID, SUM((CASE WHEN trans.buysell = 'b' THEN trans.quantity ELSE 0 END)* trans.price) / SUM(CASE WHEN trans.buysell = 'b' THEN trans.quantity ELSE 0 END) AS avgCost FROM finance_transaction as trans GROUP BY trans.security_id, trans.investwrapperID_id) AS cost ON (cost.secid = ft.security_id and cost.iwID = wi.id) GROUP BY w.wname, wi.wrapperType_id, wi.act_code, wi.act_provider, ft.security_id but I don't know how to use the Django … -
Is there a way to handle admin radio buttons changes?
I have model (Object) which have some fields + rating: class Object(PolymorphicModel): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, db_column='author') title = models.CharField(max_length=300) city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.CharField(max_length=300) phone = models.CharField(max_length=20, default='') email = models.CharField(max_length=100, default='') site = models.CharField(max_length=100, default='') facebook = models.CharField(max_length=100, default='') instagram = models.CharField(max_length=100, default='') content = models.TextField() rating = models.IntegerField(default=10) created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" There is also Comment model to these objects: class Comment(models.Model): object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, db_column='author') content = models.TextField() rating = models.TextField() approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.content}" Ok here is the deal, I have approved_object and admin_seen which are represented to radio buttons in Django Admin. I want, when, some of admins, open comment, which is not approved and check radio buttons for admin_seen and approved_object the script should update ratings and average rating with Comment.objects.filter(object_id=pk).aggregate(Avg('rating'))['rating__avg'] So I found how to rewrite save method with def save_method but I don't know how to handle if radiobutton is checked or not and update ratings? admin.py: class CommentScreenAdmin(admin.ModelAdmin): raw_id_fields = ('author', 'object') def save_model(self, request, obj, form, change): #to do...