Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF_TRUSTED_ORIGINS works only with a string, not with a list as expected
Context I am running a Netbox instance, which uses Django. Inside of its parameters, I have to set CSRF_TRUSTED_ORIGINS to the origins I trust for Netbox to work properly. The Netbox instance I use runs inside a Docker container (netbox-docker). Issue I have found out that if I write these as a list, like expected in the documentation (see here), I get a 403 error with the following description: CSRF verification failed. Request aborted. Activating debug mode also tells me this: Origin checking failed - https://myurl does not match any trusted origins., which I do not understand because my variable looks like this: CSRF_TRUSTED_ORIGINS=['https://172.23.0.5', 'https://myurl']. Temporary workaround If I set the variable as a simple string, I do not get any error: CSRF_TRUSTED_ORIGINS="https://myurl" works flawlessly for myurl (of course, it still blocks all the other URLs). Issue (still) That worked for some time, but now I have to add a second domain name referencing my Netbox instance, so I would need to add "https://myurl2" to the trusted origins list. Since having a list does not work here, I do not really know how to proceed. What I have tried I have tried to change the way I assign its value … -
How to send mail to admin from individual mail I'd in Django?
I'm Working on Employee Management System Project, There is three type of user HR, Director and Employee. I want to send record mail to Director mail I'd from Employees individual email ID. How I can implement this feature, I'm working in Django. I'm trying to implement using Django send_mail() function but there is password providing issue, we can't provide email password for all employees. I want to know how i can implement. -
Form type request in Postman for API with nested serializers in Django Rest Framework
I need to pass the nested dictionary which is the mixture of text and file. I created the nested serializer to get the data from API request. What will be my request like in Postman? Request Structure: { "type":"Large", "category":[ { "category_segment":"A", "category_features":["name", "size", "color"], "action":["pack", "store", "dispatch"], "category_image": **''' Category A Image File Here'''** }, { "category_segment":"B", "category_features":["name", "size", "color"], "action":["pack", "store", "dispatch"], "category_image":**'''Category B Image File Here'''** } ] } Serializer class DataSerializer(serializers.Serializer): category_segment = serializers.CharField() category_features = serializers.ListField(child=serializers.CharField(default='Not Required'),default='Not Required') action = serializers.ListField(child=serializers.CharField()) image = serializers.FileField() class ExtractionSerializer(serializers.Serializer): type = serializers.CharField() category_image = serializers.ListField(child = DataSerializer()) -
Django - How to test an application with millions of users
I want to test a blog application with millions of users particularly where each posts have number of views that is visited by users. Although I tried to login with different browser for each users,its not efficient. How should I test users to login and try this application? Requirements Counts must be real time or near-real time. No daily or hourly aggregates. Each user must only be counted once. The displayed count must be within a few percentage points of the actual tally. The system must be able to run at production scale and process events within a few seconds of their occurrence. Although I tried to login with different browser for each users,its not efficient. -
Passing kwargs into FactoryBoy nested RelatedFactories for pytest
I see so many different ways of doing this that I'm getting a bit of choice paralysis. Problem description I have a top-level FactoryBoy factory, FruitBasketFactory. This defines a RelatedFactory to AppleFactory, a sort of "conduit" factory: AppleFactory defines 2 RelatedFactories: SeedFactory and SkinFactory. Some pseudo code: class FruitBasketFactory(factory.django.DjangoModelFactory): class Meta: model = FruitBasket apple = factory.RelatedFactory( AppleFactory, factory_related_name="fruit_basket" ) class AppleFactory(factory.django.DjangoModelFactory): class Meta: model = Apple fruit_basket = None seed = factory.RelatedFactory( SeedFactory, factory_related_name="apple" ) skin = factory.RelatedFactory( SkinFactory, factory_related_name="apple" ) class SeedFactory(factory.django.DjangoModelFactory): class Meta: model = Seed apple = None num_seeds = 10 seed_color = "black" class SkinFactory(factory.django.DjangoModelFactory): class Meta: model = Skin apple = None skin_color="red" My goal For my tests, I want to set a top-level flag e.g. fruit_basket_factory(apple_type_is_PinkLady=True), and 'pass down state' to all related, dependent factories. In this case, the changes required would be setting: fruit_basket.apple.seed.num_seeds = 5 fruit_basket.apple.seed.seed_color = "brown" fruit_basket.apple.skin.skin_color= "green" Is this possible? I'm imagining some sort of Class Params on each Factory that serve as 'message-passers'? In reality, my conduit factory has around 5-10 RelatedFactories. -
Forbidden (CSRF cookie not set.):- Nodejs 13 with Django
I am trying to send an HTTP POST request from my frontend in Node.js 13 to my Django backend, but I keep getting the error "Forbidden (CSRF cookie not set)." Currently, the application is configured to send an API request to my server to obtain the csrf_token when I open the website. Then, I attempted to send an API request to register with the csrf_token, but encountered the aforementioned error. const respond = await fetch( 'http://127.0.0.1:8000/register/register_user/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken, }, body: JSON.stringify({ name: name, email: email, password: password, passport: passport, trustNode: trustNode, }), cache: 'no-cache', } ); This is my Django settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website_backend', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', 'http://127.0.0.1:8000' ] -
Django model clean function validation error problem
I have a Django model with custom clean function as below: class License(models.Modes): # fields of the model def clean(self): if condition1: raise ValidationError('Please correct the error!') The problem is that, my admin user uploads some file as needed by FileField of License Model, but when I raise the ValidationError file fields are emptied and user is forced to upload the files again. Is it possible to raise the error, but keep the files? -
django primary key auto assigning available id from least value
In django project primary key are assigned automatically. In my model I have some model object with id (=5,6). id (= 1,2,3,4,) is deleted from the DB. Now when I create new object model,django assigning id with the value 7. But I want this to assign in a order like 1,2,3,4 and 7 and so. How can I implement this? I've tried to create a complete different id field with custom logic to assign the available id first,but I was expecting a django built-in function. -
'dict' object has no attribute 'headers': it is coming from clickjacking.py
I have a method that generates pdf cheque for a client. the code as follows @csrf_exempt def generate_pdf(request): body = ujson.loads(request.body) monitoring = Monitoring.objects.filter(tr_id=body['tr_id']).first() if not monitoring: return { "message": MESSAGE['NotDataTrID'] } data = { 'headers': ["Abdulloh",], 'user': monitoring.user, 'tr_id': monitoring.tr_id, 't_id': monitoring.t_id, 'type': monitoring.type, 'pay_type': monitoring.pay_type, 'sender_token': monitoring.sender_token, } pdf = render_to_pdf('pdf_template.html', data) return HttpResponse(pdf, content_type='application/pdf') it should generate a cheqeu in the end. But I am receiving an error from python env it is coming from clickjacking.py. Can anyne help. I am using python 3.9 and centos 7 for operation system -
How do I run 2 processes in the return of a Django view?
I have a django site - does stuff.. when the print button is pressed I need it to run a def() and then return to home return view_xlsx(request, xlspath) return render(request, 'webpage/HomePage.html', {'last_update': lastupdted}) How can I do both Run the view_xlsx ( which downloads in browser) and then return home? I have tried return view_xlsx(request, xlspath), render(request, 'webpage/HomePage.html', {'last_update': lastupdted}) and try: return view_xlsx(request, xlspath) finally: return render(request, 'website/HomePage.html', {'last_update': lastupdted}) They both work independently of each other, but wont seem to work together. Thoughts ? -
Trying to install postgres within docker container and containerizing django project
I am new to docker and web-development generally. When trying to containerize my django-project I run into an error and can't solve it for several days. The error might be silly, but I can't find a solution. I'll be very glad if someone helps me to solve me the problem. Thank you in advance. As operational system I use Ubuntu 22.04 Here is the output after commands docker compose build and docker compose up: [+] Running 2/0 ⠿ Container test_task-db_task-1 Created 0.0s ⠿ Container test_task_container Created 0.0s Attaching to test_task-db_task-1, test_task_container test_task-db_task-1 | test_task-db_task-1 | PostgreSQL Database directory appears to contain a database; Skipping initialization test_task-db_task-1 | test_task-db_task-1 | 2023-06-07 10:46:07.124 UTC [1] LOG: starting PostgreSQL 14.1 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.3.1_git20211027) 10.3.1 20211027, 64-bit test_task-db_task-1 | 2023-06-07 10:46:07.125 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 test_task-db_task-1 | 2023-06-07 10:46:07.125 UTC [1] LOG: listening on IPv6 address "::", port 5432 test_task-db_task-1 | 2023-06-07 10:46:07.147 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" test_task-db_task-1 | 2023-06-07 10:46:07.163 UTC [21] LOG: database system was shut down at 2023-06-07 10:45:29 UTC test_task-db_task-1 | 2023-06-07 10:46:07.218 UTC [1] LOG: database system is ready to accept connections test_task_container | Watching … -
Multiple form view, in which JSON fed to one form, constitutes another in Class Based Views
I want to create a class based view in Django that after receiving one form, will translate it to another and then accept the second form (both forms accept files - the first just one, the other several). I have tried the approach with MultiFormsView (you can check the question here): Cannot proceed with multiform view in class based views And then I moved a bit further with Tarquiniuses help with another method: I cannot pass the values between the methods in classBasedView Now the code looks like this: Django: @user_authenticated @user_hkm @translation def firmware_cbv2(request): class Firmware_view(FormView): template_name = "dev_tools/firmware_cbv2.html" form_class = forms.InitialFirmwareForm2 def get_success_url(self): return self.request.path def form_invalid(self, form): print("the form is invalid") return super().form_invalid(form) def get_context_data(self, message=None, bundle=None,**kwargs): context = super().get_context_data(**kwargs) context['bundle'] = bundle context['message'] = message return context def form_valid(self, form): bundle, message = {}, {} if request.FILES: if len(request.FILES) < 2 and "file" in request.FILES: file = request.FILES["file"] try: content = json.loads(file.read().decode('utf-8')) folder_name = utils.format_folder_name(content["title"]) units = [] for unit in content["units"]: units.append(unit) bundle["units"] = units bundle["file"] = { "name": folder_name, "content": json.dumps(content) } message.update({ "type": "info", "content": "The form was parsed successfully" }) except Exception as e: print("there was an error", e) else: print("I am … -
Tagged Posts not Paginating
I have a Django app that displays posts that are created using Django's built-in admin interface. The posts have tags incorporated using django-taggit (https://django-taggit.readthedocs.io/en/latest/) The main page (home.html) is set up to display posts and tags and when a tag is clicked, it takes you to a page (tag_posts.html) with all tagged posts e.g. If i click on a post with the tag 'apple', I am presented with a page that shows all posts tagged with 'apple'. The main page works as intended, as does the pagination for home.html. THE ISSUE: When viewing the list of tagged posts, it is showing the number of posts by the number specifed with paginate_by (in the code it's 2) but not showing me the option to click next/previous or page numbers. What I Have Attempted: I thought it may be the Bootstrap navigation links in the html file but I am using the same as in my home.html, which works. re-factored my class-based view to include the tag as part of the context and supplying to the html as a context variable Used basic html for navigation links The issue lies with TagPostsView Here is my view.py: from django.shortcuts import get_object_or_404, render from … -
what is more often used in practice: FBV or CBV?
I'm new to Django development, so I want to ask people who have more practice - what do they use more often? I'm of course assuming it's CBV since it's easier for others to read, but I'll ask anyway. thanks in advance for your reply -
Django - generate product page with one url and view function?
I have a list of products with product ids. How do i create the function to open the page based on the product_id and user_id? Currently I have in urls.py: path('product/<int:product_id>/', views.product, name='product'), And in my views.py: @login_required() def product(request, product_id, user_id=None): return render(request, 'users/product.html') I am new to Django and could not find an answer searching online... -
Fulltext Search in Django with Haystack/Whoosh - Displaying Search results with tags from models not in results
swarm intelligence, right now i try to implement a database fulltext-search in a Django-project with haystack and whoosh in the backend. Installation, configuration and indexing ist done. Search works as intended. So NOW I'm talking about displaying search results: "side" problem: Results seem to be not sorted. I would like to know, WHERE in the different code-tables from Django (views/forms/serach-index/urls.py) i can set a configuration for the result-ordering? Reason for Question is furthermore: When I am trying to set up the template for displaying the results, it is no problem to use a {{ result.object.last_name }} tag when result is from model, where "last_name" is included.... But if i get results from a child table, what do i have to do to display "last_name" from parent table, too? My search-indexes.py: from haystack import indexes from employees.models import Employees, Employments, Professions, ForeignMissions, \ LanguageAbilities, SecondDegrees, MilCourseDetails, CivCourseDetails class EmployeesIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) id = indexes.IntegerField(model_attr='id') titel_rank = indexes.CharField(model_attr='title_rank', null=True) rank_short = indexes.CharField(model_attr='rank_short', null=True) last_name = indexes.EdgeNgramField(model_attr='last_name') first_name = indexes.CharField(model_attr='first_name') prefix_title = indexes.CharField(model_attr='prefix_title', null=True) suffix_title = indexes.CharField(model_attr='suffix_title', null=True) street = indexes.CharField(model_attr='street') building_number = indexes.CharField(model_attr='building_number') postal_code = indexes.CharField(model_attr='postal_code') city = indexes.CharField(model_attr='city') country = indexes.CharField(model_attr='country') employee_number = indexes.CharField(model_attr='employee_number') key_number = indexes.CharField(model_attr='key_number', null=True) … -
Django RESTAPI how to make calculation APIs PUT or POST?
Hi I'm trying to make calculation rest api using django. My objective is to save preprocessed_data(result) into the db table field The process is read raw data path(txt file) from db and calculate using pandas & numpy after that make result txt file save to db preprocessed_data field. this is my models.py class PreprocessData(models.Model): raw = models.FileField( upload_to=_user_directory_path, storage=OverwriteStorage(), preprocessed_data = models.CharField( max_length=200, null=True, blank=True, ) ) and views.py class PreprocessCalculate(APIView): def _get_object(self, pk): try: data = PreprocessData.objects.get(id=pk) return data except PreprocessData.DoesNotExist: raise NotFound #get or put or post which is the best design for api? # PUT API def put(self, request, pk): data = self._get_object(pk) serializer = PreprocessCalculateSerializer(data, request.data, partial=True) if serializer.is_valid(): updated_serializer = serializer.save() return Response(PreprocessDataSerializer(updated_serializer).data) else: return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) and serializers.py class PreprocessResultField(serializers.CharField): def to_representation(self, value) -> str: ret = {"result": value.test_func()} return ret def to_internal_value(self, data): return data["result"] class PreprocessCalculateSerializer(serializers.ModelSerializer): preprocessed_data = PreprocessResultField() class Meta: model = PreprocessData fields = ("uuid", "preprocessed_data") my question is when I use the above code. In db "preprocessed_field" is still null... what is the problem in custom field serializer? I choose "PUT" method to calculate raw file, but I think if I use "PUT" it has a problem to change … -
Override the django save and update function. both are working fine but for update function it is entering in a infinite loop
Override the django save and update function. both are working fine but for update function it is entering in a infinite loop class PrimitiveQuerySet(QuerySet): def update(self, *args, **kwargs): super().update(*args, **kwargs) super().using('New').update(*args, **kwargs) class Primitive(models.Model): modified_by = models.CharField(max_length=200, null=True) modified_on = models.DateTimeField(null=True) deleted_by = models.CharField(max_length=200, null=True) deleted_on = models.DateTimeField(null=True) deleted_flag = models.BooleanField(null=True, blank=True, default=False) objects = PrimitiveQuerySet.as_manager() def save(self, *args, **kwargs): # Dump data into default database super().save(*args, **kwargs) # Save the same data to the new database using_db = kwargs.pop('using', None) # Extract 'using' parameter self._state.db = using_db # Set the target database for saving self.save_base(using='New', force_insert=False, force_update=False ` I got the approach how to update and save data in two db but issue is it is going into infinite loop -
Django Chatterbot-how to add "default-response" to settings .py?
In my "django" application in settings.py I have: CHATTERBOT = { 'name': 'bot1', 'storage_adapter': "chatterbot.storage.SQLStorageAdapter", 'logic_adapters': [ 'chatterbot.logic.BestMatch', ] } How do I add the auto default response parameter? I tried countless ways but it doesn't work. -
Django on Android pydroid3.Python and Django are fully functional. But when I try to run Django admin site on Chrome it shows "Server error occured"
This is what am facing with with Django on my Android I'm using Pydroid on my phone. Python and Django are fully functional. But when I try to run Django admin site on Chrome it shows "Server error occurred. Contact administrator" System check identified no issues (0 silenced). April 28, 2022 - 16:28:28 Django version 4.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C. [28/Apr/2022 16:28:45] "GET /admin/ HTTP/1.1" 302 0 [28/Apr/2022 16:28:55] "GET /admin/ HTTP/1.1" 302 0 Traceback (most recent call last): File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/zoneinfo/_common.py", line 12, in load_tzdata return importlib.resources.open_binary(package_name, resource_name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 88, in open_binary package = _get_package(package) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 49, in _get_package module = _resolve(package) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 40, in _resolve return import_module(name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 972, in _find_and_load_unlocked File "", line 228, in _call_with_frames_removed File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 972, in _find_and_load_unlocked File "", line 228, in _call_with_frames_removed File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 984, in _find_and_load_unlocked ModuleNotFoundError: No … -
How to create three dependent drapdowns in Django, that the second is dependent on the first, and the third is dependent on the first and the second?
In this program, the first drapdown is a field named education level, which is independent. Then there is a drapdown named field of study, which is related to the level of study. Then it has a drapdown called book, which is related to the first and second drapdown, which means the level of study and field of study. It is expected that after selecting a education level and field of study, the book drapdown will bring only the list of books that are related to this degree and field of study. -
Shopify embedded app "frame-ancestors 'none'" error
I am having some issues with my embedded app. I checked the app in incognito mode (chrome) and found that it is not loading any page. I have configured CSP headers on my django backend with django-csp with middleware (adding screenshot of the API call from XHR section from network tab. Tech Stack Frontend: React Backend: Django Inspection console prints this error: Refused to frame '' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'none'". I am not able to figure out the issue. I can provide more info if needed. class CSPMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # Check if the request URL matches the desired prefix if request.path.startswith('/endpoint'): # Apply the CSP header for the desired URL prefix response['Content-Security-Policy'] = "frame-ancestors https://shopify-dev.myshopify.com https://admin.shopify.com;" return response -
ValueError: No route found for path 'admin/'
I'm running a Django server and encountering an error when trying to access all backend URLs. The specific error messages I'm receiving are: Exception inside application: No route found for path 'admin/'. Traceback (most recent call last): File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/routing.py", line 165, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'admin/'. HTTP GET /admin/ 500 [1.00, 127.0.0.1:54986] Exception inside application: No route found for path 'favicon.ico'. Traceback (most recent call last): File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/routing.py", line 165, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'favicon.ico'. HTTP GET /favicon.ico 500 [0.84, 127.0.0.1:54986] I have a routing.py file where I define the routes for WebSocket consumers. Here's the content of that file: from django.urls import path from channels.routing import URLRouter from WS.consumers import ( CodeConsumer, WhiteboardConsumer, ChatConsumer, ) ws_application = URLRouter( [ path("ws/code/", CodeConsumer.as_asgi()), path("ws/whiteboard/", WhiteboardConsumer.as_asgi()), path("ws/chat/", ChatConsumer.as_asgi()), ] ) And here's my asgi.py file: import os from django.core.asgi import get_asgi_application from channels import URLRouter, ProtocolTypeRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack … -
Using serializer with foreign key model when creating new entry
At first, I had this serializer and it works well for GET and POST(create new entry) class DrawingSerializer(ModelSerializer): drawing = serializers.FileField() detail = serializers.JSONField() class Meta: model = m.Drawing fields = ('id','detail','drawing','user','created_at','updated_at') in viewset where creating entry. class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer def create(self, request, *args, **kwargs): request.data['user'] = request.user.id #set userid serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) # it makes the new entry with user return Response(serializer.data) and models.py class CustomUser(AbstractUser): detail = models.JSONField(default=dict,null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Drawing(models.Model): drawing = f.FileField(upload_to='uploads/') detail = models.JSONField(default=dict) user = models.ForeignKey(CustomUser,on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) In this casel, user is foreign key model. So I want to get the user's name,email and so on, then I changed Serializer like this. class DrawingSerializer(ModelSerializer): drawing = serializers.FileField() detail = serializers.JSONField() user = CustomUserSerializer(read_only=True) # change here class Meta: model = m.Drawing fields = ('id','detail','drawing','user','created_at','updated_at') It also works well for get. I can get the data from CustomUser Model as user. however when POST(creating), it shows the error django.db.utils.IntegrityError: (1048, "Column 'user_id' cannot be null") Why does this happen and what is the user_id? -
inline many to many field inside django admin
I have a model that has a many-to-many relationship with another model. I want to have the options inline in my question model in my Django admin. That is, stacked inline is not enough for me, because I want to be able to edit all the option fields there, not just a box to add in a more beautiful way. class Option(models.Model): ... class Question(models.Model): options = models.ManyToManyField(Option) i use TabularInline and StackerInline but not enough for me. Also, I used the Django-nested-inline package, but to implement it, it is necessary to have a foreign key relationship from the options to the questions, and I don't want it to be like that.