Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Javascript is not being imported to global functions
I'm developed a webapp using Django and all works fine. Now I wanted to add a Webseit Tour guide and im using https://github.com/iamdanfox/anno.js. Now to my problem: I downloaded all the files i need and added the files to my static files. I'm importing the js files in my HTML as follows: home.html / Local <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script src="{% static 'main/js/tour/anno.js' %} type="text/javascript""></script> <script src="{% static 'main/js/tour/jquery.scrollintoview.js' %}" type="text/javascript"></script> The javascript files are unedited and saved in the static files that are written using jquery: https://github.com/iamdanfox/anno.js/blob/gh-pages/dist/anno.js https://github.com/iamdanfox/anno.js/blob/gh-pages/bower_components/scrollintoview/jquery.scrollintoview.js If I'm on my Local machine then my file is imported and everything works as expected. But if I upload it to my production server the file (anno.js) is not loaded (well atleast the function Anno is not imported to the global env). Im using Google Appengine to host the webapp. home.html /production <script src="https://storage.googleapis.com/pa_static/dev/main/js/tour/anno.83c63efc17a2.js" type="text/javascript""></script> <script src="https://storage.googleapis.com/pa_static/dev/main/js/tour/jquery.scrollintoview.42cd3e5eb217.js" type="text/javascript"></script> As STATICFILE_STORAGE im using a custom class, that inherates from ManifestStaticFilesStorage STATICFILES_STORAGE = 'web.storage.ForgivingManifestStaticFilesStorage' Any Idea why this is? Im really clueless on even where to start looking for the error. Thank you very much in advance! -
How to handle this in high concurrency in Django?
I have some code like this: bargain_count = BargainLog.objects.filter(bargain_start_log=bargain_start_log).count() # calculate `bargain_money` according to current `bargain_count` BargainLog.objects.create(bargain_start_log=bargain_start_log, bargain_money=bargain_money) But in case of high concurrency, I would get the same value of bargain_count, and then I would not get bargain_money as expected. So, it there any approach I can bundle the count() and create() in atom. -
models.E006 in abstract parent model - Django 3.1
I have an abstract model and a few other classes that inherit from it. # models.py class Parameter(models.Model): data = integer = models.IntegerField(blank=True, null=True) class Meta: abstract = True class Temperature(Parameter): received_timestamp = models.DateTimeField(default=datetime.now, blank=True) class Ph(Parameter): received_timestamp = models.DateTimeField(default=datetime.now, blank=True) although my Parameter class is abstract, I get models.E006 error in `makemigrations script. graphs.Temperature.data: (models.E006) The field 'data' clashes with the field 'data' from model 'graphs.temperature'. graphs.Ph.data: (models.E006) The field 'data' clashes with the field 'data' from model 'graphs.ph'. based on Abstract base classes and this question, if I inherit from an abstract base class, there should be no conflict in the name of the fields of various child classes with their parent (because it's abstract). any ideas? -
Django app deployment in AWS Beanstalk - Error after deployment
I have a django app deployed to AWS beanstalk. The first version was fine after following the official documentation: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html when I deploy, I get this error on the terminal and my eb status health is Red. I follow all the instructions but don't know what is the problem. and the 502 Bad Gateway occure in my page. 2020/12/17 15:03:40.884211 [ERROR] An error occurred during execution of command [app-deploy] - [StageApplication]. Stop running the command. Error: chown /var/app/staging/unifolio-src/bin/python: no such file or directory could Anybody kindly help me? -
automatically add a new models to admin page
i have a calculator app, inside it i have a Transaction , Family_group , Family_member models see pic below. i want everytime i try to make a new Transaction there will be a default 1 Family_group and Family_member added automatically, without me starting one each time. is there any way to do it ? -
Django + ReactJS. The Httponly cookie is not saved in the browser at React side. I also gave {withcredentials : true} at both side
I use django rest_framework_simplejwt to generate JWT token and set in browsable cookie with Httponly flag. At the Django side it work perfectly but at react side it not work perfectly. Read many answers related to this question like this and this but not solved my problem yet. Please help me Where am I wrong. DJANGO SIDE views.py from rest_framework_simplejwt.views import TokenObtainPairView from django.conf import settings from rest_framework import status from rest_framework_simplejwt.exceptions import TokenError,\ InvalidToken from rest_framework.response import Response class MyTokenObtainPairView(TokenObtainPairView): def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) except TokenError as e: raise InvalidToken(e.args[0]) # set access token in browser with Httponly cookie. res = Response(serializer.validated_data, status=status.HTTP_200_OK) access_token = serializer.validated_data['access'] res.set_cookie("access_token", access_token, max_age=settings.SIMPLE_JWT.get('ACCESS_TOKEN_LIFETIME').total_seconds(),samesite='Lax',secure=False, httponly=True) return res authentication.py from rest_framework_simplejwt.authentication import JWTAuthentication from django.conf import settings class CookieHandlerJWTAuthentication(JWTAuthentication): def authenticate(self, request): # If cookie contains access token, put it inside authorization header access_token = request.COOKIES.get('access_token') if(access_token): request.META['HTTP_AUTHORIZATION'] = '{header_type} {access_token}'.format( header_type=settings.SIMPLE_JWT['AUTH_HEADER_TYPES'][0], access_token=access_token) return super().authenticate(request) urls.py from .views import MyTokenObtainPairView urlpatterns = [ ...... path('auth/', include('djoser.urls')), # path('auth/', include('djoser.urls.jwt')), path('auth/api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), ] settings.py CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', 'http://127.0.0.1:8000' ) Work perfectly(Token set in cookie with Httponly.): REACTJS SIDE Login.js axios.defaults.withCredentials = true const Login = … -
Django search vector - no match on exact keyword
I have an application where customer can search for products by name, brand etc. the problem is if you write the exact name or the exact brand name will result in no match, if you write the half of the name or the id will return a match view def home(request): active_product = Product.objects.all().filter(show=True).order_by('-score', '-brand_name') #Paginator paginator = Paginator(active_product, 20) page = request.GET.get("page") active_product = paginator.get_page(page) #Filterd by search searchProduct = request.GET.get("do_search") if searchProduct: active_product = Product.objects.annotate(search=SearchVector('name', 'id', 'sex','brand_name'),).filter(search__icontains=searchProduct) return render(request, 'index.html', {'productObject': active_product}) Model: class Brand(models.Model): name = models.CharField(unique=True, max_length=30, blank=False,null=True) def __str__(self): return self.name class Product(models.Model): genderChoice = (('W','Female'),('M','Male'),('U','Unisex')) id = models.BigIntegerField(primary_key=True, null=False) brand_name = models.ForeignKey(Brand, to_field='name', on_delete=models.CASCADE, related_name='brand_name', default='Brand Name') name = models.CharField(max_length=300, blank=False,null=False) sex = models.CharField(max_length=7,choices=genderChoice, default='U') p_type = models.CharField(max_length=50, blank=True,null=True) image_link = models.CharField(max_length=500, blank=True,null=True) stock_price = models.DecimalField(max_digits=10,decimal_places=2, default=999.00) show = models.BooleanField(default=False) in_stock = models.BooleanField(default=False) created = models.DateField(auto_now_add=True) volume= models.CharField(max_length=50, blank=True,null=True) score = models.IntegerField(default=1) price = models.DecimalField(max_digits=100, default=999.00, decimal_places=2) def __str__(self): template = '{0.name} {0.brand_name} {0.volume} {0.price}' return template.format(self) html: <form class="my-2 my-lg-0" action="{% url 'home'%}" method="GET"> <div class="input-group mb-3"> <input type="search" class="form-control border-dark" placeholder="search" aria-label="Search" aria-describedby="button-addon2" name="do_search"> <button class="ml-1 btn btn-outline-dark" type="submit" id="button-addon2">Search</button> -
Error building my web application using Docker
I am a newbie using Docker, I have completed my web application in Django, and I want to containerize it using Docker. I have gone through a particular tutorial where an existing web application was dockerized successfully but when I tried the same method, I got an error which says Failed to execute script docker-compose error logs Building web Traceback (most recent call last): File "compose\cli\main.py", line 67, in main File "compose\cli\main.py", line 126, in perform_command File "compose\cli\main.py", line 302, in build File "compose\project.py", line 468, in build File "compose\project.py", line 450, in build_service File "compose\service.py", line 1147, in build compose.service.BuildError: (<Service: web>, {'message': 'dockerfile parse error line 1: FROM requires either one or three arguments'}) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose\cli\main.py", line 78, in main TypeError: can only concatenate str (not "dict") to str [11920] Failed to execute script docker-compose Dockerfile FROM python: 3 ENV: PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 -
Django author Form not saving to database
models.py class Blog(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.CharField(max_length=100, unique=True) post_pic = models.ImageField(upload_to ='media/post_pics/', default =None ) body = models.TextField() posted = models.DateTimeField(db_index=True, auto_now_add=True) #author = must be logged in, populate from login details forms.py class postForm(forms.Form): title = forms.CharField(max_length=100) slug = forms.CharField(max_length=100) post_pic = forms.ImageField() body = forms.CharField(widget=SummernoteWidget()) views.py def write_detail(request): template_name = 'blog/write.html' if request.method == 'POST': post_form = postForm(request.POST) if post_form.is_valid(): new_post = Blog(title=title,slug=slug,post_pic=post_pic,body=body) new_post.save() return HttpResponseRedirect(blog.get_absolute_url()) else: post_form = postForm() return render(request, template_name, {'post_form': post_form}) write.html {% extends 'blog/base.html' %} {% load static %} {% block back-img %}'{% static 'blog/assets/img/intro.jpg' %}'{% endblock back-img %} {% block titdes %}Write{% endblock titdes %} {% block title %}Write{% endblock title %} {% block pagedes %}A django powered community blog{% endblock pagedes %} {% block body%} <form method = "POST"> {{ post_form.as_p }} {% csrf_token %} <button type="submit" class="btn btn-primary">Publish</button> </form> {% endblock %} I have set up this form so that authors can write articles to the blog without accessing the admin panel and I believe it should work but it isn't saving to the database. I have tried to work on the views over and over but don't know what else to do. Please don't delete my … -
PKCE Parameters for Snapchat
I'm attempting to write a django-allauth Provider for Snapchat and I'm stuck at a road block. Snapchat requires PKCE parameters. I first changed the AUTH_PARAMS. 'AUTH_PARAMS': { 'code_challenge': 'state', 'code_challenge_method': "S256" } This has only resulted in invalid responses from the Snapchat API upon Access_Token Request, after I have the code response. This error the first error I got. {'error': 'invalid_request', 'error_description': 'Invalid code_verifier length.', 'state': ''} After overriding the SocialLogin.stash_state I receive this error. {'error': 'invalid_grant', 'error_description': 'Invalid code_verifier.', 'state': ''} From what I can dig through the code of all auth I can't find anything in the codebase on the PKCE parameters or base64 Url SHA256 encoding. I'm willing to implement the solution but I'm stuck finding where to subclass the state parameters then match it after. There are some issues around the Snapchat Docs with this as well. https://gist.github.com/CisarJosh/778485dc31d9f268da0339f715ab86fd This is a gist with some of my attempt. -
How to do a QuerySet in Django returning the last datetime
I'm trying to do a QuerySet using Django, want to return the latest datetime from database, with the other fields, I used prefetch_related(). The Max('data') used return all the records in the database, not just the recent ones. These are my models: #models.py class TServices(models.Model): services = models.ForeignKey(Services, on_delete=models.CASCADE) servName = models.CharField(max_length=50) def __str__(self): return self.nomeServ class Control(models.Model): costumer = models.ForeignKey(Costumer, on_delete=models.CASCADE) date = models.DateTimeField(null=True, blank=True) def __str__(self): return '%s' % self.date class Meta: get_latest_by = "date" class ServiceStatus(models.Model): control = models.ForeignKey(Control, on_delete=models.CASCADE) services_type = models.ForeignKey(TServices, on_delete=models.CASCADE) status = models.CharField(max_length=10) def __str__(self): return '%s' % self.status My views, where I do the query in Django: #views.py def integr(request, servico): costumer = Costumer.objects.all().order_by('name') services = Services.objects.filter(servName__iexact=services) control = Control.objects.prefetch_related('servicestatus_set').annotate(Max('date')) context= { 'costumers': costumer, 'controls': control, } return render(request, 'app/integr.html', context) This is the query that I made in my database and returned the recent date with the costumer_id. select max(date), app_control.costumer_id from app_control inner join app_servicestatus on app_servicestatus.control_id = app_control.id inner join app_tservices on app_tservices.id = app_servicestatus.services_type_id where app_tservices.services_id = 1 group by app_control.costumer_id -
Slicing a for loop in Django
I'm trying to make this for loop iterating through the blog posts that have been published today and I just want the user to have an overview of the LAST three posts. It is turning out to be very difficult :( {% for post in object_list %} {% if date == post.postday %} <b>{{ post.name }} {{ post.surname }}</b> </br> {% endif %} {% endfor %} I have tried to slice the iteration as follow: {% for post in DeathDay_list|slice:":3" %} {% if date == post.postday %} <b>{{ post.name }} {{ post.surname }}</b> </br> {% endif %} {% endfor %} However, the problem is that it get the full list than it checks if the day matches with today and then it slices the first three element which are not from today and it does not show anything on the views. Please :) -
Disable related object links in django admin delete confirmation page
I'm looking for a way to remove the links to related objects on the delete confirmation page of the django admin. I can see that I can override the delete_selected_confirmation.html, I don't see how I can change the content of the deletable_objects in the template. https://github.com/django/django/blob/stable/2.2.x/django/contrib/admin/templates/admin/delete_selected_confirmation.html This appears the be the related code that generates the deletable_objects rendered in the template: https://github.com/django/django/blob/bb64b99b78a579cb2f6178011a4cf9366e634438/django/contrib/admin/utils.py#L104 I can just remove the objects section in the template, but I'd like to display the names (__str__) if possible. Is there an easy way to override/replace the section of code that generates the deleteable_objects used in the delete_selected_confirmation.html template? -
Error when migrating to heroku postgres db: multiple default values specified for column "id"
I am currently deploying my django application to Heroku and I keep getting an error when migrating my database table to the Postgresql database. I get the following error: django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "planning_location" I already tried the solution specified in this post: django.db.utils.ProgrammingError: multiple default values specified for column "_id" of table "Asset_movie". However, that didn't solve it unfortunately.. This is the structure of the planning_location model: class Location(models.Model): name = models.CharField(primary_key=True,max_length=200, unique=True) locationid = models.UUIDField(default=uuid.uuid4, editable=False) slug = models.SlugField(max_length=200, editable=False) description = models.TextField(blank=True, null=True) created_date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): # create slug from name when saving for the first time if not self.slug: self.slug = slugify(self.name) super(Location, self).save(*args, **kwargs) The name is the primary key, which is essential for another part of the application. Since I do not have another id field I created an UUID field which serves kind of as a second id, without being a primary key. Does anybody know why this does not work, and what can be changed to make it succeed? -
How to solve circular import in django model?
I have created one apps in django: lecture The code in lecture.models class SchoolDepartment(models.Model): id = models.AutoField(primary_key=True) class Professor(models.Model): id = models.AutoField(primary_key=True) school_department = models.ForeignKey(SchoolDepartment) class Lecture(models.Model): id = models.AutoField(primary_key=True) school_department = models.ForeignKey(SchoolDepartment) When i run, this code raise error. ImportError: cannot import name 'SchoolDepartment' from partially initialized module 'lecture.models' (most likely due to a circular import) I have got to know, the error is because of the circular import. So i change this code like this. class SchoolDepartment(models.Model): id = models.AutoField(primary_key=True) class Professor(models.Model): id = models.AutoField(primary_key=True) school_department = models.ForeignKey('lecture.SchoolDepartment') class Lecture(models.Model): id = models.AutoField(primary_key=True) school_department = models.ForeignKey('lecture.SchoolDepartment') But still raise error ImportError: cannot import name 'SchoolDepartment' from partially initialized module 'lecture.models' (most likely due to a circular import) How can I fix it? -
How to add the fake data to mysql using django-seed
i have one project "mainreview" and inside this project i have one app called "products" please below the models image i made in products; [enter image description here][1] and i made user_seed to make fake data into mysql using django-seed below is my directory tree [enter image description here][2] last image is the problem i can not solve . i made the "seed_users " to make fake data into mysql db but it happened error when i write "python manage py seed_user --number 10" that error is [enter image description here][3] [1]: https://i.stack.imgur.com/t90j9.png [2]: https://i.stack.imgur.com/Uhpqh.png [3]: https://i.stack.imgur.com/XYPPc.png i wonder why it error happend.. if i do not use the method to use django-seed let me know how to write it. -
what is diffrences between CASCADE and CASCADE()
In django models for deleting an object in model we use on_delete=models.CASCADE but why we do not use models.CASCADE() I mean what is differences between CASCADE AND CASCADE() and why we do not use CASCADE() -
Keep recieving server error after hosting on heroku
i have been trying to host my django application on heroku, i've made several attempts and they all proved null, initially i was encountering failure in serving my staticfiles, then i disable staticfiles and was able to deploy the site, but then when i try to visit my newly deployed site i keep encountering Server Error, i have followed the steps in heroku documention, for deploying django sites and even installed django-heroku, but still get the same error, can i get a suggestions please??? -
Django Rest Framework Extra kwargs fields for Password and Unique Email
I tried creating serializers for my Model and tried serializing Model I want password field be typed in **** format when I try entering password and Email to be unique from Extra kwargs fields how can I do that? here is my serializers I tried. User = get_user_model() class AddBusCompanyUserSerializer(serializers.ModelSerializer): position = serializers.PrimaryKeyRelatedField(queryset=StaffPosition.objects.all()) class Meta: model = User fields = ( 'phone_number', 'password', 'position', 'email', ) extra_kwargs = {'password': {'write_only': True},'email':?} } what validator should I try making email being unique and password field being typed in **** format? -
POST register credentials to Django from Unity with C#
I have a Unity app with a custom made registration form. I want users to succesullyregister to a Django Backend at a url http://example/register/.com. I have a c# script (see below) that posts the information to the url. the script: using System.Collections; using System.Text; using System.Text.RegularExpressions; using TMPro; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class DjangoRegisterPost : MonoBehaviour { public TMP_Text resultText; public Button btnClick; public TMP_InputField inputUser; public TMP_InputField inputName; public TMP_InputField inputSur; public TMP_InputField inputEmail; public TMP_InputField inputPassword; public TMP_InputField inputPasswordConf; public string postURL = "http://example/register/.com"; private void Awake() { resultText.text = "Getting results from: " + postURL +"\n"; // simpleResultText.text = "Getting results from: " + localSimpleURL +"\n"; } private void Start() { //attach button event btnClick.onClick.AddListener(GetInputOnClick); } public void GetInputOnClick() { Debug.Log("Username = "+ inputUser.text); Debug.Log("Name = "+ inputName.text); Debug.Log("Surname = "+ inputSur.text); Debug.Log("email = "+ inputEmail.text); Debug.Log("Password = "+ inputPassword.text); Debug.Log("ConfPassword = "+ inputPasswordConf.text); resultText.text += "Loading results .... \n"; StartCoroutine(GetWebResult(resultText)); } public IEnumerator GetWebResult(TMP_Text results) { WWWForm form = new WWWForm(); form.AddField("username", inputUser.text); form.AddField("name", inputName.text); form.AddField("surname", inputSur.text); form.AddField("email", inputEmail.text); form.AddField("password", inputPassword.text); form.AddField("password confirmation", inputPasswordConf.text); //doLogin.SetRequestHeader ("referer", "https://dividedsky.herokuapp.com/accounts/login/"); //doLogin.SetRequestHeader ("cookie", "csrftoken=" + csrfCookie); //doLogin.SetRequestHeader ("X-CSRFToken", csrfCookie); string searchURL = postURL; //Unity will retain Cookies … -
syntax error at or near "WITH ORDINALITY" error when trying to migrate postgreSQL
I was using MySQL on my computer and when I wanted to host my app on a server I could not do it because the mysqlclient package needs root priviliges!! so I had to use something else so I used the postgreSQL database and It connected and ran the makemigrations but when I tried to run the migrate it gave me the 'syntax error on or at "WITH ORDINALITY"'. Does someone know what is causing the problem?? every time I try to run migrate it give me this error!! -
django admin User and Group models fields in a model
i have a model Transaction and i havent add a group field, However i want to make kind of system that uses Group, User models . i want each group to have users . and each group can access its own Transaction model in the admin pannel. eg: users from group1 can only see Transactions made by users in same group. and so on for other groups.... models.py class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) and admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] def save_model(self, request, obj, form, change): obj.Group = request.user.groups.all() print(obj.Group) super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(group__name__in=request.user.groups.all()) i know i have to add User or Group field to Transaction, or maybe not.. since i dont want users to choose the group each time they make a Transaction. So what is the good approach of doing it? i need to modify save_mode and get_queryset but i dont know how -
How to run django on a server where php is already running
I have a new ec2 instance, where I installed Django and made the website running. But I want to upload the website on a server where rest of webs are PHP. I followed the same steps, but I am unable to run Django app. There is no error on console. So could any one guide me the steps I need to follow? -
can we upload images directly to database and can fetch that also without creating static_media and media_root, just sweet and simple
models.py of app to create models for database. name = models.CharField(max_length=200) img = models.ImageField(null=True,blank=True) desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default=False) settings.py where i am defining root of the media, i dont want this, i just want to upload image directly to database and fetch whenever i need. dont want to create any folder to keep those. # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] STATIC_ROOT = os.path.join(BASE_DIR,'assests') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') main urls.py , i dont know what i am doing, but i also dont want to do this, is there any shortcut way , also i dont want to store images in local folder i want to upload them direct to database and fetch when i need. """bhushan URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. … -
Django: update model’s field before save
I want to automatically change the status field of my project model once the system detects that all associated tasks are finished my model class Project(models.Model): srv = models.ForeignKey(Srv, on_delete=models.CASCADE, null = True, blank = True) project_title = models.CharField(max_length=200, unique = True) slug = AutoSlugField(populate_from = 'project_title', always_update = True) resume = HTMLField() pub_date = models.DateTimeField(auto_now_add = True) category = models.ManyToManyField(Category) state = models.BooleanField(blank=True, null = True, default = False) weighted = models.IntegerField(blank=True, null = True) def change_state(self, *args, **kwargs): if self.todo_set.all().count() == 0: return percentage_notes = round(self.todo_set.filter(state = True).count() * 100 / self.todo_set.all().count()) if percentage_notes == 100: self.update(state = True) super().save(*args, **kwargs) return class Todo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, null = True, blank = True) todo_title = models.CharField(max_length=200) I create the change_state definition so that it determines if all the tasks of the project are finished, but does not save the changes in the state fields in my project model