Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a custom serializer for a django rest framework model with translations
I'm using django-rest-framework and I have a model "TextElement" with attribute "text" translated using django-modeltranslation. I need to create a generic serializer that takes translated fields and returns as data a dictionary with language as the key and the translated attribute as value. Example: text_element = TextElement.objects.get(id=1) text_element_serializer = TextElementSerializer(text_element) text_element_serializer.data >> {"text": {"en": "Something", "es": "Algo"}, "other_attribute": "Something else"} I could do it using the following serializer: class TextElementSerializer(serializer.ModelSerializer): text = serializer.SerializerMethodField() class Meta: model = TextElement fields = ('text', 'other_attribute') def get_text(self, instance): return { 'en': instance.text_en, 'es': instance.text_es } But I would like to know if it's possible to create a genereic serializer that checks automatically all the translated attributes in "fields", using available languages in settings.LANGUAGES and returning the same data structure. Thanks in advance! -
Python Django Linking URLS
I am working on an online school project, I just linked subjects, with classes so when you click on a class you get it's subjects page, and in the subject page there are lessons(lessons use IDs not slugs), My problem is at linking the lesson URL in the HTML page My codes: HTML PAGE: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Name</title> <link rel="stylesheet" href="/static/css/style.css"> </head> <body> <div> <nav> <div class="logo"><img src="/static/images/Logo.png" width=50px></div> <ul class="navul"> <li class="navli"><a class="nava" href="404.html">حول الموقع</a></li> <li class="navli"><a class="nava" href="404.html">المكتبة</a></li> <li class="navli"><a class="nava" href="404.html">الدورات</a></li> <li class="navli"><a class="nava" href="/classes">الصفوف</a></li> <li class="navli"><a class="nava" href="/">الصفحة الرئيسية</a></li> </ul> </nav> <div class="div1"> <img src="/static/images/Logo.png" width="90" class="logo2"> <h1 class="t1">المواد </h1> </div> <div class="cardrow"> {% for material in material.all %} <div class="cardcolumn"> {% for Lesson in Materials.vedio_set.all %} <a href="{% url 'vedio' lesson.id %}" > lesson1</a> {% endfor %} <div class="card"> <img class="imgcls" src="{{ material.image.url }}"> <h1>{{ material.title }}</h1> </div> </a> {% endfor %} </div> </div> </div> </body> </html> MODELS.py: from django.db import models from users.models import * # Create your models here. class Class(models.Model): image= models.ImageField(upload_to="images") name= models.CharField(max_length=200, default=1) title= models.CharField(max_length=200) def __str__(self): return self.title class Material(models.Model): name= models.CharField(max_length=200, default=1) title= models.CharField(max_length=200) classes= models.ForeignKey(Class, default=1, on_delete=models.SET_DEFAULT) def __str__(self): return self.name class Lesson(models.Model): slug=models.SlugField() … -
How to fix TypeError: FilterIPMiddleware() takes no arguments in django
I face the problem of TypeError: FilterIPMiddleware() takes no arguments when I applied to my project python version 3.7.2. here is the code raising the error from django.http import HttpResponseForbidden class FilterIPMiddleware(object): #Check if client IP is allowed def process_request(self, request): allowed_ips = ['111.111.111.111'] # Authorized ip's ip = request.META.get('REMOTE_ADDR') # Get client IP print(ip) if ip not in allowed_ips and request.user.username=="example_name": return HttpResponseForbidden() # If user is not allowed raise Error # If IP is allowed we don't do anything return None Here is the Traceback: Exception in thread django-main-thread: Traceback (most recent call last): File "/root/.pyenv/versions/3.7.2/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/root/.pyenv/versions/3.7.2/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, … -
Django support multi language for just one html file
I wonder if there is a fast way to make multilangauge(almost 30 languages) support for just one simple html file. I tried django multilangauge support but it took so long time to do it since this project is python2 and has so many apps. -
Save Binary Data Using Django Rest Framework Viewset method
I have a viewset method save that accepts formdata and should save the instance and return it. @action(methods=['put'], detail=False) def save(self, request): user = request.user if not user.is_staff: raise PermissionDenied("You must be a staff member or superuser to edit app settings.") settings = Globaloptions.objects.first() data = json.loads(request.body, encoding='utf-8') if not settings.guestEnabled: if 'guestDashboard' in data: del data['guestDashboard'] [setattr(settings, k, v) for k, v in data.items()] settings.save() serializer = self.get_serializer(settings, many=False) return Response(serializer.data) I recently added a file field to the model. So now when I try to save it, I get an error because it fails to parse the data in utf-8. What is the correct method for saving a form with binary data when using a viewset? -
Django: Trying to populate a dropdown using Javascript
I have two dropdowns and I'm trying to populate the second one using Javascript when the first one changes. It should be populated from the database values contained in 'departements' variable of my views.py file. I found some code on the web but it didn't work when I tried to apply it to my case. I have next to 0 knowledge in Javascript, so no idea if I'm even on the right path. Below are more details about my files: models.py class data_immo(models.Model): id = models.AutoField(primary_key=True) insee_dep = models.IntegerField(db_column='INSEE_DEP', blank=True, null=True) nom_reg = models.TextField(db_column='NOM_REG', blank=True, null=True) class Meta: managed = True db_table = 'immo' views.py def MyView(request): query_results = data_immo.objects.all() regions = data_immo.objects.values_list("nom_reg", flat=True).distinct() departements = data_immo.objects.values_list("insee_dep", flat=True).distinct() query_results_dict = { 'query_results': query_results, 'regions': regions, 'departements': departements, } return render(request,'home.html', query_results_dict) home.html <select id="reg" name="reg" onChange="populate2()"> {% for item in regions %} <option val="{{ item.nom_reg }}"> {{ item.nom_reg }} </option> {% endfor %} </select> <select id="dep" name="dep"></select> <script type="text/javascript"> function populate2(){ $('.dep').append('<option>' + departements[0].insee_dep + '</option'); } </script> I need the populate2() function to update the 'dep' dropdown. The function is obviously wrong, but I don't know where exactly. Thanks in advance! -
TemplateDoesNotExist at http://127.0.0.1:8000/
I don't know why I am getting this error. Below is the code I am using. settings.py TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "mysite", "static", "templates"),) urls.py from django.urls import path from django.conf.urls import include, url from django.contrib.auth import views as auth_views from notes import views as notes_views urlpatterns = [ url(r'^$', notes_views.home, name='home'), url(r'^admin/', admin.site.urls), ]``` **views.py** `def home(request): notes = Note.objects template = loader.get_template('note.html') context = {'notes': notes} return render(request, 'templates/note.html', context)` NOTE : I am following this tutorial - https://pythonspot.com/django-tutorial-building-a-note-taking-app/ -
how can i send a file from django into a script of python?
I have a python script that processes an excel or csv document, in the python script I write the specific path of the file, locally. this is my code in Python ''' url_rsso = r'file:///C:/Users/Mata/Desktop/RSSO.xlsx' ''' df_rsso = pd.read_excel(url_rsso) this is my code in django def upload(request): context = {} if request.method == 'POST': df_rsso = request.FILES['document'] fs = FileSystemStorage() name = fs.save(df_rsso.name, df_rsso) context['url'] = fs.url(name) return render(request, 'upload.html', context) I also have a web page with django that is very simple, it has a ChooseFile, a button whose action will process the file and one to download the modified file. What I want to do is: the file that I store using django can send it to the script I have in python. If the file is sent to the script, it processes it and exports it in excel which I have to send to django for the user to download the new modified file. here is my github https://github.com/mata-2p/codelweb i am very new in python and django -
Instead of the contents of the HTML page, code is displayed
I am writing a site in Python, Django. After updating PyCharm, the HTML page in the browser displays not its contents, but the code! What can be done with this? Thanks in advance. -
Django view not passing IP address data from form
Trying to do something simple here where I pass an IP address from a form to another view. Previously I had success following beginner tutorials. If someone could point me back to what I'm missing that would be a huge help. model: class GenericIP(models.Model): name = models.CharField(max_length=50) genericip = models.GenericIPAddressField() def __str__(self): return self.name form: class IpForm(forms.Form): gateway = ModelChoiceField(queryset=GenericIP.objects.order_by('name').values_list('genericip', flat=True).distinct()) views: def TestCreate(request): if request.method == 'GET': form1 = IpForm() return render(request, 'create_test.html', {'form1' : form1} ) else: if request.method == 'POST': form1 = IpForm() if form1.is_valid(): genericip = form1.cleaned_data genericip.save() return render(request, 'create_test.html', {'genericip' : genericip} ) def RunTest(request, genericip=""): if request.method == 'POST': Server = genericip return HttpResponse(Server) URLS: urlpatterns = [ path('', views.TestCreate, name='create_test'), path('run_test', views.RunTest, name='run_test',), ] template: {% block content %} <form action="{% url 'run_test' %}"method='post'> {% csrf_token %} {{ form1 }} <input type='submit' class="btn btn-success" value='Run Test'> </form> {% endblock %} So what's happening is when I hit the button to run the test, I don't get anything for the httpresponse. The post data for the TestCreate view does show variable "genericip" and input "192.168.100.100" but that data is not posting correctly to the runtest view. -
Get ID with delete mẹthod in django base views
I'm coding project by Django. In class View have some method as get, post, put, delete... I wrote get and post method. Now I want to custom delete method get object id from request. Can I code? If yes, how do I have to? -
how to show the direction between two location on a maps in django
am working on a project where a user enters the pickup location and destination location I want to show on maps of two locations with distance in my Django project this is how i want -
UserWarning: Unable to import floppyforms.gis, geometry widgets not available while installing geonode in centos 7
I am trying to install geonode in Centos 7 following this document Install GeoNode on CentOS 7. I installed all the dependencies by sudo yum install -y libxml2-devel libxslt-devel libjpeg-turbo-devel postgresql postgresql-server postgresql-contrib postgresql-libs postgresql-devel postgis geos-python python python-tools python-devel python-pillow python-lxml openssh-clients zip unzip wget git gdal python-virtualenv gdal-python geos python-pip python-imaging python-devel gcc-c++ python-psycopg2 libxml2 libxml2-devel libxml2-python libxslt libxslt-devel libxslt-python while trying to run migration by python manage.py migrate i am having following error /opt/virtual_env/geonode/lib/python2.7/site-packages/floppyforms/__init__.py:21: UserWarning: Unable to import floppyforms.gis, geometry widgets not available "Unable to import floppyforms.gis, geometry widgets not available") Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/opt/virtual_env/geonode/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/opt/virtual_env/geonode/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/opt/virtual_env/geonode/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/virtual_env/geonode/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/opt/virtual_env/geonode/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/opt/virtual_env/geonode/lib/python2.7/site-packages/mapstore2_adapter/__init__.py", line 18, in <module> __version__ = pkg_resources.require("django-mapstore-adapter")[0].version File "/opt/virtual_env/geonode/lib/python2.7/site-packages/pkg_resources/__init__.py", line 900, in require needed = self.resolve(parse_requirements(requirements)) File "/opt/virtual_env/geonode/lib/python2.7/site-packages/pkg_resources/__init__.py", line 791, in resolve raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.ContextualVersionConflict: (Django 1.11.22 (/opt/virtual_env/geonode/lib/python2.7/site-packages), Requirement.parse('Django>=2.2'), set(['jsonfield'])) i installed gdal and gdal-python and verified the installation. what might cause this error? My … -
How to add a calendar pop up for the datefield in my django form?
This is my forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout,Submit from .models import Event class EventForm(forms.ModelForm): class Meta: model = Event fields = "__all__" def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.helper = FormHelper self.helper.form_method = 'post' self.helper.layout = Layout( 'creator', 'date', 'name', 'public', 'limit_of_guests', Submit('submit','Submit',css_class='btn-success',style="margin-top: 20px; ") ) -
In 2020, what is recommended for doing AJAX in a Django Application? [closed]
Currently I have been using Jquery for doing AJAX in my Djano application. I understand that today the Web Development world is moving away from Jquery. What framework or approach would be recommended for doing Javascript moving forward? This is actually my first application with Django, HTML and Javascript so a beginner friendly approach would be recommended. -
Unable to copy or add tags to the django-taggit within admin.py
I'm making use of django-taggit. Within my admin.py file, I'm trying to copy the contents from other fields to the tags field, but it's not letting me copy it. states and cities are 2 lists that I have within my admin.py file. if form.cleaned_data["tags"] != "": org_name = form.cleaned_data["organization"] dept_name = form.cleaned_data["department"] prof_name = form.cleaned_data["profession"] current_tags = form.cleaned_data["tags"] str_tags = str(org_name) + ", " + str(dept_name) + ", " + str(prof_name) for city in cities: str_tags = str_tags + ", " + str(city) for state in states: str_tags = str_tags + ", " + str(state) obj.tags = str_tags obj.save() form.save_m2m() I viewed couple of solutions but they didn't work for me. I would really thankful if anyone could help me fix this issue. Thank you so much for your time and help in advance! -
sqlalchemy.exc.ProgrammingError in django
Im working django application with mysql version 8.0. i changed the version 5.7 after i running my application im getting this error "sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(order by ovr.obj_nm)" but the details are storing in db normally. -
Django generate bar code and save into image field
I am able to generate the bar code and can save the image file in the root folder using this library python-barcode. Now I am trying to generate the bar code image and save into the django image filed. Tryouts: import barcode bc = Barcode.objects.latest('id') upc = barcode.get('upc', '123456789102', writer=ImageWriter()) img = upc.render() # Returns PIL image class # <PIL.Image.Image image mode=RGB size=523x280 at 0x7FAE2B471320> bc.img = img bc.save() Getting Error: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-77-4ff34d9ac4c9> in <module> ----> 1 bc.save() ~/Desktop/workspace/projects/barcodescan/scan/models.py in save(self, *args, **kwargs) 19 code = get_random_string(length=11, allowed_chars='1234567890') 20 self.code = str(code) ---> 21 super(BarCode, self).save(*args, **kwargs) 22 23 def __str__(self): ~/Desktop/workspace/projects/barcodescan/venv/lib/python3.5/site-packages/django/db/models/base.py in save(self, force_insert, force_update, using, update_fields) 739 740 self.save_base(using=using, force_insert=force_insert, --> 741 force_update=force_update, update_fields=update_fields) 742 save.alters_data = True 743 ~/Desktop/workspace/projects/barcodescan/venv/lib/python3.5/site-packages/django/db/models/base.py in save_base(self, raw, force_insert, force_update, using, update_fields) 777 updated = self._save_table( 778 raw, cls, force_insert or parent_inserted, --> 779 force_update, using, update_fields, 780 ) 781 # Store the database on which the object was saved ~/Desktop/workspace/projects/barcodescan/venv/lib/python3.5/site-packages/django/db/models/base.py in _save_table(self, raw, cls, force_insert, force_update, using, update_fields) 846 base_qs = cls._base_manager.using(using) 847 values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False))) --> 848 for f in non_pks] 849 forced_update = update_fields or force_update … -
Is it possible to map a choice field selection to a foreign key in django
models.py class Testimonials(models.Model): client = 'client' employee = 'employee' general = 'general' Testimonial_Choices = ( ('client', 'client'), ('employee', 'employee'), ('general', 'general'), ) testimonial_type=models.CharField(max_length=25, choices=Testimonial_Choices, default=client) if testimonial_type=='client': client_name= models.ForeignKey(Client, on_delete=models.CASCADE) content= models.TextField(max_length=500, blank=False) posted_date= models.DateField(auto_now_add=True) def __str__(self): return self.client_name admin.py class TestimonialAdmin(admin.ModelAdmin): list_display = ('testimonial_type', 'posted_date') list_filter = ('testimonial_type', 'posted_date') search_fields = ['testimonial_type', 'posted_date'] empty_value_display = '-- NA --' list_per_page = 10 admin.site.register(Testimonials, TestimonialAdmin) I am trying to add a choice field first and if the choice type is client i want to fetch the client name and image error AttributeError: 'Testimonials' object has no attribute 'client_name' -
Which algorithm should I use for news popularity(worldwide) using machine learning, have tried K-means clustering?
I am working on News Popularity model where I need to fetch the most trending/popular news in the World. Have fetched data from 40 diff News sources through RSS APIs. What would be best approach to achieve this? Have tried K-Means clustering which will cluster similar news from diff resources, a cluster with the max count will be most popular. #machinelearning #newspopularity #clustering #ai -
DRF: how to not allow create() in Serializer
I'm working with DRF and have a ViewSet where I want to allow all the possible actions (list, details, update, delete), except create(). This is what I have for the moment: class FooViewSet(viewsets.ModelViewSet): queryset = Foo.objects.order_by('-date_added').all() serializer_class = FooSerializer def create(self, request): return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) def update(self, request, pk=None): version = get_object_or_404(Foo, pk=pk) html = request.data.get('html') version.update_content(html) return Response(data={ 'id': version.id, 'name': version.name, 'description': version.description, 'html': version.content, }, status=status.HTTP_200_OK) I know I could make the serializer inherit from ReadOnlyModelViewSet but then I wouldn't be able to update it. So what is the cleanest way of not allowing to create()? -
how to set pagination in django views?
how to set pagination in this views, i tried all the default django_pagination but i didn't get any helped. class Order_ListAPIView(APIView): def get(self,request,format=None): if request.method == 'GET': cur,conn = connection() order_query = ''' SELECT * FROM orders''' order_detail_query = ''' SELECT * FROM order_details''' with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(order_query) order_result = cursor.fetchall() order_data = list(order_result) ... ... #rest_code ... return Response({"order_data":order_data},status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) -
File Upload Parser
I need a small help, I am trying to load a JSON file content into my code via REST API, I don't want to upload it to any areas, I don't want it to download, I just want it to read by using this such rest call: urls.py **url(r'^api/postCNMetadata/(?P<filename>[^/]+)$', PostCNMetadataToDB.as_view()),** viewsets.py from rest_framework.parsers import FileUploadParser class PostCNMetadataToDB(APIView): ''' Posting data from json file to DB. ''' parser_classes = (FileUploadParser,) def put(self, request, filename, format=None): try: file_obj = request.FILES['file'] return Response("success", status = status.HTTP_200_OK) except Exception as e: return Response("error", status = status.HTTP_404_NOT_FOUND) Then I am running this command: wget -q -O - --no-check-certificate "http://atclvm1335.athtem.eei.ericsson.se:8000/api/postCNMetadata/image-metadata-artifact.json/" I am not sure what I am doing wrong here. But I am getting this error: 2020-03-05 12:16:43,400 [INFO][sshtunnel.ForwardServer:34] Server Fowarded extending SocketServer.ThreadingTCPServer parmiko class /proj/lciadm100/cifwk/my_repo/ERICcifwk/ERICcifw_reporting/django_proj/dmt/infoforConfig.py:9: DeprecationWarning: the sets module is deprecated from sets import Set Traceback (most recent call last): File "/usr/lib64/python2.6/wsgiref/handlers.py", line 94, in run self.finish_response() File "/usr/lib64/python2.6/wsgiref/handlers.py", line 135, in finish_response self.write(data) File "/usr/lib64/python2.6/wsgiref/handlers.py", line 223, in write self._write(data) File "/usr/lib64/python2.6/socket.py", line 324, in write self.flush() File "/usr/lib64/python2.6/socket.py", line 303, in flush self._sock.sendall(buffer(data, write_offset, buffer_size)) error: [Errno 104] Connection reset by peer ---------------------------------------- Exception happened during processing of request from ('10.59.140.55', 53707) Traceback … -
How to generate and format field values (primary key and other types)?
My model is defined like: class Example(models.Model): ex_id = models.CharField(max_length=30, primary_key=True) name = models.CharField() sess_id = models.CharField(max_length=20, default=0) creation_date = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return str(self.name) What I'm trying to do is assigning ids dynamically with use of the serializer below. The values should be generated based on timestamp taken from the model: class ExampleSerializer(serializers.ModelSerializer): ex_id = serializers.SerializerMethodField() name = serializers.CharField(min_length=6) sess_id = serializers.SerializerMethodField() def get_ex_id(self, obj): return '{:x}'.format(int(obj.creation_date.strftime("%Y%m%d%H%M%S%f"))) def get_sess_id(self, obj): return 'sess_' + str(obj.creation_date.strftime("%d%H%M%S%f")) class Meta: model = Example fields = '__all__' Everything ends up with inserting one record to the database; in case of following attempts UNIQUE constraints failed error is thrown. In the browser view, the one record that was added displays ids as defined in the serializer, but when I look into the database, there are empty/zero values for them (0 in case of sess_id, since this is the default value; empty value for ex_id). How/where should I configure the app to have the formatted values inserted as field values? -
Django - UNIQUE constraint failed on foreing keys
I have two tables on my Django database (SQLite), Field_Of_Research and Conference. Conference has three foreign keys associated to the primary key of Field_Of_Research. During the migrate command, I populate the database (reading from csv files), but when two conference with same foreign key value (for all three keys) are inserted, the UNIQUE constraint failed is diplayed. If I insert the confereces using the admin page, the database gives the same error. How can I solve this problem? model.py class Field_Of_Research (models.Model): for_id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=256) def __str__(self): return self.name class Conference (models.Model): conf_id = models.PositiveIntegerField(primary_key=True) title = models.CharField(max_length=256) primary_for = models.ForeignKey(to=Field_Of_Research, default=0, on_delete=models.SET_DEFAULT, related_name= 'primary_for') secondary_for = models.ForeignKey(to=Field_Of_Research, default=0, on_delete=models.SET_DEFAULT, related_name= 'secondary_for') third_for = models.ForeignKey(to=Field_Of_Research , default=0, on_delete=models.SET_DEFAULT, related_name= 'third_for') def __str__(self): return self.title populate.py with open('./server/api/database/files/fields_of_research.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=';') for row in csv_reader: f=Field_Of_Research.objects.get_or_create( for_id = row[0], name = row[1] ) print(f'Fields of Research done.') #Populates the conferences database with open('./server/api/database/files/conferences.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=';') for row in csv_reader: print(row) c=Conference.objects.get_or_create( conf_id = row[0], title = row[1], primary_for = Field_Of_Research.objects.get(for_id=int(row[3])), secondary_for = Field_Of_Research.objects.get(for_id=int(row[4])), third_for = Field_Of_Research.objects.get(for_id=int(row[5])), ) print(f'Conferences done.') error File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", …