Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django CBV doesnt pagginate with editing context
View down below should show the tasks for the logged user but when I paginate the tasks I got Cannot filter a query once a slice has been taken. how should I filter the context to avoid the error for pagination? class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = 'tasks' template_name = 'TaskList.html' paginate_by = 2 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user=self.request.user) return context -
django inspectdb-generated gitlab models throws errors when making migrations
i have generated inspectdb models for my django project. They are models generated from gitlab postgres database extracted by pg_dump. So now i have models.py file having something like 8k lines, and when trying to make migrations i get multiple errors. Some of the examples are: (They are mostly the same just with different variables) trackApp.Appearances.favicon: (fields.E121) 'max_length' must be a positive integer. or trackApp.AnalyticsDevopsAdoptionSegments.namespace: (fields.E304) Reverse accessor for 'trackApp.AnalyticsDevopsAdoptionSegments.namespace' clashes with reverse accessor for 'trackApp.AnalyticsDevopsAdoptionSegments.display_namespace'. I would be able to fix this by hand, but having a 8k lines long file makes this impossible. Is there any trick i could use to "mass-fix" these errors? -
unknow `runcrons` when running `python3 manage.py runcrons
When I run python3 manage.py runcrons, this message appears: "Unknown command: 'runcrons'". I run python3 manage.py help and couldn't find runcrons in the list of commands. How can I add runcrons to manage.py enter image description here -
Failed to push to heroku - Requested runtime (ÿþpython-3.8.0) is not available for this stack
When I try and push my django app to heroku I get the following error: Requested runtime (ÿþpython-3.8.0) is not available for this stack (heroku-20). This looks like an error with runtime.txt - I've tried changing the formatting from UTF-16 to UTF-8 which was suggested elsewhere. "ÿþ" was not included in my runtime.txt so this I why I think it's an encoding issue Does anyone know why this is occuring? Cheers! -
Problem with install GeoDjango Could not find the GDAL library
I followed with instruction: https://docs.djangoproject.com/en/4.0/ref/contrib/gis/install/ for Windows 10 I downloaded Postgres and added installed Postgis. Then OSGeo4W in the folder C:\OSGeo4W and maked point Modify Windows environment I create new project and one application. In settings.py added: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geodjango', 'USER': 'geo', }, } After run py manage.py runserver I get a error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal303", "gdal302", "gdal301", "gdal300", "gdal204", "gdal203", "gdal202", "gdal201", "gdal20"). Is GDAL installed? If it is, try setting GDAL_LIB RARY_PATH in your settings. I add (Python Root)\Lib\site-packages\django\contrib\gis\gdal\libgdal.py "gdal305", becauuse this file i have in C:\OSGeo4W\bin. I get a error: FileNotFoundError: Could not find module 'C:\OSGeo4W\bin\gdal305.dll' (or one of its dependencies). Try using the full path with constructor syntax. (this path is good ) In settings.py I add: GDAL_LIBRARY_PATH = r'C:\OSGeo4W\bin\gdal505', but I'm showing the same error as before. So I try in settings.py: import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] And I still get … -
Django reverse error when passing additional variable
I am attempting to pass variables through different django views. The error I am getting is: Reverse for 'download_file' with keyword arguments '{'path_id': '19', 'filename': 'TESTCE-DCNCE-01.conf'}' not found. 1 pattern(s) tried: ['download/(?P<filename>[^/]+)/\\Z'] I have this working code: This is my view.py def report(request, pk_test): order = Order.objects.get(id=pk_test) path_id = str(order.id) outpath = 'orchestration/outputs/' + str(order.id) files_configs = glob.glob(outpath + '/*.conf', recursive=True) files = [] for each_file in files_configs: head, tail = path.split(each_file) files.append(tail) context = { 'order': order, 'files_configs': files, 'path_id': path_id, } return render(request, 'orchestration/report.html', context) Here is my report.html: {% for each_files_configs in files_configs %} <p></p> <a href="{% url 'download_file' filename=each_files_configs %}">{{ each_files_configs }}</a> {% endfor %} This is my views.py, which is linked to the href: def download_file(request, filename=''): if filename != '': When I run the code like ths, it works fine. If I then add the additional parameter 'path_id' as below, I get a reverse error. Surely path_id is no different from passing in filename? {% for each_files_configs in files_configs %} <p></p> <a href="{% url 'download_file' path_id=path_id filename=each_files_configs %}">{{ each_files_configs }}</a> {% endfor %} This is my views.py, which is linked to the href: def download_file(request, path_id='', filename=''): if filename != '': -
Django graphene - Unable to query union field
In my application I have 2 models: class Employee(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100, null=False) email_id = models.EmailField(null=False) class UserGroup(models.Model): created_by = models.EmailField(null=False) An UserGroup can be created by an Employee or by the "System". So, the possible values for "created_by" are: "employeex@mail.com" "System" Now, I want to expose this property in graphql. From the graphql, I want to be able to get the properties of created_by (like firstName, lastName etc) if created_by is an Employee. Otherwise I want to get String in the graphql response. Here is what I have done so far: import graphene from graphene_django.types import DjangoObjectType from models import Employee, UserGroup class EmployeeObjectType(DjangoObjectType): class Meta: model = Employee class UserGroupCreatedBy(graphene.Union): class Meta: types = (EmployeeObjectType, graphene.String, ) class UserGroupType(DjangoObjectType): created_by = graphene.Field(UserGroupCreatedBy) def resolve_created_by(self, info): if self.created_by == "System": return self.created_by return Employee.objects.get(email_id=self.created_by) class Meta: model = UserGroup query { userGroups { createdBy { ... on EmployeeType { firstName } } } } When I request the graphql API, this is the error that I am getting: ERROR:django.request:Internal Server Error: /graphql Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/utils/deprecation.py", line 113, in __call__ response = self.process_request(request) … -
not found url when use persian/arabic slug in django
database: mysql database Collation encode: 'utf8_persian_ci' django version: last version python version: 3.7.12 Point: It work well in local host but not working in real host Error : models.py : class blog(models.Model): slug = models.SlugField(max_length=255,allow_unicode=True,unique=True) title = models.CharField(max_length=255) description = models.CharField(max_length=255) def __str__(self): return f'title: {self.title}' Views.py : def blogViews(request,slug): if blog.objects.filter(slug=slug).count() > 0: post = blog.objects.get(slug=slug) context = { 'post': post, } return render(request,'blog/post_detail.html',context) else: return HttpResponseNotFound() i tried these: 1- change get_bytes_from_wsgi encode in django/core/handlers/wsgi.py return value.encode('ISO-8859-1') to return value.encode('UTF-8') 2- django setings.py: ALLOW_UNICODE_SLUGS = True How do I fix it? -
Django modelform initial value doesn't work
def createProject(request): form = ProjectForm() initial_data = { 'responsible':request.user.username } yonetici = Project(host=request.user) if request.method == 'POST': form = ProjectForm(request.POST, instance=yonetici,initial=initial_data) if form.is_valid(): form.save() return redirect('home') context = {'form': form} return render(request, 'base/project_form.html', context) i tried many solutions but i couldnt make it work where am i doing wrong? -
How can I get a text in a particularly element in RichTextField Django?
Actually I have a TOC page in which data is dynamic. There is a RichTextUploading Field for this but the problem is that I have a sidebar on page which will anchor to the heading in RichTextField. I have to get the heading value and give it a id for anchoring it. How can I do that? Thanks -
Django - ModuleNotFoundError: No module named 'csvexport'
So I'm working on adding an admin function to a Django project so that I can export the model instances to csv. It is all working fine locally whilst using Docker. But when deploying I get this internal server error: It states that the package is not installed, but when accessing the Django shell (poetry run python3 manage.py shell) and importing the package (from csvexport.actions import csvexport) everything works fine. I'm stuck for quite some time now on this and cant figure out what is going wrong. Anyone had some kind of problem like this with poetry package managing? settings.py: INSTALLED_APPS = [ ... 'csvexport', ] model: from csvexport.actions import csvexport from django_summernote.admin import SummernoteModelAdmin class FundAdmin(SummernoteModelAdmin): ... actions = [csvexport] -
How Django Implement tier selection
Is that Django have any feature that can implement tier selection? the form like this, first, user select the first field says gender, then the next category field will list out all the category belongs to this gender says Male. -
multiple event targets on same parent element not working
I have been dealing with this problem for quite some time. It's been a great way to learn Javascript, but I'm just done and need help before I end up in prison for something dumb. I need the inline formset's delete checkbox checked before removing the parent element (form). I am using Django's inline formsets and refuse to use jquery to handle this because I want to learn good ol' vanilla Javascript. I have tried all kinds of combinations and solutions with nothing to show. {% load crispy_forms_tags %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="{% static 'css/availability_update_new.css' %}"> </head> <body> <form id="all-add-form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <legend class="bottom mb-4">Profiles Info</legend> {{ sun_bool.sunday|as_crispy_field }} {{ sunday_formset.management_form }} {% for sun_form in sunday_formset %} {% for hidden in sun_form.hidden_fields %} {{ hidden }} {% endfor %} <div class="sun_time_slot_form"> {{ sun_form }} <button class="delete-sun-form" type="button" id="delete-sun-btn" onclick="one();"> Delete This Sunday Timeslot </button> </div> {% endfor %} <button id="add-sun-form" type="button" class="button">Add Other Sunday Times</button> <input type="submit" name="submit" value="Submit" class="btn btn-primary"/> </form> <script type="text/javascript" src="{% static 'js/add_timeslot.js' %}"></script> </body> </html> {% endblock content %} const sunForm = document.getElementsByClassName('sun_time_slot_form'); const mainForm … -
Invalid HOST header: 'ec2-13-233-105-50.ap-south-1.amazonaws.com:8000'. You need to add 'ec2-13-233-105-50.ap-south-1.amazonaws.com' to ALLOWED_HOSTS
I have been getting this error even when I added the public ipv4 address added to the allowed hosts. I don't know what I am doing wrong. This is My settings.py code. I'm trying to run this application in amazon ec2 instances. Using bitbucket code deploy pipeline. but my code giving this unusual error. """ Django settings for Cycatz project. Generated by 'django-admin startproject' using Django 4.0.5. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['ec2-13-233-105-50.ap-south-1.amazonaws.com:8000'] ENV = "dev" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cycatzapp', 'rest_framework', 'corsheaders', 'ebhealthcheck.apps.EBHealthCheckConfig', 'drf_yasg' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Cycatz.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', … -
Whats the best strategy to upload and process big macros file
I have a project which allow user to upload macros files, about 30Mb each file. After uploading a file I need to process it like open that workbook then pick a sheet then insert the data inside to database. I realize that just open the workbook with openpyxl is taking too much time. So what's the best way to do this, do I need to run it concurrently in the background or any other option and how to achieve that. I'm using Django btw. Thanks in advance -
Django shell history commands always come from top
I've been having issues in trying to use older Django shell history commands, be it from previous shell session or current. If I press UP arrow key, they show the first lines in the ~/.ipython/profile_default/history.sqlite, and not the last one I pressed enter on. A couple of things I've tried are: Removed ipython history file, touched it again but same problem. Re-installed Ipython in venv. Tried using shell from a different project. Tried using shell_plus from django-extensions. Nothing seemed to fix the issue. Does anyone have a clue how to fix this? -
Testing cursor.execute with sql script called
Function to test def get_adgroups_not_taked_share( campaign_ids: List[str], src_table: str, spend_src_table: str ) -> List[Tuple[str, str]]: loses_adgroups: List[Tuple[str, str]] = [] with RedshiftCursor() as cursor: cursor.execute( """ SELET some_data from some_table WHERE some_condition """ ) for row in cursor.fetchall(): loses_adgroups.append((row[0], str(row[1]))) return loses_adgroups There is a test for this function import pytest from my_ap import get_adgroups_not_taked_share @pytest.fixture def campaigns_redshift_cursor_mock(mocker): cursor_mock = mocker.MagicMock() cursor_mock.fetchall.return_value = [ ('hs_video544', '123123123', 100), ('hs_video547', '123123123', 50), ] rs_cursor_creator = mocker.patch('google_panel.logic.clean_creative.RedshiftCursor') rs_cursor_creator.return_value.__enter__.return_value = cursor_mock return rs_cursor_creator @pytest.mark.django_db def test_get_adgroups_not_taked_share( campaigns_redshift_cursor_mock, ): campaign_ids = ['1111', '2222', '3333'] result = get_adgroups_not_taked_share(campaign_ids, 'test_table', 'spend_src_table') assert result == [('hs_video544', '123123123'), ('hs_video547', '123123123')] Now I want to add a new feature to test the sql script. Checking that the correct sql query is being called. something like def test_get_adgroups_not_taked_share( campaigns_redshift_cursor_mock, ): ...... query = """SELET some_data from some_table WHERE some_condition""" campaigns_redshift_cursor_mock.execute.assert_called_with(query) But got E AssertionError: Expected call: execute('query') E Not called -
DJANGO FILTERING ON FORIEGN KEY PROPERTIES
I HAVE 2 MODELS class Cart(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE,blank=True, null=True) user = models.ForeignKey(User,on_delete=models.CASCADE,null=True, blank=True) quantity = models.IntegerField(default=1) class Item(models.Model): restaurant = models.ForeignKey(Restaurant,on_delete=models.CASCADE,null=True, blank=True) name= models.CharField(max_length=100) is_active = models.CharField(max_length=30,null=False,default=True) is_avaliable = models.CharField(max_length=30,null=False,default=True) price = models.CharField(max_length=30,null=False,default=0) WHERE cart is using restaurant as a foreign key in views.py def post(self,request,*args,**kwargs): userid = request.user.id res= request.data.get('restaurant', False) cartItem = Cart.objects.filter(user=userid,item__restaurant__contains=res) it is throwing an error saying raise FieldError( django.core.exceptions.FieldError: Related Field got invalid lookup: contains [02/Aug/2022 08:37:45] "POST /placeorder HTTP/1.1" 500 118627 what i want to do is Get all cart objects which has user id = userid and item.restaurant = restaurant id ... can someone help me i referred this page https://stackoverflow.com/questions/1981524/django-filtering-on-foreign-key-properties but i doesnt seems to work! -
How to make API post request when using django-countries package
I came across this package called django-countries and the the features it provides look nice. Now I'm trying to test it out in a react application but I'm having issues making API post request when trying to post a named country to the database. Instead of CharField I used countryField() provided by the package. I have tried several format to make post request from postman but I keep having the error:"country_name" is not a valid choice. One of the ways I have tried out is this: { "country": "country_name" } How do I go about it. Since I'm using react, will be better for me to use charField instead of using the django-countries package since I'll be using html select option to get the country of the user? -
When inserting a lot of data : No 'Access-Control-Allow-Origin' header is present on the requested resource
I'm working on a React Django API project, I'm using postgreeSQL as Database, and I deployed my website using nginx and gunicorn, I have a problem on my deployed website when I try to insert a lot of data (add studies), I'm getting this error: Access to XMLHttpRequest at 'http://192.168.85.126:8000/api/new-study/' from origin 'http://192.168.85.126' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. PS: I'm not getting this error when I try to add less data, in my development environment I can add whatever data I want, the problem is only happening in production -
Saving parsed json data to a sqlite database tables collection. Regular updates with schedule
Within my Django project, which will be a website, there is an app that will collect odds data from API's of different bookmakers. So far I have set up the requests and parsed the data that I want to collect and store for one bookmaker. I have it in its own .py file which you can see below. I would like to store each block of data in a separate table within a SQLite database within the app of the project. bluebet_au.py code: import json # Bluebet Rugby League Odds API. link = 'https://affiliate-api.bluebet.com.au/json/reply/MasterCategoryRequest?EventTypeID=102&WithLevelledMarkets' \ '=true&WithLevelledMarkets=true ' # Request data from link as 'str' data = requests.get(link).text # convert 'str' to Json data = json.loads(data) # HEAD TO HEAD ODDS for win_odds in data['MasterCategories'][0]['Categories'][0]['MasterEvents']: h2h_market_competition = win_odds['CategoryName'] h2h_market_event_id = win_odds['MasterEventId'] h2h_market_event_title = win_odds['MasterEventName'] h2h_market_start_time = win_odds['MaxAdvertisedStartTime'] h2h_market_market_type = win_odds['Markets'][0]['BetDetailTypeCode'] h2h_market_home_team = win_odds['Markets'][0]['OutcomeName'] h2h_market_home_team_win_odds = win_odds['Markets'][0]['Price'] h2h_market_away_team = win_odds['Markets'][1]['OutcomeName'] h2h_market_away_team_win_odds = win_odds['Markets'][1]['Price'] print('{}, {}, {}, {}, {}, {}, {}, {}, {}'.format(h2h_market_competition, h2h_market_event_id, h2h_market_event_title, h2h_market_start_time, h2h_market_market_type, h2h_market_home_team, h2h_market_home_team_win_odds, h2h_market_away_team, h2h_market_away_team_win_odds)) # HANDICAP ODDS for handicap_odds in data['MasterCategories'][0]['Categories'][0]['MasterEvents']: handicap_market_competition = handicap_odds['CategoryName'] handicap_market_event_id = handicap_odds['MasterEventId'] handicap_market_event_title = handicap_odds['MasterEventName'] handicap_market_start_time = handicap_odds['MaxAdvertisedStartTime'] handicap_market_market_type = handicap_odds['Markets'][2]['BetDetailTypeCode'] handicap_market_home_team = handicap_odds['Markets'][0]['OutcomeName'] handicap_market_home_team_win_handicap = handicap_odds['Markets'][2]['Points'] handicap_market_home_team_win_odds = handicap_odds['Markets'][2]['Price'] handicap_market_away_team … -
HTML variable in <a> for href
In my HTML, I want to have the text of a href to be the same as the variable each_files_configs. Whatever I try seems to come out as a literal. {% for each_files_configs in files_configs %} <p></p> <a href="{% url 'download_file' %}">document.write(each_files_configs)</a> {% endfor %} I have also tried <var> and all it does is change the text to italics. -
How to get relational model of data in django?
I'm querying user data. And I'm getting the following output in response. { "id": 33, "username": "dummy", "email": "dummy@test.com", "role": 49, "is_active": true, "staff": true, "admin": false, "last_login": "2022-07-27T06:41:03.709582Z", "update_time": "2022-08-02T07:53:11.241320Z", "create_time": "2022-07-26T14:34:35.161434Z" } As you can see, this user model is in foreign relation with a role with an id 49. I want to get all the details of the role in JSON with accounts instances. How can I do that ? e.g : { "id": 33, "username": "dummy", "email": "dummy@test.com", "role": { "id":49 "projects":true, "notifications":true, "emails":true, "update_time": "2022-08-02T07:53:11.241320Z", "create_time": "2022-07-26T14:34:35.161434Z" }, "is_active": true, "staff": true, "admin": false, "last_login": "2022-07-27T06:41:03.709582Z", "update_time": "2022-08-02T07:53:11.241320Z", "create_time": "2022-07-26T14:34:35.161434Z" } My Views for this API. @api_view(['GET']) @permission_classes([IsAuthenticated]) def all_platform_user_list(request): if request.method == 'GET': users = User.objects.get_all_platform_users() total_count = len(users) total_page = total_page_counter(total_count) paginator = CustomPagination() paginator.page_size = 20 result_page=None try: result_page = paginator.paginate_queryset(users, request) except: pass serializer = CreateAccountsSerializer(result_page, many=True) return Response({"message": "Here are results","total_page":total_page,"total_count":total_count, "data": serializer.data},status=status.HTTP_200_OK) else: return Response({"message": "No User"},status=404) -
How to post with multiple images in django rest framework(DRF)?
I wanted to request several images at once, so I found them on Google and wrote the code. However, image url is not added to the image list as a result of POST in postman. The image does not enter the my vcode media folder. please...help me... The setup was completed as follows. settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') models.py from django.db import models from django.contrib.auth.models import User class Story(models.Model): title = models.CharField(max_length=50) content = models.TextField() createdAt = models.DateTimeField(auto_now_add=True, null=True) updatedAt = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.title class StoryImage(models.Model): story = models.ForeignKey(Story, on_delete=models.CASCADE, related_name='image') image = models.ImageField(upload_to='images/', blank=True, null=True) serializers.py from rest_framework import serializers from .models import Story, StoryImage class StoryImageSerializer(serializers.ModelSerializer): image = serializers.ImageField(use_url=True) class Meta: model = StoryImage fields = ['image'] class StorySerializer(serializers.ModelSerializer): images = serializers.SerializerMethodField() def get_images(self, obj): image = obj.image.all() return StoryImageSerializer(instance=image, many=True, context=self.context).data class Meta: model = Story fields = '__all__' def create(self, validated_data): instance = Story.objects.create(**validated_data) images_data = self.context['request'].FILES for image_data in images_data.getlist('image'): StoryImage.objects.create(story=instance, picture=image_data) return instance views.py from django.shortcuts import render from rest_framework import viewsets from .models import Story from .serializers import StorySerializer class StoryViewSet(viewsets.ModelViewSet): queryset = Story.objects.all().order_by('-createdAt') serializer_class = StorySerializer urls.py from django.contrib import admin from django.urls … -
How to import export works in foreign key - django
I do have two models 1) patient profile, to get patient First and last name, default id and 2) Medinfo, medical information of patient used default id of patient model as foreign key. I am trying to use django import export for bulk upload data.. in patient profile model i can able to upload data without any trouble, but when I trying upload data in medinfo model, I am getting error. I do understand due to using foreinkey as field I am getting trouble here to import data. How to do it? Note: pat_ID is also a primary key of Medinfo model. class Patientprofile(models.Model): pat_Fname = models.CharField(max_length=100) pat_Lname = models.CharField(max_length=100, blank=True) def __str__(self): return str(self.id) class MedInfo(models.Model): # Medical Information fields Notes = models.TextField(max_length=2000, blank=True) pat_ID = models.OneToOneField(patientprofile, on_delete=models.CASCADE,unique=True, primary_key=True) def __int__(self): return self.pat_ID