Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i access the session values in Django Backend
I need to access the values of the variables in the Django backend. -
Django Template extract list
I have a list: productlinks = [google.com, tes.com, lol.com] prices = [$134, $123,$123] I wanna extract those list to my django template inside the bootsrap. Here is my django template code: <section class="py-5"> <div class="container px-4 px-lg-5 mt-5"> <div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center"> {% for link in productlinks %} <div class="col mb-5"> <div class="card h-100"> <!-- Product image--> <img class="card-img-top" src="https://dummyimage.com/450x300/dee2e6/6c757d.jpg" alt="..." /> <!-- Product details--> <div class="card-body p-4"> <div class="text-center"> <!-- Product name--> <h5 class="fw-bolder">Fancy Product</h5> <!-- Product price--> x $40.00 - $80.00 -> price must be here using loop to extract the list </div> </div> <!-- Product actions--> <div class="card-footer p-4 pt-0 border-top-0 bg-transparent"> <div class="text-center"><a class="btn btn-outline-dark mt-auto" href="{{ link }}" target="_blank">View options</a></div> </div> </div> </div> {% endfor %} </div> </div> </section> So basically, I wanna also extract the prices list but i dont know how to place the loop after the my productlinks loop. Because it will ruins the result. and here is my views code: return render(request, '/home.html', { 'productlinks': productlinks, 'prices': productprices } ) -
can Anybody explain how to integerate SuiteCRM rest api in Django? with code example
I am trying to fetch data from SuiteCRM rest api but unable to, I've installed somewhat configured and set database with default values, I am using SuiteCRM v7 and rest v4_1 on apache2 server on localhost -
Diacritics in search function case sensitive
I have a search function in my Django app: #search def search(request): if request.method == "POST": searched = request.POST['searched'] result = Post.objects.filter(title__contains=searched) return render(request, 'blog/searched.html', {'searched':searched, 'result':result}) else: return render(request, 'blog/searched.html',{}) Problem is, when I search the following, I get the following results: Zaštita -> I get 'Zaštita' result zaštita -> I get 'Zaštita' result Čep -> I get 'Čep' result čep -> I get nothing (diacritic letter in the first place, case sensitive) -
Migrate Flask microservice code to Django
I have 3 microservices written in Flask. How to migrate those Flask microservices code to Django? -
Django - order fields within a queryset
Simplified Models: Class Product(models.Model): name = models.CharField(max_length=250) launch_date = models.DateField(blank=True) Class Collection(models.Model): name = models.CharField(max_length=250) products = models.ManyToManyField(Product, related_name="collections", blank=True) Say I want to return a Collection query like Collection.objects.all() but I want all products within that queryset to be ordered by launch_date, how would I do this? Just adding order_by on product on the above query does not work as that just orders the collections, but doesn't actually order the products within the collection -
When i upload an image in the database..the last image should get deleted and new one should get saved
models.py def content_file_name(instance, filename): extension = filename.split(".")[-1] ext2 = filename.replace(extension, "png") og_filename = ext2.split('.')[0] og_filename2 = ext2.replace(og_filename, str(instance.id)) path = os.path.join(settings.BASE_DIR, 'static/images/profile',) dir_list = os.listdir(path) for i in dir_list: if i == og_filename2: dir_list.pop(-1) dir_list.append(og_filename2) return os.path.join('profile/', og_filename2) return os.path.join('profile/', og_filename2) class User(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) profile_dp = models.ImageField(upload_to = content_file_name ,null=True, blank=True) profile_url = models.CharField(max_length=200) Through the content_file_name() function when i upload an image its name should change to this format user's id.png. and then when i again upload an image to the same field the last image should get deleted and the new image with the same name should get uploaded. settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images',) STATIC_URL = '/static/' MEDIA_URL = '/images/' STATIC_DIR = os.path.join(BASE_DIR, 'static',) STATICFILES_DIRS = [STATIC_DIR] -
django creating new record when update existing record
My models of Employee registration is as follow. class EmployeeRegistration(models.Model): #Departmental Details EmpId = models.IntegerField(verbose_name='EmpId') EmpImage = models.ImageField(default='default.png',upload_to='profile_pic/%Y/%m/%d') EmpSafetyCard= models.ImageField(default='default.png',upload_to='profile_pic/%Y/%m/%d') Site = models.ForeignKey(Site,on_delete=models.CASCADE,max_length=150,verbose_name='Site') Department = models.ForeignKey(Department,on_delete=models.CASCADE,max_length=150,verbose_name='Department') Category = models.ForeignKey(Category,on_delete=models.CASCADE,max_length=150,verbose_name='Category') Designation = models.ForeignKey(Designation,on_delete=models.CASCADE,max_length=150,verbose_name='Designation') PfApplicable = models.BooleanField(default = True,verbose_name='Pf Applicable') EsiApplicable = models.BooleanField(default = True,verbose_name='Esic Applicable') Uan = models.PositiveIntegerField(null = True,verbose_name='Uan') Esic = models.PositiveIntegerField(null = True,verbose_name='Esic') AttendenceAward = models.BooleanField(default = True) AttendenceAllowance = models.BooleanField(default = True) ProfesionalTax = models.BooleanField(default = False) Name = models.CharField(max_length=150,verbose_name='Name') Father = models.CharField(max_length=150,verbose_name='Father') Dob = models.DateField() Male = models.BooleanField(default = True) Female = models.BooleanField(default = False) MaritalStatus = models.BooleanField(default = True) Address = models.CharField(max_length=200,verbose_name='Address') Aadhar = models.PositiveIntegerField(null=True) pan = models.CharField(max_length=10) choices = [('Working','WORKING'),('NotWorking','NOT WORKING'),('Leave','Leave')] Status = models.CharField(choices=choices,blank = False,max_length=10,verbose_name='Status') Doj = models.DateField(default = date.today) Doe = models.DateField(blank = True,verbose_name = 'Doe',null = True) def __str__(self): return f'{self.Name}({self.EmpId})' def save(self): super().save() empimg = Image.open(self.EmpImage.path) empsafetycard = Image.open(self.EmpSafetyCard.path) if empimg.height>300 or empimg.width>300: output_size = (300,300) empimg.thumbnail(output_size) empimg.save(self.EmpImage.path) if empsafetycard.height>300 or empsafetycard.width>300: output_size = (300,300) empsafetycard.thumbnail(output_size) empsafetycard.save(self.EmpSafetyCard.path) This is my View for regitering new employee def registration_view(request,id=0): form = newEmployeeForm() record = RecordsId.objects.all() empid = 0 for data in record: empid = data.EmpId emp_id = empid+1 if(empid!=0 or empid==0): get_emp = RecordsId.objects.get(EmpId=empid) EmployeeId={"EmpId":emp_id} print(request.POST) if(request.method == 'POST'): if(id==0): form = newEmployeeForm(request.POST … -
Issue with UrlPattern for Ckeditor in Django Admin
I am trying to integrate Ckeditor into the Django Admin Panel. I'm not sure if I have misconfigured a urlpattern or if something else is wrong. I'm learning Django so it is a possibility. Here is my Core urls.py core urls.py here is my home urls.py home urls.py and here is my settings settings.py Here is the results of visiting the admin page to add a post. Post Page I really appreciate any help or guidance you have to offer. Kindest Regards, Jared -
TypeError: an integer is required (got type str) when running migrations or running tests
I modified an existing model as below: It was originally this class AppAssessment(models.Model): contact_uuid = models.CharField(max_length=255) step = models.IntegerField(null=True) optionId = models.IntegerField(null=True, blank=True) user_input = models.TextField(null=True, blank=True) title = models.TextField(null=True, blank=True) description = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return ( f"UUID: {self.contact_uuid} | Step: {self.step} | OptionID: {self.optionId} \n" f"| User_Input: {self.user_input} | Title: {self.title} \n" f"| Created_at: {self.created_at}" ) But I changed contact_uuid to contact_id and changed the model type: class AppAssessment(models.Model): contact_id = models.UUIDField() step = models.IntegerField(null=True) optionId = models.IntegerField(null=True, blank=True) user_input = models.TextField(null=True, blank=True) title = models.TextField(null=True, blank=True) description = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return ( f"UUID: {self.contact_id} | Step: {self.step} | OptionID: {self.optionId} \n" f"| User_Input: {self.user_input} | Title: {self.title} \n" f"| Created_at: {self.created_at}" ) In views.py I was already storing the entries as strings store_url_entry = AppAssessment(contact_uuid=contact_uuid, title=title, description=description, step=step, user_input=value, optionId=optionId) store_url_entry.save() I've dropped the database and recreated it but it still fails. I've also restarted the virtual env but it doesn't help. The error I see is this: File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 2343, in to_python return uuid.UUID(**{input_form: value}) File "/usr/local/lib/python3.6/uuid.py", line 137, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') TypeError: an integer is required (got type str) Thanks for … -
does not appear to have any patterns in it. If you see the 'urlpatterns' variable valid patterns in file then issue is caused by circular import
Error while running is :- Ltd\Desktop\Django\GENIE\TBL\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. In Main Url file from django.contrib import admin from django.urls import path,include,re_path urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^',include('TBL.urls')) ] In TBL App urls.py file from django.urls import re_path from TBL import views urlspatterns=[ re_path(r'^domain/$',views.DomainLApi), re_path(r'^domain/([0-9]+)$',views.DomainLApi) ] In TBL App view.py file import django from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from TBL.models import Domain from TBL.models import Context from TBL.models import Features, ContextSettingRule from TBL.serializers import DomainSerializer, ContextSerializer, FeaturesSerializer, ContextSettingRule # Create your views here. @csrf_exempt def DomainLApi(request,id=0): if request.method=='GET': domains=Domain.objects.all() domain_serializer=DomainSerializer(domains,many=True) return JsonResponse(domain_serializer.data,safe=False) elif request.method=='POST': domains_data=JSONParser().parse(request) domain_serializer=DomainSerializer(data=domains_data) if domain_serializer.is_valid(): domain_serializer.save() return JsonResponse("Added Successfully",safe=False) elif request.method=='PUT': domain_data=JSONParser().parse(request) domain=Domain.objects.get(DomainId=domain_data['Domain_ID']) domain_serializer=DomainSerializer(domain,data=domain_data) if domain_serializer.is_valid(): domain_serializer.save() return JsonResponse("Uploaded !!",safe=False) return JsonResponse("Failed to Update.", safe=False) elif request.method == 'DELETE': domain = Domain.objects.get(Domain_ID=id) domain.delete() return JsonResponse("Deleted Successfully", safe = False) -
Django Form Reject Input if Specific User uses the same name twice and notifies user
In Django, I have a custom form that creates an "email group" within a modal. The email group model contains a number of attributes, including a unique ID for the email group, for the user, etc. The idea is that a specific user shouldn't be able to enter the same name twice - and if they do, they should be notified. It seems right now like the form is rejecting inputs that duplicate email_name (it doesn't get added to the database), but the message it's returning is New Email Added. I've also been trying to get the email to show within the modal but that's a whole other issue. form.py class EmailCreateForm(ModelForm): class Meta: model = UserEmail fields = ['email_name'] constraints = [ models.UniqueConstraint(fields=['user_id', 'email_name'], name='unique_name') ] def __init__(self, *args, **kwargs): super(EmailCreateForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor self.fields['email_name'].widget.attrs['rows'] = 1 views.py def email(request): if request.method == 'POST': form = EmailCreateForm(request.POST, instance=request.user) if form.is_valid(): form.save() messages.success(request, f'New Email Added') return redirect('project-emails') else: messages.error(request, f'Email not Added') return redirect('project-emails') else: form = EmailCreateForm() return render(request, 'project/emails.html', {'form': form}) part of template emails.html {% if messages %} {% for message in messages %} <div class="alert id = 'email-message'"> {{ message|escape }} … -
converting text file to comma delimited csv file or json file
I have a text file that I want to convert to a comma-delimited CSV file, where the first row(headers) are the MySQL table fields. My text file looks like this id purchase-date last-updated-date status 305-0847312-2761164 2022-04-11T22:23:27+00:00 2022-04-11T22:23:31+00:00 Pending 028-3270261-2897162 2022-04-11T22:17:27+00:00 2022-04-11T22:17:30+00:00 Pending 028-8245400-1649940 2022-04-11T22:15:29+00:00 2022-04-11T22:15:32+00:00 Pending 028-2661715-2120359 2022-04-11T21:57:24+00:00 2022-04-11T21:57:28+00:00 Pending 303-9076983-4225163 2022-04-11T21:53:52+00:00 2022-04-11T21:53:55+00:00 Pending 304-7440363-0208337 2022-04-11T21:49:14+00:00 2022-04-11T21:49:17+00:00 Pending 302-2070657-8345128 2022-04-11T21:30:12+00:00 2022-04-12T01:32:20+00:00 Shipped What I want to achieve is a file like this id, purchase-date, last-updated-date, status 305-0847312-2761164, 2022-04-11T22:23:27+00:00, 2022-04-11T22:23:31+00:00, Pending 028-3270261-2897162, 2022-04-11T22:17:27+00:00, 2022-04-11T22:17:30+00:00, Pending I need this file to save in the database where the first row are the column names I tried pandas read_file = pd.read_csv("reports/report.txt") read_file.to_csv("reports/report.csv", index=None, sep="\n") exit() BUt I got error pandas.errors.ParserError: Error tokenizing data. C error: Expected 2 fields in line 194, saw 4 Questions How do you convert this text file to a comma delimited csv file? Or a more preferable way, to convert this txt file to json file, saving this to db is much easier if its in json format, something like: [ { id: 305-0847312-2761164, purchase_date: 2022-04-11T22:23:27+00:00 }, { id: 305-0847312-2761165, purchase_date: 2022-05-11T22:23:27+00:00 }, ....................... ] with open(file) as f: for i in f: myTable.objects.create(id=id,**i) -
Django4: Create an object for a third model for each item in many to many relation
I have these three models which depend on another. I need a mechanism that creates a result for each item in Pipeline.ms_file. When I assign a file to the pipeline, it should be processed and the results object should be created. When I remove that file from the pipeline the Result instance should be deleted. I can probably do that with signals. Though it would get a bit ugly when the file is removed from the pipeline. I would have to loop through all the results and would have to identify the ones that are now invalid. I wonder if there is a better way to do this. Maybe I should not use the ManyToMany field in that situation at all? The actual situation is a bit more complicated. Actually, the a target list is assigned to the pipeline and when a file is created a result is created for each combination of targets and files. The main problem is the deletion, because when the pipeline instance is saved, the information about removed files is gone. class MsFile(models.Model): name = models.CharField(max_length=300) instrument = models.ForeignKey(Instrument, on_delete=models.SET_NULL, null=True) method = models.ForeignKey(Method, on_delete=models.CASCADE, null=True) # file = models.FileField() def __str__(self): return self.name class … -
Django Login. Form without route is working. Does Django autodetect login forms?
I'm cleaning up my code base and I've no idea why I can! login with this code: <div> <form method="post"> {% csrf_token %} <div > <label >Username</label> <input type="text" name="username" /> </div> <div > <label >Password</label> <input type="password" name="password" /> </div> <button type="submit">Submit</button> </form> </div> Why this is working? Does Django autodetect a form with username and password as loginform? There is no route at post. Or did I define something somewhere which I cant find anymore? -
Clone django forms with RichTextUploadingField with javascript
I have forms with model like below: class Teststep(models.Model): testcase = models.ForeignKey(TestCasetest , null=True , on_delete= models.CASCADE) number = models.CharField(max_length=100 , null = True , blank = True) description = models.TextField(blank=True, null=True) condition = RichTextUploadingField(config_name="default",blank=True,null=True) remark = RichTextUploadingField(config_name="default",blank=True,null=True) modify_history = models.TextField(blank=True, null=True) def __str__(self): print(self.testcase.name,type(self.testcase.name)) name = self.testcase.name+'-('+str(self.number)+')' return name forms below: class Teststepform(forms.ModelForm): class Meta: model = Teststep fields = ['description','condition','remark','modify_history'] i use views.py to send form above to templates ,and i try to use javascript to clone when i press button to create new form <div class="form-group"> {{teststepform.media}} <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th>{% trans "number" %}</th> <th>{% trans "description" %}</th> <th>{% trans "condition" %}</th> <th>{% trans "remark" %}</th> <th>{% trans "modfiy_history" %}</th> </tr> </thead> <tbody id="formset-teststep"> <tr id="teststepform-list" class=""> <td id="number"></td> <td id="description">{{teststepform.description}}</td> <td id="condition">{{teststepform.condition}}</td> <td id="remark">{{teststepform.remark}}</td> <td id="modify_history">{{teststepform.modify_history}}</td> </tr> </tbody> </table> </div> <div class="form-group"> <div class="col-md-1 col-lg-1"> <button type="submit" name="save" value="save" class="btn btn-success btn-lg">{% trans "Save" %}</button> </div> </div> This is my javascript to clone <tr id="formset-teststep"> // teststep button var add_teststepform = document.getElementById('add_teststepform') add_teststepform.addEventListener('click',AddTeststep) function AddTeststep(event){ event.preventDefault() const teststep_body = document.getElementById('formset-teststep') var teststep_tr_list = document.getElementById('teststepform-list').cloneNode(true) var total_lenth = (document.getElementsByClassName('grident-form-teststep')).length teststep_tr_list.setAttribute('class','grident-form-teststep') teststep_tr_list.setAttribute('id','id_teststep_show_'+total_lenth.toString()) teststep_body.append(teststep_tr_list) } But after that my forms.description and forms.condition both are not … -
javascript: i want to get individual items id when click on a button using javascript
when i click on the button it shows in the console - undefined i have tried creating an event listener on click but it still does not work as expected product_detail.html {{course.title}} <li><button class="btn_adcart update-cart data-course={{course.id}}" data-action="add">Add to Cart</button></li> cart.js const updateBtns = document.getElementsByClassName('update-cart') for (let i = 0; i < updateBtns.length; i++){ updateBtns[i].addEventListener("click", function(){ let productId = this.dataset.course let action = this.dataset.action console.log('productId', productId, 'action', action); }) } -
error when testing django app with pytest, no app installed with this label
I am implementing tests for my django application with pytest. I added the decorator @pytest.mark.django_db to my test_function so i could access my database (sqlite3). When i run a simple assert response.status_code an error occurs and tells me that there are no application installed with the label. I precise that my application appears in INSTALLED_APPS settings. Complete error message: (env) Inspiron-3793:~/Python-OC-Lettings-FR$ pytest lettings/ ============================================================== test session starts =============================================================== platform linux -- Python 3.9.7, pytest-7.1.1, pluggy-1.0.0 -- /home/arthur/openclass/P13/Python-OC-Lettings-FR/env/bin/python3 cachedir: .pytest_cache django: settings: oc_lettings_site.settings (from ini) rootdir: /home/arthur/openclass/P13/Python-OC-Lettings-FR, configfile: setup.cfg plugins: django-3.9.0, mock-3.7.0 collected 1 item lettings/tests/unit/tests.py::TestLettings::test_index ERROR [100%] ===================================================================== ERRORS ===================================================================== ___________________________________________________ ERROR at setup of TestLettings.test_index ____________________________________________________ self = <django.db.migrations.state.StateApps object at 0x7f3fd35b0b50>, app_label = 'oc_lettings_site' def get_app_config(self, app_label): """ Import applications and returns an app config for the given label. Raise LookupError if no application exists with this label. """ self.check_apps_ready() try: > return self.app_configs[app_label] E KeyError: 'oc_lettings_site' env/lib/python3.9/site-packages/django/apps/registry.py:155: KeyError During handling of the above exception, another exception occurred: request = <SubRequest '_django_db_marker' for <Function test_index>> @pytest.fixture(autouse=True) def _django_db_marker(request): """Implement the django_db marker, internal to pytest-django. This will dynamically request the ``db``, ``transactional_db`` or ``django_db_reset_sequences`` fixtures as required by the django_db marker. """ marker = request.node.get_closest_marker("django_db") if marker: transaction, … -
Is there a way to alter UserPassesTestMixin?
I'm trying to create a moderator in my Django blog. I'm using classed-based views with the UserPassesTestMixin so that a user's post can only be updated by them. Is there way to override some features of UserPassesTestMixin using the AccessMixin so that if another user has permissions, they too can update original posters blog? Is this supported? Or should I use function based views instead? -
Download a PDF from url, edit it an render it in Django
I need to download a PDF form Azure Storage, edit the file (extract an specific page) and render it from a Django view, I have this: def download_desprendible_user(request): if request.method == 'POST': file_location_in_blob = request.POST.get('pdf_download') url = get_blob_url(file_location_in_blob) file = urllib.request.urlopen(url) reader = PdfFileReader(io.BytesIO(file.read())) for i in range(0, reader.getNumPages()): content = "" content += reader.getPage(i).extractText() + "\n" ResSearch = re.search(id, content) if ResSearch is not None: page = i break pdfWriter = PdfFileWriter() pdfWriter.addPage(reader.getPage(page)) with io.BytesIO() as out: pdfWriter.write(out) But I can't achieve to render the pdf from the Django view, I don't want to use open because I had issue in production by doing this. -
Django form instance initial image
I am trying to make an instance of a Django form that has an initial picture uploaded. This picture is coming from an instance of a form that has already been submitted. The initial values are working for every case except the image. Does anybody have any idea how I might fix this? This is in my views.py. title = Recipe.objects.get(id=pk) t = title.title recipe_image = title.recipe_image cooktime = title.cooktime servings = title.servings culture = title.culture form = RecipeForm(initial={"title": t, 'recipe_image': recipe_image, 'servings': servings, 'cooktime': cooktime, 'culture': culture, 'visibility': False}) context = { "title": title, "pk": pk, "form": form, } return render(request, "Recipe/create_recipe.html", context) -
Django : display data got via ajax call on html
I am quite new to django and struggling to do something simple.I'm building map with data visualisation,I am showing the user a simple svg-map that will help in doing the following: 1-user will click on one of the areas of the map . 2-data visualisation of that specific selected area will be displayed. First,i send the name of the area( that i got from svg path ) with Jquery,ajax call to python, this is my main.js/index.html/style.css : $(document).ready(function(e) { $('path').on('focus', function(e) { e.preventDefault(); $('#selection').html($(this).attr('name')); var gov = $('#selection').text(); console.log(gov) var obj = { gov} $.ajax({ type: 'POST', url: '/map/', contentType: 'application/json; charset=utf-8', //EDITED data: gov, success: function(data) {}, error: function(rs, e) { } }); }); }); Then, i send the name to python, This is how my views.py looks like: [views.py][1] here Every time i select on region , the data that i want to display is printed in terminal data of the selected area is printed but not sent to html but i m struggling to send it to the html page,it doesn't work,the context variable is empty . Can you please help ? -
how to check out selected product on my cart in Django
Hy everyone, I create simple ecommerce project on Django and my problem is I click add to cart button and then add multiple product in cart then I will checkout so all products checkout but I need specific product for checkout , so any body solve this Thanks -
Check if request.user has a Valid Refresh Token?
I have this Python3.7 Django 3.2.13 code: from django.contrib.auth.tokens import default_token_generator @api_view('POST') @permission_classes([IsAuthenticated]) def sign_out(request): # Get the refresh_token from POST data... refresh_token = request.data.get("refresh") # We want to know if the refresh_token is associated with the current user? is_refresh_token_valid = default_token_generator.check_token(request.user, refresh_token) Now, this always returns False. This check_token works when I use it on an access token instead. Is there way to get this to function with a refresh token instead? Thanks! Erik W. -
Incorrect csv format when using ImportExportModelAdmin
I'm trying to upload the csv file below but it's only uploading some colummns and then some of those values are empty. Prior to this, I was receiving a error: ``` self.fields[f] for f in self.get_import_id_fields() KeyError: 'id'``` which I fixed by using advice from here basically saying django import-export uses "id" by default. So, create a resources.py file - where I declare settings for import and export. And as an exception, declare "id", which is what I did and the upload worked... BUT it's incorrect and just wrong. Part of the CSV Customer ID,Customer Name,Latitude,Longitude,town,region,country C00001,Valentino Solomon,57.13514,-2.11731,Aberdeen,Aberdeen City,Scotland C00002,Luna Armstrong,57.13875,-2.09089,Aberdeen,Aberdeen City,Scotland C00003,Jaylen Crane,57.101,-2.1106,Aberdeen,Aberdeen City,Scotland C00004,Christopher Fritz,57.10801,-2.23776,Milltimber,Aberdeen City,Scotland Customer Model class Customer(models.Model): customer_id = models.CharField(primary_key=True, max_length=150) customer_name = models.CharField(max_length=150) longitude = models.FloatField(null=True) latitude = models.FloatField(null=True) town = models.CharField(max_length=150) region = models.CharField(max_length=150) country = models.CharField(max_length=150) #Admin.py from django.contrib import admin from systemx.models import Customer, Demand, Product from import_export.admin import ImportExportModelAdmin from systemx.resources import * class DataImportExportAdmin(ImportExportModelAdmin): resource_class = PropertyAdminResource list_display = ['customer_id', 'customer_name', 'longitude', 'town', 'region', 'country'] # class DataImportExportAdmin(ImportExportModelAdmin): # list_display = ['customer_id', 'customer_name', 'longitude', 'town', 'region', 'country'] admin.site.register(Customer, DataImportExportAdmin) Resource.py file: from import_export import resources from .models import Customer class PropertyAdminResource(resources.ModelResource): class Meta: model = Customer exclude = ('id',) …