Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can django prefetch related work with 3 lookups?
I want to prefetch 3 tables plus the initial table. Here are model examples of the project i am working on class ExampleOne(models.Model): name = models.Charfield() option = models.BooleanField() money = IntegerField() class ExampleTwo(models.Model): word = models.Charfield() example_one = models.ManyToManyField(ExampleOne) number = IntegerField() class ExampleThree(models.Model): number = models.IntegerField() example_two = models.ForeignKey(ExampleTwo) def get_calculation_one(self): Calculate using data from Example_2 and Example_1 class ExampleFour(models.Model): date = models.DateField() example_three = models.ManyToManyField(ExampleThree) def get_calculation_two(self): Calculate using data from method on Example_3 Now I want to know if it is possible to retrieve data from all these models with as little hits to the database as possible because when I try to retrieve data it takes over one minute to retrieve the data and send it to the frontend The calculation might be making many database hits in order to get the data and calculate and i think that is why it is taking more than a minute to retrieve the data my view looks like this qs = ExampleFour.objects.prefetch_related( Prefetch('example_three__example_two__example_one') ).filter(...) Is there a way to use prefetch to make the retrieval faster or is there another suggestion on I can rewrite my code in order to avoid this long retrieval time? Note I … -
How to relate a Django form template to the id of an input html tag
newbie here, this is my problem, i used to have a form looking like this in my website where the ID's of each input helped my to apply a JavaScript code to let users check their password's strength, so as the checkbox to watch or hide the password etc... <input id="psw_1" type="password"> <input id="psw_2" type="password"> Now with Django i just need these two lines: {{ form.password1 }} {{ form.password2 }} If i use those templates inside an input or div tag or whatever, to assign the ID's i i need, it shows some weird outputs in the sign form, is there a way to use those ID's or tell the js script those Django templates are what I'm pointing to? -
How ro redirect user to correct page in django-oscar checkout?
I am trying to follow this implementation of django-oscar cash on delivery but after updating and changing things my checkout flow is getting redirected back and forth to two pages only. I am not sure where i am going wrong. ] -
How to proxy binary files in django
I have a Django service that needs to be a proxy for binary files. For example, the binary files FileA.pdf and FileB.xslx are in http://some-server.con/binaryfiles/. My service have to access this data, and then return that data in a Response. Currently, it works fine if I have a binary file on my own server, for example: file_name = './example.pdf' with open(file_name, mode='rb') as file: return Response( file.read(), headers={'Content-Disposition': 'attachment; filename="{filename}"'.format(filename=file_name)}, content_type=self.get_type(file_name)) But I'm not sure of how get the data from the other server. Can I open an external uri resources as it was a simple file? I will greatly appreciate any help -
Django Rest Framework fails to return a response if response it too large. http code 0
We are building an API on Django and using the Django Rest Framework. This API sits between two servers, so it receives requests from server A, makes requests to server B, formats the response from server B and responds back to server A with the formatted data. The view handler extends the ApiView class from DRF, and the response is a Response object from DRF as well. Here is pseudo code from views.py to put things into perspective: class dummy(APIView) # define auth here def get(request): # handle the request from server A # get the content here, from server B # content is a list of up to 1028 elements response = Response({'status':'success','content':content}, status=200) return response <--- fails here if content length > 200 elements The content is a list of dicts, each dicts contain 4 - 5 key/value pairs, if this list is less than 200 elements long, the response goes through just fine, but anything above 200 elements will result in a response code 0 and no error message explaining what happened, other than a broken pipeerror from server A. We increased the timeout on the request from server A to 30 seconds, just to be sure … -
?: (corsheaders.E014) Origin 'https://domain_name.com/' in CORS_ALLOWED_ORIGINS should not have path
MIDDLEWARE = [ ... "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ] CORS_ALLOWED_ORIGINS = [ "https://domain_name.com", "http://127.0.0.1:8000", ] django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E014) Origin 'https://api.krafttopia.com/' in CORS_ALLOWED_ORIGINS should not have path -
Getting Typerror in django but fields appear to be defined correctly
I'm brand new to django and I can't figure out why this is happening. Here is my model which I have added to my settings "Installed Apps" config and I have migrated: class User(models.Model): name = models.CharField(max_length = 200), state = models.CharField In the shell I import the model like so: from homepage.models import User then I try to create a new user like so: a = User(name='Alex', state='Alberta') and it throws this error which makes no sense to me because I've defined the fields of the User schema above: I know I'm missing something like maybe I'm supposed to add something to my views.py file before starting the shell but I just don't know. Any direction appreciated! Thanks! TypeError Traceback (most recent call last) <ipython-input-3-88cc332f436e> in <module> ----> 1 a = User(name='Alex Honing', state='Alberta') /usr/local/anaconda3/envs/pyfinance/lib/python3.9/site-packages/django/db/models/base.py in __init__(self, *args, **kwargs) 501 pass 502 for kwarg in kwargs: --> 503 raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) 504 super().__init__() 505 post_init.send(sender=cls, instance=self) TypeError: User() got an unexpected keyword argument 'name' In [4]: a = User(name = 'Alex', state ='Alberta') -
Passing both user ID and product ID to Paypal Button
I am using @paypal/react-paypal-js to display the PayPal button and create an order. I am specifically interested in processing credit card payments. Once my Django backend receives the payment capture completion event from PayPal, it needs to store information about a particular user owning a particular product. Hence, the notification has to contain both the user ID (i.e. email) and the product ID. This is how I am trying to pass these two pieces of information in my frontend: createOrder={(data, actions) => { return actions.order.create({ purchase_units: [ { amount: { value: course.price, currency_code: course.currency, }, custom_id: course.title, }, ], payer: { email_address: userEmail, } }); }} The user email address is automatically filled into the form. However, the webhook_event event in the server does not contain this information. That is, there is no payer field inside resource in webhook_event. How can I pass the two pieces of information so as to get them in webhook_event? (I would like to avoid the ugly solution of concatenating both pieces into custom_id) -
Switching from NoSQL to SQL land in django
I am porting my Mongo-Express app to Postgres-Django. The app includes a simple form for collecting a student's information and the books they have read over the summer. The express API writes the payload to MongoDB. The payload looks like below: { student_id: 123, student_name: 'James Hook', books: [ { book: 'War and Peace', author: 'Leo Tolstoy' }, { book: 'Harry Potter', author: 'JK Rowling' } ] } Mongo is a document-based database so I could store the above payload as-is. Now moving to django-postgres, I have to define models and I can see two options: A. Just create one model with three fields - student_id (IntegerField), student_name (CharField), and books (ArrayField(JSONField)) B. Go full RDBMS and create two models - student and books. Student and book have many-many relationship. Give this, I have a few questions: Q1. If I don't need to index on books, does option A make more sense? Q2. In option A, should it be just JSONField or ArrayField(JSONField)? Q3. In option B, how do we write TWO or more books for one student at a time? Do I need an ArrayFiled there? How does the model would look like and does it violate atomicity constraint … -
Heroku try to deploy python website ,,manage.py collestatic --noninput"
I create a website using Python ,JS, React, Django .When I deployed on Heroku via github, an error occur: -----> Determining which buildpack to use for this app ! Warning: Multiple default buildpacks reported the ability to handle this app. The first buildpack in the list below will be used. Detected buildpacks: Python,Node.js See https://devcenter.heroku.com/articles/buildpacks#buildpack-detect-order -----> Python app detected -----> Using Python version specified in Pipfile.lock cp: cannot stat '/tmp/build_02d1f320/requirements.txt': No such file or directory -----> Installing python-3.9.7 -----> Installing pip 20.2.4, setuptools 57.5.0 and wheel 0.37.0 -----> Installing dependencies with Pipenv 2020.11.15 Installing dependencies from Pipfile.lock (dee4f1)... -----> Installing SQLite3 -----> $ python leadmanager/manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_02d1f320/leadmanager/manage.py", line 22, in <module> main() File "/tmp/build_02d1f320/leadmanager/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 318, in … -
(NOT NULL constraint failed:owner_id)
I make migrations and run migrate. Then, I submit the form for registration but I get NOT NULL constraint. Below is my models: models.py class A(models.Model): u = models.OneToOneField(User, on_delete=models.CASCADE) num = models.IntegerField() class B(models.Model): x = models.ForeignKey(u, on_delete=models.CASCADE) y = models.CharField(max_length = charLen100) forms.py class AForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(), required=True), first_name = forms.CharField(max_length=charLen100, widget = forms.TextInput(attrs= {'placeholder': 'First Name'})) last_name = forms.CharField(max_length=charLen100, widget=forms.TextInput(attrs= {'placeholder': 'Last Name'})) num_items = forms.CharField(label="How many items do you own?", widget=forms.Select(choices=ITEM_NUMBER_CHOICES)) class Meta: model = A fields = ('username', 'email', 'password','first_name', 'last_name') class BForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':name'})) class Meta: model = B fields = ('name') views.py def register(request): registered = False if request.method == 'POST': user_form = AForm(request.POST) profile_form = BForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileForm() context_dict = {} context_dict['user_form'] = user_form context_dict['profile_form'] = profile_form context_dict['registered'] = registered return render(request, ..., context=context_dict) so, what I am doing is that I have two tables in database A and B and A can have many B's that is B then holds A as a foreign key. Then, … -
Django migration: django.db.utils.OperationalError: (1824, "Failed to open the referenced table 'classroom_user'")
I am trying to deploy a Django app from a development server to a production server I have set up a virtualenv with python 3.8.10, created the mysql database, I am running in the virtualenv. I get no errors from python manage.py check, get "no changes detected" when running python manage.py makemigrations, but when I run ```python manage.py migrate`` I get the following: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying admin.0001_initial...Traceback (most recent call last):... final line of the traceback: Django.db.utils.OperationalError: (1824, "Failed to open the referenced table 'classroom_user'") ("classroom" is the name of the app within the project "codex") I just recently rebuilt all of the tables in this database on my development server with no issues. The database on the production server is empty. models.py is in place and complete. I have tried it both with an empty migrations folder and the migration folder removed. The migration does create django_admin_log, django_content_types, django_migrations, but no other tables. All of the other posts I have seen on this have been about have foreign key constraints, but in my models.py all of the tables that have foreign keys are specified after the … -
cant upload multiple images djago - ajax
I'm trying to upload multiple images with ajax request, i'm using modelformset_factory to upload several images , here is my code : class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my forms.py class UploadDocumentsForm(forms.ModelForm): class Meta: model = Document fields = ['docs'] my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.is_ajax() and request.method == 'POST': images = UploadDocumentFormSet(request.POST,request.FILES) if images.is_valid(): for img in images: if img.is_valid() and img.cleaned_data !={}: img_post = img.save(commit=False) img_post.booking = obj img_post.save() return JsonResponse({'success':'success'}) else: messages.error(request,_('error message')) images = UploadDocumentFormSet(queryset=Document.objects.none()) return render(request,'booking/add_img.html',{'obj':obj,'images':images}) and here is my template includes html and ajax $('#addButton').click(function() { var form_dex1 = $('#id_form-TOTAL_FORMS').val(); $('#images').append($('#formset').html().replace(/__prefix__/g,form_dex1)); $('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1); }); const formData = new FormData() formData.append('csrf',document.getElementsByName('csrfmiddlewaretoken').value); formData.append('docs0',document.getElementById('id_form-0-docs').files[0]); formData.append('docs1',document.getElementById('id_form-1-docs').files[0]); formData.append('docs2',document.getElementById('id_form-2-docs').files[0]); formData.append('docs3',document.getElementById('id_form-3-docs').files[0]); const form = document.getElementById('docs-uploader-form') form.addEventListener("submit",submitHanler); function submitHanler(e){ e.preventDefault(); $.ajax({ type:'POST', url:"{% url 'booking:add_new_image' id=2222 %}".replace(/2222/,parseInt({{obj.id}})), data:formData, dataType:'json', success:successFunction, }) } function successFunction(data){ // console.log(data) form.reset(); alertify.success('added new image') } <button id="addButton" class="px-4 py-1 pb-2 text-white focus:outline-none header rounded-xl"> {% trans "add new image" %} </button> <form action="" method="POST" enctype="multipart/form-data" dir="ltr" id="docs-uploader-form">{% csrf_token %} {% for form in images.forms %} {{form.id}} {{images.management_form}} <div class="form-group mt-3" id="images"> {{ form.docs | add_class:'form-control-file' }} </div> {% endfor %} <div class="form-group mt-3" id="formset" style="display: none;"> {{ images.empty_form.docs | add_class:'form-control-file' … -
Django bootstrap collapse isnt working well
i am trying to make a nav bar collapse when a browser window reaches a minimum size it does collapse the right part of the navbar but the button doesnt show a list of the collapsed items which are register and login i am using django latest version with bootstrap3 <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"></button> <a class="navbar-brand" href="{% url 'blogs:Home' %}">MyBlog</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'blogs:blogs' %}">blogs page</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li> <a>hello , {{ user.username }}</a> </li> <li> <a href="{% url 'users:logout' %}">logout</a> </li> {% else %} <li><a href="{% url 'users:register' %}">Register</a></li> <li><a href="{% url 'users:login' %}">Login</a></li> {% endif %} </ul> </div><!--navbar collapse--> </div> </nav> -
How to customize/styling forms using class based views
Is it possible to customize the HTML attributes of the form created by class base views? At this moment, I'm using a generic CreateView: class SlipCreateView(LoginRequiredMixin, CreateView): model = Atum fields = ['atum1', 'atum2', 'atum3', 'atum4', 'atum5', 'atum6', 'atum7'] I want to change, for example, the length and position of the input fields, the color, and others attributes. Is this possible? And if yes, how? Thank you advance. -
Django, Vue and WebSocket - getting client side to work
There was a similar question on SO about this some time ago, though I tried the answers and they did not work. I am implementing a SPA using Django backend and Vue front end with Vue cli. Django is using channels to send JSON via a WebSocket to the frontend, the frontend receives this data and is supposed to update a table. The Django part is working. A connection to the WebSocket is confirmed and data is received in Vue, though I have two problems that I have not been able to find a way to solve: The data, while in a variable, is not being shown on the table and The front end only receives the data once - I don't know how to apply a listener to the WebSocket, or in which part of my Vue app, so that new payloads (I hope I am saying that correctly) are received and updated accordingly. Below I have provided the Django consumers.py file, the Signals.vue view file, and the console.log output showing that the variable does contain the JSON object despite the table remaining blank. Does anyone have an idea of where I am going wrong and how I can … -
Django Model Constraint Condition With Field From Inherited Class - Is It Possible?
I'd like to use a field from a parent class as a constraint condition in a child class. models.py class ParentClass(object): ... is_public = models.BooleanField(default=False) class ChildClass(ParentClass): ... price = models.DecimalField(max_digits=6, decimal_places=2, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['price', 'is_public'], name='null_price'), models.CheckConstraint( check=Q(price__isnull=True) & Q(is_public=True), name='price_exists_check', ) ] When I attempt to migrate, I see this error in my terminal: myapp.ChildClass: (models.E016) 'constraints' refers to field 'is_public' which is not local to model 'ChildClass'. HINT: This issue may be caused by multi-table inheritance. It's obvious why I am seeing this error (is_public field lives in ParentClass). My question is, is it simply not possible then, or can I refactor something? What is my end-goal? To not let an instance of ChildClass is_pulic change to True if the price is null. I'd like to enforce this at the database level. Is there a way and if so, what needs to change? -
Scoped Styling in Django
My base.html ... <body> {% include 'parts/navbar.html' %} <div>This is the base content html file</div> {% block content %} {% endblock %} {% include 'parts/footer.html' %} </body> ... my navbar: <div>NAV</div> my footer: <div>Footer</div> <style> div { color: blueviolet; } </style> The footer style applies also to the nav-div which i don't want. Is scoped styling in Django possible or do i have to use line-styles or some engine etc. -
Try to host a website usigh Python and Django
I create a website using Django , Python ,Redux .This website I wanna to host on a domain that I bought for this project.Now , I am kinda new and I do not understand why I ca not upload the files for this website via my host provider. I understand that I am rlly dump , but I wanna to understand why and how to host this website.In localhost:800 all work great. Code for this website:enter link description here (repository on github) -
Django creates an extra unwanted entry in many-2-many intermediate table
I have a many-2-many relationship between Flight and Passenger. When I try to assign a passenger to a flight object, Django seems to add an extra entry to the intermediate table. Here are the models: class Passenger(models.Model): name = models.CharField(max_length=30) age = models.IntegerField() class Flight(models.Model): time = models.DateTimeField('flight time') destination = models.CharField(max_length=20) passengers = models.ManyToManyField( to=Passenger, symmetrical=True, related_name='flights', blank=True, ) Say the intermediate table looks like this, with passenger Say flight_object is a Flight with ID=1, and passenger_object is a Passenger with ID=2, when I run flight_object.passengers.add(passenger_object) Django adds 2 entries to the intermediate table in the database. The table now looks like this: Both entries with ID=1 and 2 should be there, but 3 is incorrect, and the flight_id foreign key is for a completely different flight! -
Why does stunnel keep throwing "Address already in use (48)"?
I am working in implementing Auth0 in a Django project, using stunnel to create the https connection. I followed this instruction This is my dev_https file: pid= cert = stunnel/stunnel.pem foreground = yes output = stunnel.log [https] accept=8080 connect=8000 TIMEOUTclose=1 However, when want to start the server, using this command: stunnel stunnel/dev_https & python3 manage.py runserver& I get the following: [.] Configuration successful [ ] Deallocating deployed section defaults [ ] Binding service [https] [ ] Listening file descriptor created (FD=9) [ ] Setting accept socket options (FD=9) [ ] Option SO_REUSEADDR set on accept socket [.] Binding service [https] to :::8080: Address already in use (48) [ ] Listening file descriptor created (FD=9) [ ] Setting accept socket options (FD=9) [ ] Option SO_REUSEADDR set on accept socket [.] Binding service [https] to 0.0.0.0:8080: Address already in use (48) [!] Binding service [https] failed I tried changing the accept port from 8443 to 8080. Same result I then checked for active processes on the port with lsof -i 8080 This reveals that stunnel is already running on the port. I killed that process and tried again, but I get the same error. Specific questions Can someone briefly explain how … -
How do I set a NOT NULL constraint on Django charfield?
I'm struggling with how I can set a NOT NULL constraint on a charfield. Currently, my model looks like this: class Tutors(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20, blank=False) email = models.EmailField(max_length=254) birth_day = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return(self.first_name + ' ' + self.last_name) I want to make sure that last_name and first_name can't be saved to the database as NOT NULL. Docs are confusing me a bit lol -
Django Databases - Can you use Postgresql for the Django tables, but have the meat of the data on MSSQL?
I have a scenario where I have full access to CRUD operations on a Database, but cannot create tables, etc., or justify requesting tables to be created. Is it possible to have all the meta tables (auth_*, user_*, django_* tables) hosted local to the app server, and keep the working data in the MSSQL database? I know I could create models to match the MSSQL tables, and copy the data over regularly, but this doesn't seem like a great idea. I'm also aware that there is mixed feelings online about the django-mssql plugin and its abilities. So this adds extra confusion to the problem for me. -
En un modelo DJANGO estoy usando la herramienta FilterView, al momento de visualizar el filtro no me aparece el form clase META
Modelo python donde se define los campos de la tabla from django.db import models # Create your models here. class Integrantes(models.Model): nombre = models.CharField(max_length=50) apellido = models.CharField(max_length=30) codigo = models.CharField(max_length=20) cargo = models.CharField(max_length=20) Filter.py - aqui defino que filtro aplicaré from django.contrib.auth.models import User import django_filters from apps.integrantes.models import Integrantes class integrantesFilter(django_filters.FilterSet): class Meta: model = Integrantes fields = ['nombre'] La vista del Filtro - Uso la herramienta FilterView from django.shortcuts import render, redirect from django.http import HttpResponse, request from django.urls import reverse_lazy from django.views.generic import ListView, CreateView, UpdateView, DeleteView from django_filters.views import FilterView from apps.integrantes.forms import IntegrantesForm from apps.integrantes.models import Integrantes from apps.integrantes.filters import integrantesFilter # Create your views here. class IntegrantesList(ListView): model = Integrantes template_name = 'integrantes/integrantes_list.html' paginate_by = 10 class Integrantes1List(FilterView): model = Integrantes template_name = 'integrantes/integrantes_list.html' filter_class = integrantesFilter paginate_by = 10 Template HTML -> la visualización, sin enmargo, me aparecen todos los campos del modelo INTEGRANTES y solo necesito filtrar por 'nombre' {% extends 'base/base.html' %} {% block title %} ADM RTN {% endblock %} {% block header %} {% endblock %} {% block content %} <form action= "" method="get"> {{ filter.form.as_p }} <input type="submit"/> </form> <table class="table table-bordered"> <thead> <tr> <td>#</td> <td>NOMBRES</td> <td>APELLIDOS</td> <td>CODIGO</td> … -
Is the a way to pass data from an inline formset's clean method to the parent's model admin's clean method in Django?
I have models Product and ProductVariant where on the admin site, the ProductVariant (child) is an inline within the Product (parent). I have overriden the ProductVariant's clean() method to do some validation and creation of stuff like SKU etc. Now I would like to also override the Product's clean() method to do some validations but for one of the validations, I would like to use data (cleaned_data) I have obtained from the ProductVariant's clean() method. So my question is, is there a way that I can pass something I've obtained from the cleaned_data in an inline to the clean() method of the inline's parent. I have added a bit of my code below for reference. It may look a bit more complex than the question I've asked above because I'm using nested inlines and whatnot, but I'm sure the answer will apply in both cases. Thank you in advance. # File: models.py class Product(models.Model): name = models.CharField(max_length=100, unique=True) slug = AutoSlugField(populate_from='name', slugify_function=autoslug_slugify, unique=True) option_types = models.ManyToManyField(OptionType, blank=True) class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) option_values = models.ManyToManyField(OptionValue, blank=True) # File: admin.py # ==================== # ProductVariant Admin # ==================== class OptionValueInlineFormSet(BaseInlineFormSet): def clean(): # Generate SKU using option_values. Opted for this because …