Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I connect my model to an external app?
I've installed a new app thorough pip (it's called django-sitetree). I want to know if I can connect my models (like Category model) to this app with Foreignkey our something else? -
How can I check whether a person is included in a model to make a Job/Post
I have created a School System-like system, that creates a job and sends them to employees/users. I'm almost done making this system however I can't seem to know what do to check if the user is included in the manager model that I created to create a job.. Also, how can a user just see all their job that was assigned to them. All I know is to use objects.allbut that might only seem to show all of the jobs that was posted, I just want the user to see the job included to them. Here is my model.py: from django.db import models from profiles.models import User # Create your models here. class Points (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0, null=False) def __str__(self): return self.user.username class Profile (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png',upload_to='profile_pics') def __str__(self): return f'{self.user.username}Profile' class Manager (models.Model): name = models.CharField(max_length=30, blank=True, null=True) manager = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name class Member (models.Model): name = models.CharField(max_length=30, blank=True, null=True) manager = models.ForeignKey(Manager, on_delete=models.CASCADE) member = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name class Job (models.Model): manager = models.OneToOneField(Manager, on_delete=models.CASCADE) member = models.OneToOneField(Member, on_delete=models.CASCADE) title = models.CharField(max_length=30, blank=False, null=False) description = models.TextField() datePosted = models.DateTimeField (auto_now = True) … -
How to add unique_together constraint to a Django table with prior data
I am trying to implement a unique_together constraint on one of the models in my Django project. The decision to have a unique constraint was taken after test data was already created in the table. Now while running migrations, I came across the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: movt_frt.frt_group_id, movt_frt.rec_loc_id, movt_frt.dis_loc_id I have tried creating similar unique constraints on table that previously held no data and migrations happened successfully. My question is: Am I right in concluding that the Migration is failing because the table already has data residing in it? Is there a way to do some changes to the migration file on the lines as discussed here and attempt migration again, to run successfully? I am using Django ver. 2.0.6 -
cant use django with mysql db
i have been search for answers on line on how to install mysqlclient but no answer was useful, please does this means i cant work with Django_mysql, because i have downloaded mysql_connector downloaded windows build tools just mention it and still having this error: Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\ecel\envs\mydjango\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\ECEL\AppData\Local\Temp\pip-install-rkn3bzqg\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\ECEL\AppData\Local\Temp\pip-install-rkn3bzqg\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\ECEL\AppData\Local\Temp\pip-wheel-o49c3slt' cwd: C:\Users\ECEL\AppData\Local\Temp\pip-install-rkn3bzqg\mysqlclient\ Complete output (24 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb -
Is it OK that change autofield data type in mysql regardless of django field definition?
Is it OK that I change data type in mysql differently from django? For example, I want to change Django model 'int' data type of ID autofield to 'tinyint' by mysql command. Is there not issue for future programming? the reason that I want to change data type is the model has only 24 row and data is no longer likely to be added to the model. so, Is it ok to change 'int' data type to 'tinyint'? -
ImportError: No module named wmicodes.makes
I am trying to setup my project in django and the folder structure seems to be fine. However upon running the command python manage.py runserver I get a ImportError: No module named wmicodes.makes. So i went into the traceback and found out a few files which led me to it. here are the files. myfolder/myfolder/somename/models/base.py #other imports from wmicodes.makes import InternalMake # i get the error on this particular line #other imports '''The rest of the code''' here's another file myfolder/myfolder/somename/models/init.py from .base import * #other imports and here's the traceback: Traceback (most recent call last): File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/mayureshkadam/Desktop/myfolder/myfolder/somename/models/__init__.py", line 1, in <module> from .base import * File "/home/mayureshkadam/Desktop/myfolder/myfolder/somename/models/base.py", line 20, in <module> from wmicodes.makes import InternalMake ImportError: No module named wmicodes.makes I tried finding the error however failed. any pointers would be of help. thanks! -
Django - Is there a better way to send bulk Twilio text messages?
I'm currently using the following views.py function sendsmss to allow a user to do a bulk sms message to their list of subscribers, after the user has completed an html form with the sms they want to send to their subscribers: def sendsmss(request): if request.method == "POST": subscribers = Subscriber.objects.all() sms = request.POST['sms'] mytwilionum = "+13421234567" ACCOUNT_SID = TWILIO_ACCOUNT_SID AUTH_TOKEN = TWILIO_AUTH_TOKEN client = Client(ACCOUNT_SID, AUTH_TOKEN) for subscriber in subscribers: subscriber_num = subscriber.phone_number client.messages.create( to= subscriber_num, from_=mytwilionum, body=sms ) return redirect('homepage') This function works, but I have only tested the bulk send with 3 subscribers. If there were 100s or 1000s of subscribers how long would this take .. if it takes long then would user be waiting for task to complete before redirect to homepage happens? Is there a better way to do this in Django? -
How to populate table after button click in django template?
I want to insert the values in the input field from the dictionary using DTL. Here's the snippet of code that on load page, making invisible this code tag in the table (may be because of if condition turns False) but just after data submission from dictionary, showing inserted value in the same tag. How can I make it work and remains all the td tags visible on the page load as well? Also since my data.items having 6 keys, so its iterating 6 times, I just want to get single time. I know I'm not very clear but sorry I can't post the whole code since is too big and confidential. Please Help it out, I'm totally new in django. Thanks. .... ... .. {% for key, value in data.items %} {% for key2,value2 in value.items %} <tr class="info"> <td>1</td> <td>Cholesterol -HDL</td> <td> {% if value2.test_name == "Cholesterol -HDL" %} <div class="form-group"> <input type="text" class="form-control" name="cholesterol_hdl_result" value="{{ value2.results }}"> </div> </td> <td><div class="form-group"> <input type="text" class="form-control" name="cholesterol_hdl_uom" value="{{ value2.units }}"> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="40.00" name="cholesterol_hdl_lr"> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="60.00" name="cholesterol_hdl_hr"> </div></td> {% endif %} </tr> {% endfor %} {% endfor %} .. ... … -
Auto suggestion?
I am working on chat bot(Front end: Angular,Back end: Django). I am thinking to add a feature in my chat bot i.e Auto suggestion like when the user comes to the chat bot and when user starts typing What then I need to get all the auto questions which starts with What which I have prepared the question(for ex: similar to google search).I am doing chat bot in manual process(rule- based process) i.e when the user asks the relevant questions then only I would get the output. So can you suggest me how should I do, I don't have any basic knowledge on auto suggestion or auto completion. And say me the approach. like where do I need to keep the questions(in front end or back end).If front end then what is the approach and in back end then what will be the approach.. Please suggest me the approach which would be better. -
Django Host name for an ip address
i have an ip address say x.x.x.x:8080 ,how can i mask this ip address and run as labview.net:8080 so that ip address cannot be exposed to the users.Can any one please explain the steps to be followed? -
Multiple databases routers Django
Dummy Task: Multi DB Router Requirements: 1) Databases: PostgreSQL DB and My SQL DB. 2) Django 1.10 with Python. 3) The multi-setting for local and production environments. 4) Proper Readme file with setup instructions. Description: - Project has 2 roles Admin and User - PostgreSQL has 2 database: database1, database2 - My SQL has 3 database: database3, database4, database5 You need to create a Django application where admin can add users and assign multiple databases (database1, database2, database3, database4, database5 ) to a user and when the user is created, he should get Email for login and password(or any other way to handle this flow). When the user performs login, he can see the database list, which admin assigned to him. Then a user can create a Product by selecting the database from the List. The product should be saved under the selected database. There should be one page where the user can see all product list with the database name. Admin has one page, where he can see all users and their product details. (CRUD operation should follow by default.) -
Django Fernet Fields : InvalidToken at / No exception message supplied
I am running a website using Django . The error i am getting is below: raise InvalidToken cryptography.fernet.InvalidToken`in fernet.py When i login to the ip: 127.0.0.1:8000, i am getting like this :`InvalidToken at / No exception message supplied What am i missing?` -
Combine the results while querying in Django
I am struggling to querying in Django as expected.I have multiple models that are Profile, Education, Address and Social Media. Education, Address and Social Media and related with Profile by foreign key and OnoToOne relation. I want the query results that list of profiles and each profile should contain relevant educations (as list), addresses (as list) and social media (as dictionary). This is my models.py from django.db import models class ORMProfile(models.Model): profile_photo = models.URLField(blank=True, null=True) cover_photo = models.URLField(blank=True, null=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) bio = models.TextField(blank=True, null=True) gender = models.CharField(max_length=120, blank=True, null=True) dob = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class ORMEducation(models.Model): profile = models.ForeignKey(ORMProfile, on_delete=True) school_name = models.CharField(max_length=255, blank=True, null=True) school_type = models.CharField(max_length=255, blank=True, null=True) qualification = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class ORMSocialMedia(models.Model): profile = models.OneToOneField(ORMProfile, on_delete=True) linked_in = models.URLField(blank=True, null=True) facebook = models.URLField(blank=True, null=True) twitter = models.URLField(blank=True, null=True) instagram = models.URLField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class ORMAddress(models.Model): profile = models.ForeignKey(ORMProfile, on_delete=True) street = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) state = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, … -
Django: 'QuerySet' object has no attribute 'serialize'
models.py class UpdateQuerySet(models.QuerySet): def serialize(self): qs = self return serialize('json', qs, fields=('user', 'content', 'image')) class UpdateManager(models.Manager): def get_queryset(self): return UpdateQuerySet(self.model, using=self._db) class Tools_booked(models.Model): auto_increment_id = models.AutoField(primary_key=True) user=models.ForeignKey(Profile, on_delete=models.CASCADE) component = models.CharField(max_length=30, blank=True) booked = models.DateTimeField(auto_now_add=True,blank=True) objects = UpdateManager() def __str__(self): return self.component def serialize(self): return serialize("json", [self], fields=['auto_increment_id','user','component','booked']) in views.py from django.core.serializers import serialize class SerializedDetialView(View): def get(self, request, *args, **kwargs): obj = Tools_booked.objects.get(auto_increment_id=1) json_data = obj.serialize() return HttpResponse(json_data, content_type='application/json') class SerializedListView(View): def get(self, request, *args, **kwargs): qs = Tools_booked.objects.all() json_data = qs.serialize() return HttpResponse(json_data, content_type='application/json') I have seen the similar question, it is solved with a new class view. But why this code is not working. The error it showing for SerializedListView and SerializedDetialView urls is 'QuerySet' object has no attribute 'serialize' and 'Tools_booked' object has no attribute 'serialize' Why this error exist and how can we solve this error without creating a new class. -
Django pages accessible through passphrases
(Reposted as my first post was worded incorrectly) Hi, I have a Django website up which currently supports login authentication and posts, however, I want to make a second-layer of authentication. I want to know if there is a way that seperate from user authentication, I could have passcode protected pages. For example, a post could be generated on a hidden page, the only way this page is accessible is if a logged in user enters a passcode into a form. So the user would log in, go to /passform and be greeted by a text input field, once they enter a code which correlates to a post ( for example post1 has a secret passcode of "abc123" ) if the code matches a post it would re-direct them to said page, and, if the code does not correlate it would just error out. Is there a way to do this within Django or should I be using queries for this? ( for this example I'm also assuming my create post has a function to enter a passphrase in the same way you would enter a title ect so it would be stored in the same database. ) Many thanks … -
How can I CSS-style different returns from the same Python function?
I have a Python function which returns different messages in different scenarios. I want to style different messages differently, but I don't know how to do it. This is my function: def checkans(request, spanish_id): random_spanish_question = get_object_or_404(Spanish, pk=spanish_id) query = request.GET.get('ans') coreng = random_spanish_question.english_set.get() if query == str(coreng): message = { 'message' : "Correct!" } return JsonResponse(message) else: message = { 'message' : "Incorrect. The correct answer is " + str(coreng) } return JsonResponse(message) This is the HTML page: <div class="flexcontainer" style="justify-content: center;"> <div class="sectiontitle">Quiz time </div> <div class="question_card"> <div class="question_word">{{ random_spanish_question }}</div> <div id="msg"></div> <form action="/checkans/{{random_spanish_question.id}}/" method="get">{% csrf_token %} <label for="ans">Answer:</label> <input type="text" name="ans"autofocus autocomplete="off" id="ansfield"/> <input type="submit" value="Submit"/ id="submitbtn"> </form> <input type="submit" value="Skip"/> <button onclick="location.reload();">Next</button> </div> </div> And this is the JS and AJAX code: $('form').on('submit', function(e){ e.preventDefault(); var form = $(this); var url = form.attr('action'); $.ajax({ type: 'GET', url: url, data: form.serialize(), success: function(data){ $("#msg").html(data.message); } }); disable(); }) function disable(e){ $('#submitbtn').prop('disabled', true); $('#ansfield').prop('disabled', true) } For example, I want to make the "Correct!" message green, while if it returns "Incorrect...", I want it to be red, and underline the answer, "str(coreng)". Please tell me how I can do it. Thanks in advance! -
Save Image from url Django Rest Framework
I'm trying to save an image from a url in the post request. Here is what I have so far, the error is while passing the file to the serializer. #models.py class Picture(models.Model): picture = models.ImageField( upload_to=upload_location_picture, max_length=255 ) owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name='owned_pictures') #views.py class PlanPostPictureByUrl(APIView): ''' Class to post dislike to plan ''' permission_classes = (permissions.IsAuthenticated,) def post(self, request, format=None): img_url = request.data["picture"] name = urlparse(img_url).path.split('/')[-1] response = requests.get(img_url) if response.status_code == 200: serializer = PlanPicturesSerializer( data={"picture":ContentFile(response.content)}) if serializer.is_valid(): serializer.save(owner=self.request.user) return Response(status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) #serializers.py class PlanPicturesSerializer(serializers.ModelSerializer): class Meta: model = Picture fields = ['picture'] This is the error I am getting from the serializer: {'picture': [ErrorDetail(string='No filename could be determined.', code='no_name')]} -
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'
So I am building a Django REST API with a Vue.js frontend and am not able to do cross origin get requests using Axios. I have seen several other posts to enable CORS on Django and what not which I have done but continue to get the same error. My Django backend settings looks like: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'api', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = False # CORS Origin Whitelist is the list of origins that are authorized # to make cross-site HTTP requests to our Django local server CORS_ORIGIN_WHITELIST = [ 'http://localhost:8080', ] CRSF_TRUSTED_ORIGINS = [ 'http://localhost:8080', ] And this is the Vue component I am trying to make the get request with: <script> import axios from 'axios' export default { mounted: function () { this.getStocks() console.log('Mounted Got Here') }, data: () => ({ … -
Django TypeError when accessing a link by get_absolute_url()
Good day. So i'm going through Django 2 by Example and i've encoutered a strange error when visiting a object from list of objects. TypeError at /1/black-tea/ product_detail() got an unexpected keyword argument 'id' The type it recieves is correct so small help would be appriciated. code from views.py def product_detail(request, product_id, slug): product = get_object_or_404(Product, slug=slug, id=product_id, available=True) return render(request, 'shop/product/detail.html', {'product': product}) models.py class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug')) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) urls.py path('<int:id>/<slug:slug>/', product_detail, name='product_detail'), Code from template <div id="main" class="product-list"> <h1>{% if category %} {{ category.name }}{% else %}Products{% endif %}</h1> {% for product in products %} <div class="item"> <a href="{{ product.get_absolute_url }}"> <img src="{% if product.image %}{{ product.image.url }} {% else %}{% static 'img/images.jpeg' %}{% endif %}"> </a> <a href="{{ product.get_absolute_url }}">{{ product.name }}</a> <br> ${{ product.price }} </div> {% endfor %} </div> -
fetch() URL won't get recognized
I keep getting error that the get-response in fetch("/get-response/" isn't found Can you help me figure out why? Here is some code fetch("/get-response/", { //<---- Not found body: JSON.stringify({'message': message['text']}), cache: 'no-cache', credentials: 'same-origin', headers: { 'user-agent': 'Mozilla/4.0 MDN Example', 'content-type': 'application/json' }, method: 'POST', mode: 'cors', redirect: 'follow', referrer: 'no-referrer', }) The get-response is coming from urls.py: from django.contrib import admin from django.conf.urls import include, url from django.urls import path from MyApp.views import Index, get_response from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), url('', Index), path('get-response/', get_response), ] And the get_response is coming from views.py @csrf_exempt def get_response(request): response = {'status': None} if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) message = data['message'] chat_response = chatbot.get_response(message).text response['message'] = {'text': chat_response, 'user': False, 'chat_bot': True} response['status'] = 'ok' else: response['error'] = 'no post data found' -
Django password protected pages
I've made a Django based website that can authenticate users by logging in, but I'm wondering if there is a way I could lock pages to a password? for example, on the front page I would have a form asking for a code (such as "SecretPassword1") and once a correct passphrase has be entered you would be re-directed to a 'secret' page? is this possible or am I thinking about it in the wrong way? (this is my first post on StackOverflow so sorry if anything is posted incorrectly) -
How do I link the is_org_admin field in the User model to the org_admin field in the Organization model in Django?
I'm trying to create some models in Django. I currently have the following: User and Organization. One of the fields in the User model is "is_org_admin", which is a boolean. How should I link this field to the "org_admin" field in the Organization model? Here's the simplified code: class Organization(models.Model): id = ... org_admin = models.OneToOneField("users.User"... class User(AbstractUser): id = ... is_org_admin = models.BooleanField(default=False) organization = models.ForeignKey("organizations.Organization", on_delete=models.CASCADE, null=True) -
Getting actual name of file after upload Django
I got a problem with retrieving the current name of the file. At the moment when I'm uploading file to my model with suffix. class DataUpload(models.Model): file_uploaded_path = models.FileField(upload_to="csv/%Y/%m/%d/") The problem with that is that I can't retrive file name with suffix. When i use >> DataUpload.file_uploaded_path.path I get only only path to the media root folder project/media/file.txt I've tried also .name or .url, still it's not it. I think I checked everywhere and I'm really out of ideas. -
vscode didn't close all django processes when comment "--noreload"
VSCode Version: 1.42.1 OS Version: Ubuntu 18.04 Steps to Reproduce: Comment "--noreload" in launch.json Press Ctrl + F5 to run the django process. Click "stop(Shift + F5)" button to stop all django processes. But there is still a process (pid 23069) that has not been closed. And its parent process become 1 from 23064 -
Model design for One to many relationship
I have to design model for a customer and cars owned by customer. A customer can own one car or multiple cars. The template should have a car dropdown thru which user can select a car model, there should be a add button for user to add another car model. [template view][1] [1]: https://i.stack.imgur.com/N8Fo6.png how do i go forward designing the model currently the model looks like this: class Customer(models.Model): customer_name = model.Charfield(max_length=30) class Car(model.Model): model_name = model.Charfield(max_length=30) class Engine(model.Model): horse_power = model.Charfield(max_length=30) car = model.ForeignKey(Car) class Car_Owned(model.Model): driver = model.ForeignKey(Customer, related_name="members",on_delete=models.CASCADE) model_name = model.ForeignKey(Car, related_name="car",on_delete=models.CASCADE) engine = model.ManytoMany(Engine)