Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What should I use, request params or path converters in DRF get request?
I want to pass a pk to a get method in a APIView class, but I am confused whether I user request params or path converters for that. -
How to send articles a mail in Django
I am having an issue about sending out newsletters in Django. I want to send out series of posts or articles as one newsletter email but, what I have currently is that mails are sending out one after the other i.e each post is sent one after the other. I want my mail to be sent once, below is my code models.py class NewsLetters(models.Model): title = models.CharField(max_length=35) subject = models.CharField(max_length=150) image = models.ImageField(upload_to='uploads/') link = models.URLField(blank=True, null=True) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject + " " + self.created_at.strftime("%B %d, %Y") class Meta(): verbose_name_plural = 'Newsletters' def img_url(self): if self.image: return self.image.url def send(self, request): subscribers = Subscribers.objects.filter(confirmed=True) email_data = [] for sub in subscribers: args = { 'title':self.title, 'content':self.content, 'image':self.image } email_data.append(args) html_message = render_to_string('website/newsletter.html', email_data) plain_message = strip_tags(html_message) from_email = settings.FROM_HOST mail.send_mail(self.subject, plain_message, from_email, [sub.email,], html_message=html_message) admin.py def send_newsletter(modeladmin, request, queryset): for newsletter in queryset: newsletter.send(request) send_newsletter.short_description = "Send selected Newsletters to all subscribers" @admin.register(NewsLetters) class NewsLetterAdmin(admin.ModelAdmin): actions = [send_newsletter,] newsletter.html {% if news %} {% for n in news %} <div class="col-md-4"> <p>n.title</p> <p>n.image</p> <p>n.content</p> </div> {% endfor %} {% endif %} -
How can i filter with checkboxes
I want to filter with checkboxes from column values Code: cursor.execute("[Prueba].[dbo].[N]" + "'" + str(format_min) + "'," + "'" + str(format_max) + "'") qs = cursor.fetchall() it returns the values image with values <input class="form-check-input" type="checkbox" id="h1" name="h1"> <label class="form-check-label" for="h1"> <b>H1</b> </label> <br /> <input class="form-check-input" type="checkbox" id="h2" name="h2"> <label class="form-check-label" for="h2"> <b>H2</b> I want to click on checkbox h1 and filter by h1 machines -
React JS - Module build failed (from ./node_modules/babel-loader/lib/index.js):
I'm having the following error and can't find out what I'm doing. whatever I try it gives this error. Please help me. Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: Plugin/Preset files are not allowed to export objects, only functions. In E:\Neptune\node_modules\babel-preset-es2015\lib\index.js my files are: Index.JS import React from 'react'; import ReactDOM from 'react-dom'; import reportWebVitals from './reportWebVitals'; import App from './App' import './components/main.css' ReactDOM.render( <React.StrictMode> <App/> </React.StrictMode>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) reportWebVitals(); Package.json { "devDependencies": { "@babel/core": "^7.14.3", "@babel/preset-env": "^7.14.2", "@babel/preset-react": "^7.13.13", "babel-loader": "^8.2.2", "babel-plugin-transform-class-properties": "^6.24.1", "webpack": "^5.37.1", "webpack-cli": "^4.7.0" }, "dependencies": { "@testing-library/jest-dom": "^5.12.0", "@testing-library/react": "^11.2.6", "@testing-library/user-event": "^12.8.3", "babel-preset-es2015": "^6.24.1", "bootstrap": "^4.6.0", "prop-types": "^15.7.2", "react": "^17.0.2", "react-bootstrap": "^1.6.0", "react-dom": "^17.0.2", "react-router-dom": "^5.2.0", "react-scripts": "4.0.3", "styled-components": "^5.3.0", "web-vitals": "^1.1.2" } } .bablerc { "presets": ["@babel/preset-env", "@babel/preset-react", "es2015", "stage-0", "react"], "plugins": ["transform-class-properties"] } Webpack.config.js module.exports = { module: { rules: [{ test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader?cacheDirectory=true', } }] } }; -
TemplateSyntaxError at Posts, First Django Project
I'm trying to make my first Django project. I'm making the first post and in the the tutorial, it goes like this in HTML: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1> This is our list of post</h1> {% for post in post_objects &} {{ post }} {% endfor %} </body> </html> Now that I'm trying to run the server and check the page so I can see the 'This is our list of post', there is an error. Error during template rendering In template C:\Users\Invoker\Dev\trydjango\src\posts\templates\posts\index.html, error at line 10 Invalid block tag on line 10: 'endfor'. Did you forget to register or load this tag? 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 </head> 6 <body> 7 <h1> This is our list of post</h1> 8 {% for post in post_objects &} 9 {{ post }} 10 {% endfor %} 11 </body> 12 </html> What should I do? -
Django models: implement
I am trying to build a Django app that allows the user to crawl a website, collect all the internal links of said website and then the user can create a number of variants on this list and make changes on those links to simulate a different website architecture (for example, delete some links, add a link, etc.). I need to keep the original link list and then be able to compare it with each variant to show differences (i.e. +50% removed links, -10% links in footer, etc.) I am not sure what the ideal model structure would be in this case. I have already created the models to save each crawl the user does and the model to store the crawled links: models.py # Django from django.db import models from django.urls import reverse from django.utils.timezone import now # Owner from apps.project.models import Project, Experiment CRAWL_STATUS = {(1, "Running"), (2, "Paused"), (3, "Finished")} # Custom model managers class CrawlManager(models.Manager): def new_crawl(self, exp_id, status): # get experiment instance experiment = Experiment.objects.get(id=exp_id) # save new crawl in DB crawl = self.create(experiment=experiment, status=status) return crawl class CrawledLinksManager(models.Manager): def new_link(self, crawl, source_url, target_url, nofollow): link = self.create( crawl=crawl, source_url=source_url, target_url=target_url, nofollow=nofollow ) return link … -
Merge each friend's tweets and own feeds, return top 100 tweets ordered by post date
enter image description here Filter out user's friends. Filter each friend's top 100 tweet ordered by post date. Filter user's own feeds. Merge each friend's tweets and own feeds, return top 100 tweets ordered by post date -
Django rest framework API is not responding when I run server with ASGI
I used channels in my Django project and when I changed WSGI to ASGI then some of my APIs stopped responding. 1. if customer_object.status == None: 2. new_user, created = User.objects.get_or_created(username="abc", role_id=Role(1)) 3. new_user.set_password('abc') 4. temp_object = User.objects.filter(id = self.request.data['user_id']).first() 5. new_user.restaurant_id = temp_object.restaurant_id 6. new_user.save() 7. url = settings.API_URL+"/api/v1/auth/sign_in/" 8. response = requests.post(url, data={'username': f"customer1", 'password': '123456'}) In the above-mentioned code at line 8 project not responds. I used the python async-await method like response = await requests.post(url, data={'username': f"customer1", 'password': '123456'}) It returns coroutine object and I try to get data from it by using response.text but it says couroutine object has no attribute text. Please answer if anyone came accros this kind of situation. -
TemplateDoesNotExist: account/register.html
I am tryinging to create my own customized registration form. I already created register.html file in the templates folder, and I set the templates setting like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [Path(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTH_USER_MODEL= "account.Account" This is views.py for registration_view: from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from account.forms import RegistrationForm def registration_view(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) return redirect('home') else: context['registration_form'] = form else: #GET request form = RegistrationForm() context['registration_form'] = form return render(request, 'account/register.html', context) and this is my urls.py: from django.contrib import admin from django.urls import path from personal.views import ( home_screen_view, ) from account.views import ( registration_view, ) urlpatterns = [ path('admin/', admin.site.urls), path('', home_screen_view, name="home"), path('register/', registration_view, name="register"),] I am watching this tutorial Can someone please tell me how can I solve this issue? -
add_error(fieldname, ...) in Django Rest Framework (DRF)
I have a model serializer like this: class MySerializer(ModelSerializer): class Meta: model = MyModel fields = ('myfield', 'otherfield') I need to check a cross-field condition, say, x.myfield > x.otherfield. (There are actually several otherfields and several conditions.) I need detailed and easy-to-grasp human-readable error messages. I currently generate them (actually only the first) in MySerializer.validate() via raise ValidationError(message), but then the message comes under the non-field-errors key, which is ugly and difficult for the users. It would be much nicer to attach it to myfield. In Django forms, I would use add_error('myfield', ...), but I could not find a similar thing in rest framework. What is a suitable idiom here? -
Django's Get Queryset as Generic Function
Can It be possible if I create a common get_queryset and use it for all the class. If yes, what can be the drawback of this. -
How to pass custom input field inside a form to Django CreateView and to the Model
I will keep the description as short as possible So frontend an image is compressed Via CompressorJs In HTML: <form class='form' action="" method="post" enctype="multipart/form-data"> {%csrf_token%} {{form.as_p}} <p> <input name='photo_1' id='id_photo_1' value='${base64data}'> </p> <!-- this will be created --> <button>Submit</button> </form> <div class='Uploader'> <input type="file" id="upload" accept="image/*"> </div> <script> document.getElementById('upload').addEventListener('change', (e) => { var file = e.target.file new Compressor(file, { quality: 0.5, maxWidth:910, success(result) { var reader = new FileReader(); reader.readAsDataURL(result); reader.onloadend = function() { var base64data = reader.result; var img1 = `<p> <input name='photo_1' id='id_photo_1' value='${base64data}'> <img src='${base64data}' > </p>`; $(".form").append(img1); } }, error(err) { console.log(err.message); }, }); } }); </script> In Models.py: class Card(models.Model): photo_1 = models.ImageField(upload_to='photos/cards/%Y%m/', blank=True) In Views.py: class AddCardView(CreateView): model=Card form_class = CardForm template_name='card/addcard.html' def form_valid(self, form): form.instance.poster = self.request.user return super(AddCardView, self).form_valid(form) In Form.py before: fields=(photo_1,) In Form.py after: fields=(#I removed it so the createview generated one doesn't show up in the html page) My original plan is to set the createView generated input field to hidden, Then replace the value with JS, But then I learned you can't change the value of file=input due to security reasons, The default Id and name for the CreateView generated file=input is id_photo_1 and photo_1, So I set … -
Django REST: projects vs apps
I am developing a REST API using Django Rest Framework. This API deals with a high number of resources that are divided into "business areas". I should be developing this API so that the resources from the different business areas are independent and can be used individually in contexts other than the project I am working on. My question is: should I be using different DRF projects, or different Django apps for each business area? I.e., Should I organize like this: |- businessarea1_api_project |- core_app |- api_documents |- businessarea2_api_project |- core_app |- api_documents Or like this: |- big_api_project |- businessarea1_api_app |- businessarea2_api_app I am assuming that using different apps helps me in the sense that I can use Django's reusable apps to create a package for each business area, and then I can install them in the projects they are required. Using different projects helps in the sense that i have an individual API running for each business area that can be called whenever needed, together with other APIs or not. Is this it? Are there other factors that I should be considering? Which one is better? Thank you! -
add django native authentication as the second layer of authentication, after user login via LDAP authentication
I have used Django2 to build a web app. I configured LDAP login as the auth method to login to the website. But now the client need another layer to authenticating the user logged in by LDAP. They want to map the user logged in using LDAP to the django user table, and query the user type to guide the different user to different pages. I have already disabled django native auth to give way to ldap auth, how could I add it back as the second layer to check user identify after user logged in by ldap? settings.py: AUTHENTICATION_BACKENDS = ( 'bookdb.backends.LDAPBackend', ('django.contrib.auth.backends.ModelBackend'), ) INSTALLED_APPS = [ 'django.contrib.auth', ] backends.py from django.contrib.auth import get_user_model UserModel = get_user_model() class LDAPBackend: def authenticate(self, request, username=None, password=None, **kwargs): now = datetime.datetime.now() text = str(now.day) + 'ls@bBk3y' def computeMD5hash(my_string): m = hashlib.md5() m.update(my_string.encode('utf-8')) return m.hexdigest() username = username.lower() try: headers = {'Authorization': computeMD5hash(text).upper()} body = {"username": username, "password": password} response = requests.post(url="https://XXX/REST/json/service/loginStaff", json=body, headers=headers) result = response.json() if result['code'] != "OK": return None except Exception as e: print(e) user, created = UserModel.objects.get_or_create(username=username) return user def get_user(self, user_id): try: return UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None What I want to achieve is, when user login … -
Django Error ''WSGIRequest' object has no attribute 'Players''
I am trying to create a detailed page for each player from the Players model, but for some reason, I am getting this error. How can I fix this? My models.py: class Players(models.Model): name = models.CharField(max_length=255) position = models.CharField(max_length=255) image_url = models.CharField(max_length=2083) My views.py: def PlayerDetailView(request, player): model = Players player = request.Players context = {'player' : player} return render(request, 'player_detail.html', context) My player_detail.html: {% extends 'base.html' %} {% block content %} <h1>{{ player.name }}</h1> <img class="card-img-top" width="20" height="300" src="{{ player.image_url }}"> {% endblock %} My urls.py: path('players/<str:player>', views.PlayerDetailView, name='player-detail'), -
Django Reverse for '' not found
while working with Django URLs I ran into a problem that i cannot understand. I will bring 2 examples that are implemented in a similar way but only one is working. The dashboard and users-list (dashboard not working) urlpatterns = [ path('', views.home, name='home'), path('dashboard/', views.dashboard, name='dashboard'), path('users-list/', views.users_list, name='users-list'), ] The html of both links <li class="sidebar-item"> <a class="sidebar-link waves-effect waves-dark sidebar-link" href="{% url 'dashboard' %}" aria-expanded="false"> <i class="mdi mdi-av-timer"></i> <span class="hide-menu">Dashboard</span> </a> </li> <li class="sidebar-item"> <a class="sidebar-link waves-effect waves-dark sidebar-link" href="{% url 'users-temp-records' %}" <i class="mdi mdi-account-multiple-outline"></i> <span class="hide-menu">Users</span> </a> </li> views @login_required def dashboard(request): user = request.user entranceRecords = None if user.is_staff == True: entranceRecords = TbEntranceRecord.objects.all().order_by("-create_time") else: entranceRecords = TbEntranceRecord.objects.filter(people_name=user.username).order_by("-create_time") page = request.GET.get('page', 1) paginator = Paginator(entranceRecords, 10) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) context = { 'title': 'Dashboard', 'records': data, } return render(request, 'app/common/dashboard.html', context) @ login_required def users_temp_records(request): user = request.user entranceRecords = None if user.is_staff == True: entranceRecords = TbUserTemperatureRecord.objects.all().order_by("-create_time_date") page = request.GET.get('page', 1) paginator = Paginator(entranceRecords, 12) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) context = { 'title': 'Users Records', 'records': data, } return render(request, 'app/admin/users/users_temp_records.html', context) … -
'QuerySet' object has no attribute 'order_by' While accessing model's field in view
I am building a BlogApp and I am stuck on an Error. I am trying to give user an option to order_by the results ( blogs ) with choices. AND i am trying to access model's field in view it is keep showing me. 'QuerySet' object has no attribute 'order_by' models.py ORDER_CHOICES = [ ('date_added':'date_added'), ('likes':likes), ] class Blog(mdels.Model): user = models.ForeignKey(User,models=on_delete.CASCADE) blog_title = models.CharField(max_length=30) blog_description = models.CharField(max_length=300) order_by = models.CharField(max_length=30,choices=ORDER_CHOICES) likes = models.ManyToManyField(User, related_name='likes', blank=True) views.pp def posts(request): post = Blog.objects.filter(user=request.user) if post.order_by == 'date_added' : order_bys = Blog.objects.filter(user=request.user).order_by('-date_added') elif post.order_by == 'likes': order_bys2 = Blog.objects.filter(user=request.user).order_by('likes') context = {'order_bys':order_bys,'order_bys2':order_bys} return render(request, 'posts.html', context) posts.html {% for ord in order_bys %} {{ ord.blog_title }} {% endfor %} {% for ord2 in order_bys2 %} {{ ord.blog_title %} {% endfor %} When i run this code and check browser it is keep showing me :- > 'QuerySet' object has no attribute 'order_by' I have no idea what am i doing wrong. Any help would be much Appreciated. Thank You in Advance. -
Django model can't be render in html
There are some models that I've created but it wont render in template, there are some that are ok so i just use the same method to create the other model but when i try manage.py runserver some of the model is not render, i already do manage.py makemigrations and manage.py migrate, sorry this is my first time asking question here and thank you This is my views.py from django.shortcuts import render from django.http import HttpResponse from .models import FrontPage, DailyQuote, Photo, kate # Create your views here. def front(request): photo = Photo.objects.all() content = {'photo': photo} return render(request, 'front.html', content) def home(request): page = FrontPage.objects.all() args = {'page':page} return render(request, 'Home.html', args) def ytvideos(request): return render(request, 'ytvideos.html') def reading(request): page = FrontPage.objects.all() Fullpage = {'page': page} return render(request, 'Reading.html', Fullpage) def KGK(request): Thekate = kate.objects.all() Therealkate = {'Thekate': Thekate} return render(request, 'KGK.html', Therealkate) This is my HTML {% extends 'front.html' %} {% block head %} {% endblock %} {% block content %} <div class="container-fluid"> {% for i in kate %} <div class="card text-center"> <div class="card-header"> <b>kate</b> </div> <div class="card-body"> <h5 class="card-title">{{ i.katetitle }}</h5> <p class="card-text">{{ i.katecontent }}</p> <a href="#" class="btn btn-primary">Read More</a> </div> </div> {% endfor %} </div> {% … -
How can I change the db_column name of foreign key in Django?
How can I change db_column of Foreign Key in Django? class A(models.Model): it_id = models.CharField('IT ID', max_length=10) class B(models.Model): it_id = models.ForeignKey('A', related_name='item', on_delete=models.PROTECT, db_column='it_id') when I call objects, >>> B.objects.all().values() <QuerySet [{'it_id_id'}:'xxx']> It is 'it_id_id'.... How can I change 'it_id' from 'it_id_id'? -
How can i read the data of headers of a post request sent by python requests?
Looking for the help, I am making a post request to an django application with AUTH-TOKEN in the header and trying to access it on view but not able to. python app import requests import json URL = "http://127.0.0.1:8000/test/api/" request_data ={ 'order':{ 'id':'order.id', 'payment_collection_status': 'transaction_status', 'payment_collection_message': 'transaction_message' } } request_headers = {'AUTH-TOKEN':'webhook_auth_token'} json_data = json.dumps(request_data) response = requests.post(url = URL,headers=request_headers, data = json_data) print(response) django application view from django.shortcuts import render,HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def request_handle(request): if (request.method=='POST'): print(request.body) print(request.META["AUTH-TOKEN"]) return HttpResponse('<h1>hello</h1>') but not able read the header data it is throwing an error: KeyError: 'AUTH-TOKEN' -
manage.py cant find any urls in myapp.urls file. Says something about circular import
I seem to find the following error despite making a number of changes in my app.urls file and in my project.urls file. I can't seem to put my finger on it, here is the code: app.urls file from django.urls import path from . import views urlpatterns = [ path('', views.home_page, name = 'home_page'), ] project.urls file from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Success.urls')), ] views.py file from django.shortcuts import render from django.http import HttpResponse enter code here Create your views here. def home_page(request): hello = 'hello world' return HttpResponse (hello) -
openpyxl.load_workbook takes a long time in Django
I have an excel conversion function in my Django project. I have some processes like a copy of the data from one excel to another excel. While it was working very fast about a week ago, it suddenly started to work slowly in openpyxl.load_workbook part. I do not know why? I am using the remote desktop connection with Azure server. We should use read_only=False because we have to copy operations. Any help would be appreciated. Note: load_workbook parts take about 1 minute. views.py def excel_convert(path, target_path): pythoncom.CoInitialize() save_path = target_path.replace('.xlsx','.xlsm') wb_to_load = openpyxl.load_workbook(target_path, read_only=False, keep_vba=True) ws_to_load = wb_to_load['OCR'] wb = openpyxl.load_workbook(path, read_only=False, keep_vba=True) ws = wb['OCR'] n_row = ws_to_load.max_row n_col = ws_to_load.max_column for row_idx in range(1, n_row + 1): # Iterate through rows for col_idx in range(1, n_col + 1): # Iterate through columns current_cell = ws_to_load.cell(row=row_idx, column=col_idx) value = current_cell.value # Get cell object by row, col ws.cell(row_idx, col_idx).value = value if current_cell.has_style: ws.cell(row_idx, col_idx).font = copy(current_cell.font) ws.cell(row_idx, col_idx).border = copy(current_cell.border) ws.cell(row_idx, col_idx).fill = copy(current_cell.fill) ws.cell(row_idx, col_idx).number_format = copy(current_cell.number_format) ws.cell(row_idx, col_idx).protection = copy(current_cell.protection) ws.cell(row_idx, col_idx).alignment = copy(current_cell.alignment) wb.active = wb['Finansal Tablolar_formul'] wb.save(save_path) wb1 = openpyxl.load_workbook(save_path) wb2 = openpyxl.load_workbook(save_path, keep_vba=True) wb2.save(save_path) excel = win32.gencache.EnsureDispatch('Excel.Application') excel.Visible = True ex = excel.Workbooks.Open(save_path) … -
Heroku deployment: Django site does not exist
Morning, I have deployed my site to Heroku and got the errors as per the attached images. I checked migrations, have SITE_ID=1. Would anybody be able to help to solve this issue? Not sure if related while deploying to Heroku I had an issue with loaddata utf-8 decoder and converted JSON file with online tool to comply with utf-8. I manage to loaddata thereafter but got these errors. thank you[ -
How to write data from Django model to Redis DB using HSET in Python standalone script?
I am trying to write data to redis DB from Django Model using HSET command. Below is a standalone script in Django project:- File name: - insertToRedis.py import redis, django def writeOnRedis(): r = redis.Redis( host='XXX.XXX.XX.XXX', port='6379') #imported model from MainApp.models import Employee allEmployees =Employee.objects.all() # Here I want to insert this all Employees object to Redis with HSET command # But don't know how to do this. # CONDITION: e_name is key and the remaining fields are values #why this condition? --> I want to query Redis DB by E_name if __name__ =='__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Project.settings') django.setup() writeOnRedis() my employee model looks like this:- file name:- models.py from django.db import models class Employee(models.Model) e_id = models.IntegerField() e_name = models.TextField() e_designation = models.TextField() e_salary = models.FloatField() def __str__(self): return self.e_name Question: How can I query the model in such a way that e_name, e_id, e_designation, and e_salary will be the output? And How this Output can be passed to HSET as an input. Version: Django==3.1.7 redis_version:6.0.9 I am a newbie to Django and Redis, any suggestions will help me a lot. Thanks in advance. -
Django does not throw threat exceptions
Could you please help me? Django does not threat the exceptions. I would like when it returns the integrity exception block when this case occur. But nothing, it continue to the else block which raise the integrity exception. I tried with from django.db.utils import IntegrityError and from django.db import IntegrityError datafile = csv.DictReader(datafile, delimiter=',') for row in datafile: row = {k: None if not v else v for k, v in row.items()} try: road_type_id = row['id'] name = row['name'] roadtype = RoadType( road_type_id=road_type_id, name=name, congestion=CONGESTION_TYPES[row['congestion'].lower()], default_speed=row.get('default_speed', None), default_lanes=row.get('default_lanes', None), default_param1=row.get('default_param1', None), default_param2=row.get('default_param2', None), default_param3=row.get('default_param3', None), color=row.get('color', None)) except IntegrityError: e = 'this data already exists in the database' return render(request, template, context={'e': e}) else: roadtype = RoadType( road_type_id=road_type_id, name=name, congestion=CONGESTION_TYPES[row['congestion'].lower()], default_speed=row.get('default_speed', None), default_lanes=row.get('default_lanes', None), default_param1=row.get('default_param1', None), default_param2=row.get('default_param2', None), default_param3=row.get('default_param3', None), color=row.get('color', None))