Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Injecting Django attributes into Java script
I am trying to add the title of my post to a javascript but I am doing wrong it is not showing correctly. My objective is the show the title and the link of the Django page to the Facebook sharing button. The name of the app is score Here is the models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) design = models.ImageField( blank=False, null=True, upload_to=upload_design_to) Here is the post-details.html <!-- Share Buttons TODO --> <div class="icons"> <ul> <a target="_blank" class="facebook-btn" href="https://facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}"><li class="facebook"><i class="fab fa-facebook-f"></i></li></a> <a target="_blank" class="twitter-btn" href="https://twitter.com/intent/tweet/?text={{ request.build_absolute_uri }}"><li class="twitter"><i class="fab fa-twitter"></i></li></a> <a target="_blank" class="linkedin-btn" href="#"><li class="linkedin"><i class="fab fa-linkedin"></i></li></a> </ul> </div> <!-- Share Buttons --> Here is the script function init() { let postUrl = encodeURI(document.location.href); let postTitle = score=> score['title']; console.log(postTitle); } init(); My question: how to get the console to show the name of the {{ object.title }}, currently it is showing score=> score['title'] -
django: template show timezone also for the datetime
I am sending the following datetime timezone aware object to django template current_time = timezone.now() In my template i am showing it using {{ current_time }} it displays as: Feb. 10, 2021, 3:25 a.m I want it to display as Feb. 10, 2021, 3:25 a.m UTC I dont see which timezone the time is. So i want to be more clear by adding the timezone. how can i do this in django template -
I am getting a programming error in django after changing the models.py and deleting all my migrations besides __init__.py
I am getting a programming error - ProgrammingError at /admin/appointed/patient/ I changed my model from having an occupation =models.CharField(max_length=100) to frontlineWorker = models.BooleanField(default=False) and then went to delete all the migrations I made I then did python3 manage.py makemigrations python3 manage.py migrate which worked fine and created my new models. However, after entering into my localhost which is currently running this server, I get the programming error above because column appointed_patient.frontlineWorker does not exist I have tried to see my psql, and have tried $ python3 manage.py reset_db using django-extensions to reset my tables. this gives me psycopg2.errors.InsufficientPrivilege: must be owner of database appointed2 psycopg2.errors.InsufficientPrivilege: permission denied to create database when i run psql and try to see my tables for my database, I do not see anything either. Does anyone have any suggestions for me to try? Thank you -
Unable to set post id for Django and Vue application
Am trying to use vue to submit a comment on a post to the backend. am unable to get the post id. The app has a feed like twitter. I want users to be able to comment on post without going to the detail view. methods: { commentPost(post_id) { console.log('commentPost:', post_id); if (this.body.length > 0) { var post = { 'post_id': post_id, 'body': this.body, 'user': this.user, 'created_at': this.created_at }; fetch('/api/add_comment/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, credentials: 'same-origin', body: JSON.stringify(oink) }) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); } }, However when i click on the submit button. In the browser log i get commentPost: undefined. How can i set the post id -
Empty query parameters in url
Using Django==2.2.13, djangorestframework==3.8.1 This is a question to establish "what is the right thing to do", rather than "how to do it". I have a backend API route that takes some optional query parameters. The frontend has noticed that if they call: https://my_domain.com/some_path/?foo= They trigger a ["natural"] behavior that checks for the foo value, and similar to a bad value, takes the empty value and responds: { "objective": [ "Select a valid choice. is not one of the available choices." ] } I think that if an endpoint supports a query param, or a hundred of them, if I am not trying to filter by them I should not include them like that: https://my_domain.com/some_path/ (if you don't want to filter by it then don't use it) The other side thinks that all query parameters should be in, empty or not. (if you include an empty query param, then you want all -- unfiltered) The question is, what is the "right" thing to do, methodology/pattern-wise? tl;dr in case you are curious, this is the basic look of the endpoint: in views file: class SomeView(viewsets.ModelViewSet): filter_class = SomeViewFilter ... In the filters file: class SomeViewFilter(django_filters.FilterSet): ... the_query_parameter = EnumMultipleChoiceFilter( choices=[(my_val.name, my_val.name) for … -
member-related permission checking rest-framework
So This is how I currently validate permissions. I have a base class like this class MemberPermission(permissions.BasePermission): """ The Base Permission class that every member-permission must inherit from. Provides reusable functions to validate the existence of permissions, as well as facilitates additional context validation. To check permissions, we need to get the member object first. However, as the approach to do the same differs per view, the `get_member` method must be suitably overwritten by subclasses. """ CHECK_METHODS = [] PERMISSION_LABEL = None message = 'permission denied' @classmethod def get_member(cls, view, request, obj=None): # returns the member-object for the current view. This method # may vary greatly for different permissions because # the approach to lookup the box for the request's user might differ # References the box-id in the url by default box = get_object_or_404(api_models.Box, id=view.kwargs.get('box_id')) return get_object_or_404(api_models.Member, box=box, user=request.user) @classmethod def get_overwrite_channel(cls, view, request, obj=None): # returns the overwrite-channel-object for the current view # This method may vary greatly for different permissions # because the approach to lookup the box for the request's # user might differ. Returns None by default return None def validate_additional_context(self, view, request, member, obj=None): # check for implementation of additional permission-logic # subclasses must … -
Can you host a Django app and Strapi API on the same server using NGINX?
Is it possible to have... A static file is served from => 0.0.0.0 A Django application served at => 0.0.0.0/django A Strapi API at => 0.0.0.0/strapi ... with NGINX? I've tried server { listen 80; server_name 0.0.0.0; root /var/www/html; index index.html; location /static/ { root /home/user/app/static/; } location /django { proxy_pass http://0.0.0.1:8000; } location /strapi { proxy_pass http://0.0.0.1:1337; } } # I have my real IP not 0.0.0.0 in the file But / returns my static /django returns a django 404 page /strapi returns an html with 'not found' Is the question I'm asking "Can an NGINX location alias a port?" -
Django ModelChoiceField how to save not just the string representation but also the other database(model) row values
I have 2 models. The customer model and the customerpricing model. class Customer(models.Model): priceline= models.IntegerField() billto=models.IntegerField(null=False,default=False,db_column="billto") customername=models.CharField(max_length=500) def __str__(self): return self.customername class Meta: db_table='customer' class Customerpricing(models.Model): rep=models.CharField(max_length=10) billto=models.ForeignKey(Customer, on_delete=models.CASCADE, null=False,db_column="billto") customernm=models.CharField(max_length=60) specialterms=models.CharField(max_length=100) start=models.DateField(default=timezone.now) Here is my form. class CustomerpricingForm(forms.ModelForm): customernm=forms.ModelChoiceField(queryset=Customer.objects.all()) priceline=forms.ModelChoiceField(queryset=priceline.objects.all()) billto=Customer.objects.all() class Meta: model = Customerpricing fields = ['customernm','billto', 'priceline','rep','specialterms'] widgets= { 'rep': forms.TextInput(attrs={ 'class': 'form-control' }), 'start': forms.SelectDateWidget(empty_label=("Choose year", "choose Month", "choose day" ),attrs={ 'class': 'form-control' }), 'specialterms': forms.TextInput(attrs={ 'class': 'form-control' }), } Here's my view. def addnew(request): if request.method == "POST": form = CustomerpricingForm(request.POST) if form.is_valid(): try: form.save() return redirect('/customerpricingfile') except Exception as e: #print (e.message, e.args) print (form.errors) print(e) else: messages.error(request,"Error") else: form = CustomerpricingForm() What I want to do seems so easy. When the user selects their value from the ModelChoiceField named customernm I want to also save that model's (Customer model) other database rows aka model fields which are billto and shipto with the Customerpricingform. How can I do this? I've spent far too much time on this and your help would be greatly appreciated. -
How to properly use code coverage with django redis queue?
I'm creating a Django rest API that runs async tasks with django-rq. I run my unit tests in sync mode, just like the django-rq docs indicates. The problem is that my code coverage is low because the code that the async tasks run is not being covered. How can I fix this? -
How to force a value on created_at and updated_at in Django
I have a model in Django that have the created_at and updated_at fields. I implement certain functionality that depends on those dates, so I want to write some unit tests, but when I create the objects, they always save both fields with the current date. I assume (I looked up but I did not find any information) that Django in some way does not allow the client to updated those fields, and it does it by itself. There is any way to overwrite this behavior in a test? -
Django model save method don't work with celery
I'm working in a project using drf, django channels and celery i want to push notification on created to subscribed channel and it works well but when using celery the model create method doesn't excute save method or any signal that's my taks @shared_task() def send_notification_to_all(data, users=None): if not users: users = User.objects.values_list('id', flat=True) for user in users: Notification.objects.using('notifications').create(user_id=user, title=data['title'], message=data['message'], url=data['url']) and excute it using send_notification_to_all.delay(data) and that's my consumer class LiveNotificationConsumer(ListModelMixin, GenericAsyncAPIConsumer): serializer_class = NotificationSerializer permission_classes = (permissions.IsAuthenticated,) async def accept(self, **kwargs): await super().accept(** kwargs) await self.model_change.subscribe() @model_observer(Notification) async def model_change(self, message, observer=None, action=None, **kwargs): if message['user'] == self.scope['user'].id: await self.send_json(message) @model_change.serializer def model_serialize(self, instance, action, **kwargs): return NotificationSerializer(instance).data def get_queryset(self, *args, **kwargs): user = self.scope['user'] return Notification.objects.filter(user=user).using('notifications') -
call_command migrate problem python django
I'm trying to add dynamically app and do makemigrations and migration, but it doesn't show print ('2'). Reboots and asks to apply the migration manually some.py settings.INSTALLED_APPS += ('tests.apps.OrderConfig',) apps.app_configs = OrderedDict() apps.apps_ready = apps.models_ready = apps.loading = apps.ready = False apps.clear_cache() apps.populate(settings.INSTALLED_APPS) management.call_command('makemigrations','tests', interactive=False) print('>>WORK1') management.call_command('migrate', app_module.MODULE_NAME, interactive=False, skip_checks=True) print('>>WORK2') #this don't show Terminal: No changes detected in app 'orders' >>WORK1 Operations to perform: Apply all migrations: orders Running migrations: [11/Feb/2021 02:07:22] "GET /plugins/repository/12/ HTTP/1.1" 200 14459 C:\PythonProject\ServiceCRM3\plugins\settings_plugin.py changed, reloading. Applying orders.0001_initial...Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): orders. Run 'python manage.py migrate' to apply them. February 11, 2021 - 02:07:24 Django version 3.1.4, using settings 'ServiceCRM3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. -
My django app breaks when installing geo django: libpoppler not found
I developing an app but it doesn't compile after installing django-leaflet and django.contrib.gis. Everythin works perfectly if I don't use django.gis nor django-leaflet, and it appeared after I struggled a lot installing the gdal library. I thought it could be compatibility with Python, because I'm using latest version, but downgrading didn't work form me (should I downgrade more?) Any suggestion? The error I see: > File "/home/horacio/anaconda3/envs/epec/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from … -
Django How to Fix Multiple Server Issues
I have this model, and it has been causing me a lot of trouble here are the models: class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=20) text = models.TextField(default='') created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) class Videos(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='videos/') def __str__(self): return self.title First, when I try to migrate anything I get: django.db.utils.OperationalError: table "blog_videos" already exists This is for model Videos. This error happened after I deleted a few migration files. Then when I try to add to the model "Comment", I get this: django.db.utils.IntegrityError: NOT NULL constraint failed: blog_comment.author_id_id This happened after I added this to comment model: author_id = models.ForeignKey(User, on_delete=models.CASCADE, default='') I then deleted this model and have this problem now. I am unable to fix this because I can't migrate anything becuase of the issue above. Please help me. I am using python 3.8 and django 3.1.5. I am fine deleting all data (It's all worthless at the moment, its just dummy data. Cheers. -
Override vs extend Django's models.Manager to handle deleted objects (best practice)
There is a requirement, that nothing should be deleted from database So, obviously, all models should be inherited from something like this: class BaseModel(models.Model): is_deleted = models.BooleanField(default=False) But, it is not obvious how to make QuerySets handle is_deleted the best way I can imagine two options: 1) Override BaseModel's Manage's ._get_query_set() method So, both will return only active objects (marked as is_deleted=False): Article.objects.all() Article.objects.filter(id__in=[1, 2]) Even .get(...) will raise 404 if is_deleted=True: Article.objects.get(id=1) Also, extend with additional method, to actually access is_deleted=True: Article.objects.deleted(id=1) 2) Second option is to extend BaseModel with additional second Manager, let's say - actual So, all three will exclude objects with is_deleted=True: Article.actual.all() Article.actual.filter(id__in=[1, 2]) Article.actual.get(id=1) Regular .objects stands with native behaviour: Article.objects.all() Article.objects.filter(id__in=[1, 2]) Article.objects.get(id=1) --- Maybe there are another good options? Is there a best practice? Big thx for advices! -
Working with one-to=many relationships (Django)
Okay....previously I wrote up a simple HTML-CSS-Javascript site. I then created an empty Django project and tried to put everything in that project. I created a real mess! So I am now writing everything up from scratch, working on the Django project first. I still am having problems with the database I set up. Here is my models.py: from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) description = models.TextField() source = models.CharField(max_length=200) source_site = models.CharField(max_length=200) def __str__(self): return self.title class Chapter(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE, related_name='chapters') chtitle = models.CharField(max_length=100) chtitletext = models.CharField(max_length=200) chtext = models.TextField() def __str__(self): return self.chtitle And here is my views.py: from django.shortcuts import render, get_object_or_404 # Create your views here. from django.http import HttpResponse from .models import Book, Chapter def index(request): book_list = Book.objects.order_by('-id') output = ', '.join([b.title for b in book_list]) context = { 'book_list': book_list, } return render(request, 'sophia/index.html', context) def readBook(request, book_id): book = get_object_or_404(Book, pk=book_id) chapter_list = Chapter.objects.order_by('-id') context = {'book':book, 'chapter_list':chapter_list} return render(request, 'sophia/readbook.html', context) and here is my urls.py: from django.urls import path from . import views app_name = 'sophia' urlpatterns = [ path('', views.index, name='index'), path('<int:book_id>/', views.readBook, name='readbook'), ] and finally, my … -
How to call distinct() on django-pivot results
I've been using the django-pivot package to pivot complaint data, and it's an amazing package that generally works like a dream, but I noticed yesterday that when rows or columns are referring to ManyToMany fields, the results include some duplicates. When I'm constructing my own queries I just throw a distinct() on the end of it, is there a way to do something similar in django-pivot? -
Fetch failed loading: GET (with same path)
Got an issue with fetch in js + Django document.addEventListener("DOMContentLoaded", function () { // loading inbox as default load_mailbox("inbox"); console.log("again loaded INBOX____________") // when form is submitted, send email to other user document.querySelector("#compose-form").onsubmit = function () { fetch("/emails", { method: "POST", body: JSON.stringify({ recipients: document.querySelector("#compose-recipients").value, subject: document.querySelector("#compose-subject").value, body: document.querySelector("#compose-body").value, }), }) .then((response) => response.json()) .then((result) => { // Print result console.log(result); // after sending email, loading page with sent emails load_mailbox("sent"); }); }; }); Load mailbox will call other function, which will fetch the data for the page if (mailbox === "sent") { fetch_mail_by_folder("sent") } function fetch_mail_by_folder(folder) { fetch(`/emails/${folder}`) .then((response) => response.json()) .then((emails) => { emails.forEach(email => { // we fetching data for this page, and paste it into new div const element = document.createElement("div"); element.innerHTML = `some data`; element.addEventListener("click", function () { get_email(email.id, folder); }); const div = document.querySelector('#emails-view') // after that we add elements into existing html div div.append(element); }) }); } There is an error when mail was sent, (after concole.log with "email sent successfully") Fetch (fetch_mail_by_folder("sent")) was failed, (see screenshot). After, I tried to fetch the "sent" page with other function (just a simple button): document .querySelector("#sent") .addEventListener("click", () => load_mailbox("sent")); And it works well (see … -
How can I resolve an" ImportError: attempted relative import with no known parent package" issue in a Django project?
I'm working on Chapter 18 of Python Crash Course, and have started over from scratch twice already, all 53 steps. (A very educational process) The program was working fine until I tried to add the code for individual pages. Now, it won't run at all. It keeps saying that views aren't defined. I've tried every suggestion I've found for similar issues without success and double checked all the elements. Here is the code for my urls.py and views.py. Any information/suggestions on how to resolve this would be greatly appreciated. """Defines URL patterns for learning_logs""" from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [ path('topics/<int:topic_id>>/',views.topic,name = 'topic'), path('', views.index,name='index'), path('topics/',views.topics, name='topics'), ] from .models import Topic from django.shortcuts import render def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics':topics} return render(request,'learning_logs/topics.html',context) def index(request): return render(request,'learning_logs/index.html') def topic(request, topic_id): topic = Topic.objects.get(id= topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic,'entries':entries} return render(request, 'learning_logs/topic.html',context) -
Custom User Model in Django (email as username) - removing username safely if overriding AbstractUser
In my Django project, I would like users to register/login with their email address rather than a username, so I am planning to use a custom User model. Alongside this, I would like to define a couple of extra fields, and avoid extra database queries that would come with having a separate Profile model (with One-to-one relationship) for those. Other than these things, the default User functionality is exactly what I need, so rather than overriding AbstractBaseUser and having to rewrite code without confidence, I think overriding AbstractUser is the way to go. But I'm not sure, so that's where you come in! I have read many blog posts and threads on StackOverflow about the subject and there seems to be a common approach when using AbstractUser for this purpose (setting username = None) as follows: class CustomUserA(AbstractUser): username = None email = models.EmailField(unique=True) #necessary as it must now be unique extra_field = models.CharField(max_length=20) #for example USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] #necessary to empty this as 'email' is now USERNAME_FIELD objects = CustomUserManager() If this approach is used, a custom user manager (a subclass of BaseUserManager) needs to be set up, as it states here in the docs: You … -
Restrict access to a url unless user is coming from a certain page
For example the user won't be able to access page 'b' unless they are coming from page 'a' (they can't just paste the link and go to the page) -
Django Custom Use with Array of Another Model (Acting like a shopping cart)
Newbie to Django, Django rest_framework, and Djoser here. I am building the backend to what you can think of as a simple shopping app (think coffeeshop on this one). At the moment, I have a custom User model in one app called authapp and a Coffee model that lives in another app called apiapp. My goal is to allow User objects to have 0-infinity number of Coffee objects to act as their shopping cart and to have that data displayed in the users endpoint. Currently, I the User model looks like the following in models.py: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): email = models.EmailField(verbose_name='email', max_length=255, unique=True) phone = models.CharField(null=True, max_length=255) coffees = models.ManyToManyField("apiapp.Coffee", verbose_name="coffee") REQUIRED_FIELDS = ['username', 'phone', 'first_name', 'last_name'] USERNAME_FIELD = 'email' def get_username(self): return self.email In serializers.py, I have: from djoser.serializers import UserCreateSerializer, UserSerializer from rest_framework import serializers from .models import * # Create your serializers here class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User field = ['id', 'email', 'username', 'password', 'first_name', 'last_name', 'phone', 'coffee'] In the admin dashboard, I currently see this when editing a User object (looks like you can select and deselect any / all of the … -
How to caught exception when django query is not performed due to no internet connection
I need to handle the scenario when django query can't reach the database due to no internet connection I tried with try-except block like this, but there's no exception caugth: try: return self.filter(my_model_id=<some int number>) except Exception as e: logger.error(e) How can i handle this? -
Django's set_exprity() in JsonResponse
I want to implement the "Remember me" functionality in my app. According to the docs and other questions the snippet request.session.set_expiry(0) is supposed to destroy the user session when the user closes the browser. My problem is that I can't find a way to add this to the JsonResponse in my login view. (the logic is not implemented yet) @require_POST def login_view(request): data = json.loads(request.body) email = data.get('email') password = data.get('password') if email is None or password is None: return JsonResponse({'detail': 'Please provide email and password.'}, status=400) user = authenticate(email=email, password=password) if user is None: return JsonResponse({'detail': 'Invalid credentials.'}, status=400) login(request, user) request.session.set_expiry(0) # does not work return JsonResponse({'detail': 'Successfully logged in.'}) -
Fastest way of performing multiple different calculations to every object in a queryset
I have these two models in my db: class Product(models.Model): name = models.CharField(max_length = 64) retailer = models.ForeignKey(Retailer, related_name = 'products', on_delete = models.CASCADE) brand = models.ForeignKey(Brand, related_name = 'products', on_delete = models.CASCADE, null = True, blank = True) enabled = models.BooleanField(default = True) def __str__(self): return self.name class Item(models.Model): product = models.ForeignKey(Product, related_name = 'p_items', on_delete = models.CASCADE) date = models.DateField(null = True, blank = True) user = models.ForeignKey(User, related_name = 'p_items', on_delete = models.CASCADE) net_price = models.PositiveIntegerField(blank = True) class Meta(): ordering = ['-date'] These models are in fact an alias to protect my employer. Keep this in mind if something doesn't really make sense - The db structure can't change. An Item represents one sale made by one of our users. The user needs to fill which type of product and when they did sell it, also by how much. However, the net_price chosen by the user isn't whats being charged at the client. There are two types of "added costs" later added to the net_price. One of them is deliberately chosen by the management, and it can be done days after the item has been added to the db. With this new model: (...) class GradeInflation(models.Model): …