Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to run django app with Apache server in Mac Ventura
I am new to django app development. I am trying to use apache server for my django app in Mac OS Ventura. For this I am using mod_wsgi module to make the integration between Apache server and django app. I followed the required steps to do the setup, by making changes in httpd.conf and httpd-vhost.conf file. After the setup, I started the apache server but in the app log I am getting below error - [wsgi:error] [pid 30317] [remote ::1:62168] mod_wsgi (pid=30317): Failed to exec Python script file '/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py'. [Mon Jan 09 16:16:41.752524 2023] [wsgi:error] [pid 30317] [remote ::1:62168] mod_wsgi (pid=30317): Exception occurred processing WSGI script '/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py'. [Mon Jan 09 16:16:41.752667 2023] [wsgi:error] [pid 30317] [remote ::1:62168] Traceback (most recent call last): [Mon Jan 09 16:16:41.752707 2023] [wsgi:error] [pid 30317] [remote ::1:62168] File "/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py", line 12, in [Mon Jan 09 16:16:41.752719 2023] [wsgi:error] [pid 30317] [remote ::1:62168] from django.core.wsgi import get_wsgi_application [Mon Jan 09 16:16:41.752731 2023] [wsgi:error] [pid 30317] [remote ::1:62168] File "/Users/yadavv2/PycharmProjects/ESE/venv/lib/python3.9/site-packages/django/init.py", line 1, in [Mon Jan 09 16:16:41.752740 2023] [wsgi:error] [pid 30317] [remote ::1:62168] from django.utils.version import get_version [Mon Jan 09 16:16:41.752751 2023] [wsgi:error] [pid 30317] [remote ::1:62168] File "/Users/yadavv2/PycharmProjects/ESE/venv/lib/python3.9/site-packages/django/utils/version.py", line 1, in [Mon Jan 09 16:16:41.752761 2023] … -
Django smart fiter transfers
I have a model Book and there are duplicated rows in that table. One of the duplicates was changed during duplicate operation. The differences between that rows are in two fields (special_id and state). E.g.: Name special_id state Idiot "0107" 1 Idiot "0106" 2 During filtering by state if i write Book.objects.filter(state=2), i'll get the books with value of state 2, So i want to exclude this book if there is the book with the same name and with the state 1 Is there any way to do this without for loop and looking by the name of every book in QuerySet? Now when quantity of books is not big the delay of for loop is not noticeable. But when they'll be enormous i think it's going to be really long delay. -
Have multiple fields from another model linked by a foreign key
I have multiple models : class Circuit(models.Model): name = models.CharField('Circuit', max_length=120) country = models.CharField('Pays', max_length=120, choices=country_choices) version = models.CharField('Version circuit', default='Grand-Prix', max_length=120, choices=circuit_version_choices) image = models.ImageField('Image noir/blanc', blank=True, upload_to='circuit_pics', default='circuit_pics/a2*1ùp6*ù.png') image_details = models.ImageField('Image détaillée', blank=True, upload_to='circuit_details', default='circuit_details/a2*1ùp6*ù.png') class Event(models.Model): game = models.ForeignKey(Game, verbose_name='Nom du jeu', null=True, on_delete=models.SET_NULL) event_type = models.CharField(verbose_name="Type d'événement", max_length=50, choices=type_course) league = models.ForeignKey(League, verbose_name='Ligue', null=True, on_delete=models.SET_NULL) circuit = models.ForeignKey(Circuit, verbose_name='Circuit', null=True, on_delete=models.SET_NULL) event_date = models.DateTimeField(verbose_name="Date de la course") A race event takes place in a circuit. This circuit can have multiple versions (the version field in the Circuit model gives "Version1", "Version2", as possible choices). How can I have this choice also in the Event model, so that, in the admin section, I also have the choice to pick the circuit version it will take place in. More generally, how do I add multiple fields in a model from another model linked with a foreign key ? -
Use a django template variable in django-crispy bootstrap AppendedText or PrependedText
I saw that a similar question was asked 10 years ago about buttons and that it was resolved. I was naive enough to think that maybe it was possible for other fields ^^ Have I missed something ? As said in the Title, I'm trying to use a django template variable {{ tetra }} in a Layout Fieldset AppendedText or PrependedText value, like this class AddObjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( 'Some Text as Legend', AppendedText('userref', {{tetra}} ), but it won't work :-( I also tried with HTML tag like : PrependedText('userref', HTML("""{{tetra}}""") ), but in this case I also obtain : <crispy_forms.layout.HTML object at 0x7fb1997f8c70> Can anyone enlighten me, direct me or confirm that this is not possible? -
What is the right way to write test cases in django?
Unittest or Bultin test.Testcases or pytest I have these options. I have a socialmedia project where there is so many apis. should I only test apis with request methods or should I test every single views, serializers etc. Right now i m doing with django test.Testcases -
How to show if users already enable two-factor-auth on Django admin
Is there a way to show user two-factor-auth status on Django admin user list? From the documentation, I only found this manage.py two_factor_status user, which only show user OTP status on terminal. -
Django: How can I get the child element ListView and DetailView in the same Template?
I have a model for Letter_box and Letter. I want to display the "list of received letters" and "contents of the selected Letter" on the detail page of each Letter_box, but I don't know how. I can display the contents of the Letter_box and the list of Letter, but it is difficult for the letter contents. What I want to do is similar to this question (DJANGO: How to access data from ListView and DetailView on the same template?). However, the effect of pk on letter_box raised questions. Can you help me? models.py class LetterBox(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField("title", max_length=100) created_at = models.DateTimeField("create_date", auto_now_add=True) class Letter(models.Model): name = models.CharField("name", max_length=100) contents = models.TextField("cotents") created_at = models.DateTimeField("create_date", auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) letter_box = models.ForeignKey(LetterBox, on_delete=models.CASCADE) views.py class LikeLetterBoxDetail(LoginRequiredMixin,generic.ListView): template_name = "like_letter_box_detail.html" paginate_by = 2 def get_queryset(self): return Letter.objects.filter(letter_box_id=self.kwargs['pk']).order_by("created_at") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["letter_list"] = Letter.objects.filter(letter_box_id=self.kwargs['pk']).order_by("created_at") context['letterbox'] = get_object_or_404(LetterBox, pk=self.kwargs['pk']) return context class LikeLetterDetail(LoginRequiredMixin,generic.DetailView): model= Letter template_name = "like_letter_detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["letter_list"] = Letter.objects.filter(letter_box_id=self.kwargs['pk']) return context -
Ajax form processing
After submitting a form to Django, it takes about 3 seconds to process I need an Ajax script that will redirect the user to an intermediate page where he will wait for a response from Django. Django got a new redirect after receiving the response I tried to solve this problem with Django, but I can't do 2 redirects in one view -
Save a model in the database with multilevel nested serializers in Django
i need help with my rest Api,with Django rest Framework and Django 4. My Api is for reading texts in foreign language, i'm trying to save a new MyTexts model in the database (Sqlite). I think the problem comes from the serializer TextSerializer. I have these models and serializers(correct them if they are wrong): #language/models.py from django.db import models # Model for a Language class Language(models.Model): LgName=models.CharField(max_length=40) LgDict1URI=models.CharField(max_length=200) LgDict2URI=models.CharField(max_length=200) LgGoogleTranslateURI=models.CharField(max_length=200) LgExportTemplate=models.CharField(max_length=1000) LgTextSize=models.IntegerField() LgRemoveSpaces=models.BooleanField() LgRightToLeft=models.BooleanField() LgSkills=models.TextField() def __str__(self) -> str: return self.LgName #language/serializer.py from rest_framework import serializers from .models import Language class LanguageSerializer(serializers.ModelSerializer): class Meta: model=Language fields='__all__' #learner/model.py from django.db import models from django.contrib.auth.models import AbstractUser from language.models import Language # Model for a Learner(a user) class Learner(AbstractUser): SelLanguage=models.OneToOneField(Language,on_delete=models.CASCADE,null=True,related_name="SelLanguage") is_teacher=models.BooleanField(default=False) can_post=models.BooleanField(default=False) level=models.IntegerField(default=0) def __str__(self) -> str: return self.username #learner/serializer.py from django.contrib.auth import authenticate, get_user_model from rest_framework import serializers from language.models import Language from language.serializers import LanguageSerializer from .models import Learner User = get_user_model() class UserSerializer(serializers.ModelSerializer): SelLanguage=LanguageSerializer(many=False,read_only=True) def create(self, validated_data): SelLanguage = validated_data.pop('SelLanguage') user = Learner.objects.create(**validated_data) lg=Language.objects.get(Learner=user, **SelLanguage) user.SelLanguage=lg user.save() return user class Meta: model = Learner fields = '__all__' #myTags/models.py from tkinter import CASCADE from django.db import models from accounts.models import Learner from language.models import Language # Model for optional tags … -
How to integrate novnc client inside django project
I have a couple virtual machines running inside proxmox but I found out you can use the novnc client to connect to these virtual machines and use the console in a web browser. This is perfect for different clients I work with. I already have a small django project that shows the running nodes and vm's inside of them. Now I wanted to include de js library by novnc. However I can't really find a lot of information online and since my coding experience is not that high I don't really know what I am doing wrong. I used this outdated repo and tried to see if I can find out how to get it to work. https://github.com/missuor/novnc-proxy-django for now I have a view that call the api of proxmox. /api2/json/nodes/{node}/lxc/{vmid}/vncproxy to be precise. this returns a ticket, port, cert, user and upid. Now I am not sure if I just need to call the vncproxy or use these variable to open a websocket by /api2/json/nodes/{node}/lxc/{vmid}/vncwebsocket. The django view i currently have just call the vncproxy and sends the values to the rendered template. This template I used from the repo metioned above, but I just don't know why I … -
Queryset for search by username and display_name In Django Rest Framework
I'm trying to search users by their usernames and display names. I have used that for the starting match. search_obj = User.objects.exclude(user_uuid=token_user_uuid).filter(Q(display_name__istartswith=search_name) | Q(username__istartswith=search_name) ).order_by('-created_on')[:10] I get the answer same as I want but the problem is if the display name is William Welch and I search for Welch It should return that user also, but it does not return that user. -
Calling a model's method inside a serializer and handling a received object
I'm supposed to write an API for the endpoints. It should be an application inside an existing project. I should work with its models and i'm not allowed to alter them in any way. The project consists of multiple application, and some application have their own models. There is an exempt from CategoryMetall/models.py in the CatalogNew application: class CategoryMetall(MPTTModel): position = models.ForeignKey( Menu, on_delete=models.CASCADE, verbose_name="foo", blank=True, null=True, ) subPosition = TreeForeignKey( "self", on_delete=models.CASCADE, verbose_name="bar", blank=True, null=True, ) def parent(self): if self.subPosition: return self.subPosition else: return self.position As i understood, the parent() method is supposed to return an object of either a CatalogNew model, or a Menu model. A Menu model is a model of another application from the project. Here is an exempt from it as well: Menu/models.py class Menu(models.Model): parent = models.ForeignKey( "self", on_delete=models.CASCADE, verbose_name="parent category", null=True, blank=True, ) So, i figured that in order to get a parent category i'm supposed to use the CategoryMetall.parent() method written by some other developer. The issue is, i'm also supposed to somehow serialize it. I have written a serializer in my serializers.py: class CategoryMetallSerializer(serializers.HyperlinkedModelSerializer): parentCategory = serializers.ReadOnlyField(source='parent') class Meta: model = CategoryMetall fields = ['id', 'name', 'parentCategory'] And a view for … -
Hosting Django Docker Postgres on DigitalOcean Droplets
I am new to deploying to DigitalOcean. I recently created a Droplet, into which I will put my Django API to serve my project. I saw that the droplet I rent has 25 GB of memory, and for the actual size of my project, it could be a good fit for the database. I run my entire code with Docker Compose, which handles Django and PostgreSQL. I was wondering if it is a good idea to store all the data in the PostgreSQL created by Docker Image, and stored in the local memory of the droplet, or do I need to set up an external Database in Digital Ocean? Technically I think that could work, but I don't know if it is safe to do, if I will be able to scale the droplets once the size scales, or if I will be able to migrate all the data into an external database, on digital ocean, a managed PostgreSQL all my data without too many problems. And if I save it all locally, what about redundancy? Or can I clone my database on a daily basis in some way? If someone knows about that and can help me, please I … -
ModuleNotFoundError: No module named 'config' outside django app
I am using cookiecutter-django on my project and having problem while trying to import settings from config outside app. Getting error ModuleNotFoundError: No module named 'config' Project structure project ┣ .envs ┃ ┗ .local ┃ ┃ ┣ .bot ┃ ┃ ┣ .django ┣ bot ┃ ┣ __init__.py ┃ ┗ bot.py ┣ compose ┃ ┣ local ┃ ┃ ┣ django ┃ ┃ ┃ ┣ Dockerfile ┃ ┃ ┃ ┗ start ┃ ┃ ┗ pytelegrambot ┃ ┃ ┃ ┣ Dockerfile ┃ ┃ ┃ ┗ start ┣ config ┃ ┣ settings ┃ ┃ ┣ __init__.py ┃ ┃ ┣ base.py ┃ ┃ ┣ local.py ┃ ┣ __init__.py ┃ ┣ urls.py ┃ ┗ wsgi.py ┣ project ┃ ┣ app ┃ ┃ ┣ migrations ┃ ┃ ┃ ┗ __init__.py ┃ ┃ ┣ admin.py ┃ ┃ ┣ apps.py ┃ ┃ ┣ signals.py ┃ ┃ ┣ models.py ┃ ┃ ┗ views.py ┣ requirements ┃ ┣ base.txt ┣ README.md ┣ local.yml ┣ manage.py bot.py import telebot from config.settings.base import env bot = telebot.TeleBot(env('BOT_TOKEN')) def send_welcome(message): print(message) if __name__ == '__main__': bot.infinity_polling() signals.py from bot.bot import send_welcome @receiver(post_save, sender=Model) def translate(sender, instance, created, **kwargs): send_wlcome("Hi") Here I am sending message on telegram bot when object created. If I try to … -
Python - What is wrong with this fucniton declaration?
def convert(self, path: str): ^ SyntaxError: invalid syntax i am getting a SyntaxError. I checked online and saw this is how it should be declared. what is wrong with this? -
celery beat schedule: why one same task is completed in different time durations?
I have used celery-beat to get data from about 30 different APIs and save them in database. There are two prblems: first: why it takes so long to do the task (i thought it shouldn't take more than 2-3 seconds)? second: why a single task takes different time durations to be done? celery: terminal: -
Django + vue.js importing modules problem while using vue-simple-context-menu
How can I import modules for VueJS app in a template, rendered by Django. I'm trying to import module vueSimpleContextMenu. for ref- https://www.npmjs.com/package/vue-simple-context-menu trying to use this library but it requires import statement which I am unable to use. This is my situation: archiveModal.html: <template id="archiveModal"> <ul> <li v-for="item in items" @click.prevent.stop="handleClick($event, item)" class="item-wrapper__item" > {{item.name}} </li> </ul> <vue-simple-context-menu element-id="1" :options="options" ref="vueSimpleContextMenu" @option-clicked="optionClicked" /> <template> archiveModal.js const archiveModal = { delimiters: ['[[', ']]'], template: '#archiveModal', data() { return { options: [ { name: 'Duplicate', slug: 'duplicate', }, { type: 'divider', }, { name: 'Edit', slug: 'edit', }, { name: '<em>Delete</em>', slug: 'delete', }, ], }; }, methods: { handleClick(event, item) { this.$refs.vueSimpleContextMenu.showMenu(event, item) }, optionClicked(event) { window.alert(JSON.stringify(event)) }, }, component: { 'vue-simple-context-menu': VueSimpleContextMenu, }, }; On Github it requires import VueSimpleContextMenu from 'vue-simple-context-menu'; import 'vue-simple-context-menu/dist/vue-simple-context-menu.css'; Is there a way to use that in django template and where am I doing the mistake? -
Returns only the last data. I need all the data Django python
return response is only sending the last response in the for loop I need all the data in postman data=[] data.append({"coll_code":coll_code,"coll_name":coll_name,"coll_location":coll_location,"branch_name":branch_name,"branch_id":curentbranch_id,"extention2021":c1, "seconground2021":c2, "firstround2021":c3, "extention2020": c4, "seconground2020":c5, "firstround2020":c6, "extention2019": c7, "seconground2019":c8, "firstround2019":c9}) return Response(data) -
How to use django-autocomplete-light and django-hacker to make a chained dropdown in django admin?
I have 3 models 1) university 2) courses and 3) enquiry. My enquiry model has a foreign key to "course". And Course has a foreign key to the university. I only want to show the courses related to that university while adding an enquiry. I tried django-smart-select but failed to do so. I tried This answer but I dont understand the logic and failed to implement in my project. this is my models.py file class university(models.Model): univ_name = models.CharField(max_length=100) country = CountryField(blank=True, null=True) univ_desc = models.CharField(max_length=1000) univ_logo = models.ImageField(upload_to="media") univ_phone = models.CharField(max_length=10, blank=True) univ_email = models.EmailField(max_length=254, blank=True) univ_website = models.URLField(blank=True) assigned_users = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, default="") def __str__(self): return self.univ_name class Meta: verbose_name_plural = "Universities" class Course(models.Model): university = models.ForeignKey(university, on_delete=models.CASCADE) course_name = models.CharField(max_length=100) course_levels = models.ForeignKey(course_levels, on_delete=models.CASCADE) intake = models.ForeignKey(intake, on_delete=models.CASCADE) documents_required = models.ForeignKey(documents_required, on_delete=models.CASCADE) course_requirements = models.ForeignKey(course_requirements, on_delete=models.CASCADE) Active = models.BooleanField() def __str__(self): return self.course_name class enquiry(models.Model): student_name = models.CharField(max_length=100) student_phone = models.CharField(max_length=10) student_email = models.EmailField() student_address = models.TextField() current_education = models.ForeignKey(current_education, on_delete=models.CASCADE) country_interested = CountryField(blank=True, null=True) university_interested = models.ForeignKey(university, on_delete=models.CASCADE) course_interested = models.ForeignKey(Course, on_delete=models.CASCADE, limit_choices_to={'Active':True}) level_applying_for = models.ForeignKey(course_levels, on_delete=models.CASCADE) intake_interested = models.ForeignKey(intake, on_delete=models.CASCADE) assigned_users = models.ForeignKey(User, on_delete=models.CASCADE, default="", limit_choices_to={"is_active": True}) enquiry_status = models.ForeignKey(enquiry_status, on_delete=models.CASCADE, default="") course_interested= ChainedForeignKey(Course,chained_field= 'university_interested',chained_model_field= … -
Django Unit test is written but coverage report says there are missing statements
I try to get coverage reports using a simple django model. Unit test for model was written but report says there are missing statements. The model: from django.db import models from model_utils import FieldTracker from generics.base_model import BaseModelMixin class AModel(BaseModelMixin): record_name = models.CharField(max_length=255) tracker = FieldTracker() class Meta(BaseModelMixin.Meta): db_table = 'a_model_records' def __str__(self): record _name = self. record_ name if record_name is None: record_name = "N/A" return record name The unit test: class TestAModel(TestCase): def setUp(self): super().setUp() def test_allowed_domain_model(self): record_name = "some name" is_active = True user = User.objects.first() record = AModel.objects.create( record_name=record_name, is_active=is_active, created_by_id=user.id, ) self.assertEqual(str(record), record_name) self.assertEqual(record.name, record_name) self.assertEqual(record.is_active, is_active) The command line code I run: source activate set -a source local.env set +a coverage run --source="unit_test_app" --rcfile=.coveragerc project/manage.py test -v 2 coverage report coverage html The coverage configuration is like this: [run] omit= */migrations/* */tests/* */manage.py */apps.py */settings.py */urls.py */filters.py */serializers.py */generics/* [report] show_missing = true Coverage result shows missing statements: This is the simplest example. There are many ignored functions by coverage which descends percentage average, but actually covered by unit tests. Why does coverage act like this? -
Can I provide automatically current user in Django rest API like this?
I have a Django rest api. In my model I have a user as a foreign key. When I do a post with the, I do not want that the user needs to provide his own user. But if the user does not provide his user credentials, the serializer won't be valid and then won't be saved. I have found that we can access to serialized dat before validation with initial_data so I am doing like this to save the user automatically from the token provided. The user need to provide everything except his own user. Is it ok or am I doing something not recommended ? @api_view(['POST']) @permission_classes([IsAuthenticated]) def add_mesure(request): serializer = MesureSerializer(data=request.data) serializer.initial_data['user'] = request.user.id if serializer.is_valid(): serializer.save() return Response(serializer.data) -
I am using Django and I want to encrypting my URL to secure it can some one help me
I am using Django rest framework and I want to encrypting my URL to secure it, I want to encrypt only one URL which is section URL I create the encryption file but I do not know tho use it inside the views.py here is my code views.py class ChapterSectionList(generics.ListAPIView): serializer_class=SectionSerializer def get_queryset(self): chapter_id=self.kwargs['chapter_id'] chapter=models.Chapter.objects.get(pk=chapter_id) return models.Section.objects.filter(chapter=chapter) encryption_util.py from cryptography.fernet import Fernet import base64 import logging import traceback from django.conf import settings def encrypt(text): try: txt = str(txt) cipher_suite = Fernet(settings.ENCRYPT_KEY) encrypted_text = cipher_suite.encrypt(txt.encode('ascii')) encrypted_text = base64.urlsafe_b64encode(encrypted_text).decode("ascii") return encrypted_text except Exception as e: print(e) logging.getLogger("error_logger").error(traceback.format_exc()) return None def decrypt(txt): try: txt = base64.urlsafe_b64encode(txt) cipher_suite = Fernet(settings.ENCRYPT_KEY) decoded_text = cipher_suite.decrypt(txt).decode("ascii") return decoded_text except Exception as e: logging.getLogger("error_logger").error(traceback.format_exc()) return None -
Django : Reduce number of possible choices based on previous model choice inputs
I have multiple models : class Game(models.Model): name = models.CharField('Nom du jeu', max_length=100) logo = models.ImageField('Logo', blank=True, upload_to='game_logos') class League(models.Model): game = models.ForeignKey(Game, verbose_name='Jeu', null=True, on_delete=models.SET_NULL) league = models.CharField('Ligue', max_length=20) hexcolor = models.CharField('Code couleur Hex', max_length=7, blank=True, default='#000000') class Event(models.Model): game = models.ForeignKey(Game, verbose_name='Nom du jeu', null=True, on_delete=models.SET_NULL) event_type = models.CharField(verbose_name="Type d'événement", max_length=50, choices=type_course) league = models.ForeignKey(League, verbose_name='Ligue', null=True, on_delete=models.SET_NULL) circuit = models.ForeignKey(Circuit, verbose_name='Circuit', null=True, on_delete=models.SET_NULL) event_date = models.DateTimeField(verbose_name="Date de la course") The logic here is, that we have races, that take place place in a certain game, and in a certain league. The thing is, I can have different games that have their own league, independent from the league of the other games (Formula 1 will have League A, B and C, and another game will have League 1, 2 and 3). So when I set up a new event, as soon as I choose the game, I want to get the leagues associated with this game, not all of them. How can I filter the choices of the leagues based on the game input ? -
Pylint Fatal error while checking on every python file
/Users/..../coding/projects/.../.../campaign/permissions.py: Fatal error while checking /Users/..../coding/projects/.../.../campaign/permissions.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in '/Users/.../Library/Caches/pylint/pylint-crash-2023-01-09-17-28-38.txt'. I have just configured pylint on vscode. But have this eeror apper on the first line of every python file.enter image description here How can i fix this? -
Should I use oneToMnay or ManyToMany in django
I am new in django and trying to create a website where I can search for vehicles and see what parts I have for this vehicle. I have two databases, one with vehicles and one with parts: class Vehicle(models.Model): vehicle_id = models.BigIntegerField(primary_key=True) vehicle = models.CharField(max_length=255) def __str__(self): return self.vehicle class Part(models.Model): part_id = models.BigIntegerField(primary_key=True, db_column='part_id') part_name = models.CharField(max_length=255, db_index=True, null=True) catalog_code = models.CharField(max_length=255, null=True) price = models.CharField(max_length=255, default=None, null=True) description = models.CharField(max_length=255, default=None, null=True) vehicle_id = models.ForeignKey(Vehicle, on_delete=models.PROTECT, null=True) def __str__(self): return self.part_name Now I using oneToMany, but can't figure out if it is correct and how can I see all parts for one vehicle