Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I print a hierarchical view from my self referencing table efficiently?
class Business(models.Model): name = models.CharField(max_length=100, blank=False) class Element(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE, editable=False) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, blank=False) has_children = models.BooleanField(default=False) A Business can have a hierarchy of Element objects as per the schema. A parent value of None means that particular Element instance is a top level Element with no parents of its own. The hierarchy can be nested up to 100 levels deep. Given a company object I need to be able to iterate through all of the that business's elements and output them in a hierarchical view. As seen below: FYI: output of each row is a from a unique Element object Account Income Statement Balance Sheet Assets Liabilities Equity Scenario Actuals Budget -
I am building a Django project of invoice generator and i am Unable to figure out How to send object OR array of objects to the server using AJAX,
In the below code I want to make an ajax request to the contact function in views.py with the object detail, But I am unable to do so also It is showing me CSRF not found. html <button id="submit"> Click here</button> JavaScript detail ={'id':[{Pid: 2, HSN_code: "AE12#@", Rate: 2000, quantity: 1, Price: 0}, {Pid: 3, HSN_code: "1223ABC", Rate: 1000, quantity: 1, Price: 0}, {Pid: 5, HSN_code: "ABC123@", Rate: 1000, quantity: 1, Price: 0}, {Pid: 6, HSN_code: "ABC@123", Rate: 12000, quantity: 1, Price: 0}, {Pid: 7, HSN_code: "ABC@1234", Rate: 3000, quantity: 1, Price: 0}]}, $(document).ready(function(){ $('#submit').click(function(){ console.log(detail) $.ajax({ url:'/contact/', type:'post', data:{'detail':detail, csrfmiddlewaretoken: '{{ csrf_token }' }, dataType:'json', success:function(data){ console.log(data) } }) }) }); Views.py def contact(request): details = request.POST['detail'] print(details) return HttpResponse('true') -
Saving data from Django form into DB
So I have this django model: class Cart(models.Model): ref_code = models.CharField(max_length=15, null=True) owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) items = models.ManyToManyField(PickedProduct) start_date = models.DateTimeField(auto_now_add=True) is_ordered = models.BooleanField(default=False) tot_price = models.DecimalField(max_digits=10, decimal_places=2, default=0) tot_item = models.IntegerField(default=0) note = models.TextField(max_length=500, null=True, blank=True) I am using the Cart model to build my NoteOption form like below: class NoteOption(forms.ModelForm): class Meta: model = Cart fields = ['note'] On my views I have this code (it is incomplete but I am working on it): @login_required def UserCartView(request, **kwargs): user_cart = current_cart(request) note = NoteOption(instance=user_cart) # I don't know what to do here if request.method == 'POST': user_cart.note = note user_cart.save() context = { 'note': note, 'user_cart': user_cart, } return render(request, 'cart/cart.html', context) In my template I have below field: <div class="col-lg-4 mt-5 ftco-animate"> <form method="post" id="my_form"> {{ note|crispy }} </form> </div> and at the end of my template I use an a tag to send a post request like below: <a href="{% url 'precheckout-view' %}" class="btn btn-primary py-3 px-4" onclick="document.getElementById('my_form').submit();">Proceed to Checkout </a> When I first launch the template I am able to get the current stored data from datatbase into Note field. However, when I modify the Note field content and after clicking on "Proceed … -
Django: OperationalError: 'no such table: django_site'
I know there many variatons of this question out there such as No such table as django_site. However, the answers found there have not helped. I am attempting to use the 'django.contrib.sites' app and have included it in the INSTALLED_APPS section of settings.py, I then ran the migrations as follows python manage.py makemigrations spatulaApp #the name of the app I made python manage.py makemigrations python manage.py migrate This gave me the following output: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, sites, spatulaApp Running migrations: Applying sites.0001_initial... OK Applying sites.0002_alter_domain_unique... OK I was hopeful this would be the issue sorted however when logging into the admin panel or generating the sitemap we receive the familiar error: I read on the article linked above that I should comment out the app from settings re-run migrations and then reintroduce the app and run migrations a final time. This has had no effect sadly. I have configured the SITE_ID variable in settings too it is located at the bottom of settings.py and set to a value which exists in the DB ... SITE_ID = 2 It is also worth mentioning that I can create Site objects via the manage.py shell (which … -
Django application fails to deploy on AWS ElasticBeanstalk with 'firebase-admin' library
I am deploying my python/django application to aws elasticbeanstalk. It gets deployed fine if i don't specify 'firebase-admin' library in requirements.txt. But fails to deploy if i add 'firebase-admin' no matter what version in requirements.txt as shown below: Here's my requirements.txt: Django==3.0.1 djangorestframework==3.11.0 psycopg2==2.7.3.1 django-cors-headers==3.2.0 pytz==2017.2 tinys3==0.1.12 apiclient==1.0.3 drf_yasg==1.17.1 google-api-python-client==1.7.3 google-auth==1.5.0 google-auth-httplib2==0.0.3 httplib2==0.11.3 django-rest-auth==0.9.5 oauth2client==4.1.2 geographiclib==1.50 geopy==1.20.0 numpy==1.15.2 pyyaml==5.3.1 And AWS elasticbeanstalk python instance details: Python 3.6 running on 64bit Amazon Linux/2.9.7 Please Help. Thanks -
django allauth template tags not working in custom template
I have added the following code in verification_sent.html file. But template tags do not work on templates. # templates/account/verification_sent.html {% extends 'primary/_base.html' %} {% load i18n %} {% block content %} <h1>{% trans "Verify Your E-mail Address" %}</h1> {% load account %} {% user_display user as user_display %} {% blocktrans %}{{ user_display }}, Confirmation email has been sent to your email address{% endblocktrans %} {% endblock content %} Result shows as below Verify Your E-mail Address AnonymousUser, Confirmation email has been sent to your email address. How can I get the Registered user full name and email address from template file? -
import requests is showing error in python but it is showing in pip3 list
import request is not workingIf I am trying to install requests it is showing requirement already satisfied but If I am trying to import then it is throwing error. Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'requests'. I am running the command pip3 list then it is showing requests 2.23.0. but not able to import. -
Entering Abstract Base User Data - IntegrityError: UNIQUE constraint failed
My goal is to create a user account model with AbstractBaseUser. My application requires data that fits into multiple categories. i.e. name city age because there are a lot of questions to be asked of the user, I have tried separating each category into a separate form, view, and template. For example: models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) Name = models.CharField(max_length=30, unique=False) City = models.CharField(max_length=30, unique=False) Age = models.CharField(max_length=30, unique=False) forms.py: class NameForm(forms.ModelForm): class Meta: model = Account fields = ('Name',) class CityForm(forms.ModelForm): class Meta: model = Account fields = ('City',) class AgeForm(forms.ModelForm): # . . . views.py def NameView(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): Name = request.POST['Name'] form.save() return redirect('City') else: form = NameForm() return render(request, 'account/Name.html', {'form': form}) def CityView(request): if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): City = request.POST['City'] form.save() return redirect('Age') else: form = CityForm() return render(request, 'account/City.html', {'form': form}) def AgeView(request): # . . . I was expecting that I would be able to upload segments of user data in separate pages, however, after uploading the first page "Name", and attempting to upload the second page "City", I get the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: account_account.email … -
Showing certian categories first while iterating
Currently I order my categories by doing "categories": category.objects.order_by('-title') I want to have full control over what order each object appears. I was thinking of having a rank attribute rank = models.IntegerField() however I feel like there could be 2 category objects with a rank of '1' which doesn't make sense. -
Failing To Display Media File Django
I have created a model called Product that takes in an ImageField that will be upload on a function I created: class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=10, default=39.99) image = models.ImageField(upload_to=upload_image_path, null= True, blank=True) def __str__(self): return self.title return self.image def __unicode__(self): return self.title I have also created my MEDIA_ROOT and STATIC_ROOT below is code from main urls however I also defined this two on the settings.py: if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So I am able to upload Image from the admin and it uploads properly to the media_root that I created. When I try calling/displaying the image it render nothing I do not know where I could have made a mistake {% load static %} {{ object.title }} <br/> {{ object.description }} <br/> {{ object.image.url }}<br/> <img src="{{ object.image.url }}" class='img-fluid'/> but the {{ object.image.url }} actually gives me the exact path of the Image which should make sense for the the picture to rendered. This is the the result output that I was telling about, that I'm getting the image url but I can not display the Image -
Django+Supervisor+NGINX on Ubuntu server 18.04. Attempt to write a read only database
I am trying to deploy my website in Django+Supervisor+NGINX on Ubuntu server 18.04. gunicorn.conf.py bind = '127.0.0.1:8000' workers = 3 user = "nobody" Here is my .conf (supervisor): [program:ako] command=/home/oleg/dj/venv/bin/gunicorn ako.wsgi:application -c /home/oleg/dj/ako/ako/gunicorn.conf.py directory=/home/oleg/dj/ako user=nobody autorestart=true redirect_stderr=true stdout_logfile=/home/oleg/dj/ako/ako_supervisor.log stderr_logfile=/home/oleg/dj/ako/ako_supervisor.log autostart=true autorestart=true startsecs=10 conf. NGINX server { listen 80; server_name 95.217.187.37; access_log /var/log/nginx/example.log; location /static/ { root /home/oleg/dj/ako/rsf/; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } When I try to launch gunicorn with a stopped supervisor: sudo service supervisor stop on the root of my project gunicorn ako.wsgi:application everything properly works : Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-91-generic x86_64) (venv) root@t-20200417:~/dj/ako# gunicorn --bind 0.0.0.0:8000 ako.wsgi [2020-04-18 13:44:15 +0200] [1768] [INFO] Starting gunicorn 20.0.4 [2020-04-18 13:44:15 +0200] [1768] [INFO] Listening at: http://0.0.0.0:8000 (1768) [2020-04-18 13:44:15 +0200] [1768] [INFO] Using worker: sync [2020-04-18 13:44:15 +0200] [1771] [INFO] Booting worker with pid: 1771 The website normally runs under http://95.217.187.37/rsf/f_size_water/ and everything properly works. When I start supervisor sudo service supervisor start the website is still reachable, static links are still working, but the dynamic content does not work. When a user in his browser changes the language in the menu "homepage language … -
Can't install django using pip. I have tried many things but nothing worked
ERROR: Exception: Traceback (most recent call last): File "c:\program files\python38\lib\site-packages\pip_internal\cli\base_command.py", line 186, in _main status = self.run(options, args) File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 253, in run options.use_user_site = decide_user_install( File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 604, in decide_user_install if site_packages_writable(root=root_path, isolated=isolated_mode): File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 548, in site_packages_writable return all( File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 549, in test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs)) File "c:\program files\python38\lib\site-packages\pip_internal\utils\filesystem.py", line 140, in test_writable_dir return _test_writable_dir_win(path) File "c:\program files\python38\lib\site-packages\pip_internal\utils\filesystem.py", line 153, in _test_writable_dir_win fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) PermissionError: [Errno 13] Permission denied: 'c:\program files\python38\Lib\site-packages\accesstest_deleteme_fishfingers_custard_zsocdh' -
How to access Pivot Table ahead in Django Models
I have 3 models as following class User(models.Model): name = models.CharField(max_length=20, unique=True) class Job(models.Model): name = models.CharField(max_length=20, unique=True) class Slot(models.Model): name = models.CharField(max_length=20, unique=True) jobs = models.ManyToManyField(Job, related_name = 'slots') As you can see I am able to create Pivot table for Job_slot, with the Primary key of that Table I need to create a table between User and job_slot, where I can have something like following Thanks in advance for solving this complex problem That I am trying to solve for more than 5 hours!! -
How do I create an API endpoint with django rest framework jwt for when user is logged_in?
I am trying to create an endpoint for when a user is logged in to check the status of user is logged in react js. For my backend, I use django rest-framework. Here is the backend code. serializers.py: from rest_framework import serializers; from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) # handle signups only class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) inst = self.Meta.model(**validated_data) if password is not None: inst.set_password(password) inst.save() return inst class Meta: fields = ('token', 'username', 'password') urls.py: The following code is where I would create the endpoint from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from rest_framework_jwt.views import obtain_jwt_token from rest_framework_jwt.views import verify_jwt_token urlpatterns = [ path('api-auth/', include('rest_framework.urls')), # path('rest-auth/', include('rest_auth.urls')), # path('rest-auth/registration/', include('rest_auth.registration.urls')), path('token-auth/', obtain_jwt_token), path('api-token-verify/', verify_jwt_token), path('login/', include('login.urls')), path('admin/', admin.site.urls), path('api/', include('menus.api.urls')), path('phlogapi/', include('phlogfeeder.phlogapi.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am confused on how to create a endpoint with jwt. -
django ORM annotate of sum of integers divide by sum of floats some how fail
class CSVFile(models.Model): installs = models.fields.IntegerField() spend = models.fields.FloatField() # this give me weird error! CSVFile.objects.annotate(metric=Sum('installs') / Sum('spend')) # but this will fix it! any idea why? CSVFile.objects.annotate(metric=Sum('installs', output_field=FloatField()) / Sum('spend')) sum of integers divide by sum of floats some how fail! database is SQLite django 3.05 -
Add data from request POST into a table template [Django, Python]
I create a table show book info from SQLite database and I'm trying to create an "Add New Book form" to make it add a new book into a table database. How can I add a book and then make it show into the table Book Info ? <div class="container-fluid"> <!-- Add Book --> <div class="add-book"> <h1>Add a Book</h1> <form action="/add_book" method="POST" class="add_more_book"> {% csrf_token %} <p> <label for="title" id="title">Title:</label> <input type="text" name="title" class="form-control" id="input-title" /> </p> <p> <label id="desc" for="desc">Description:</label> <textarea class="form-control" name="description" id="input-desc" rows="3"></textarea> </p> <button type="submit" class="btn shadow btn-primary" id="addbtn"> Add </button> </form> </div> <!-- End of Add Book --> <!-- Book info --> <div class="book-info"> <form action="/" method="POST"> {% csrf_token %} <table class="table table-bordered"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Action</th> </tr> </thead> <tbody> {% for i in all_books_info %} <tr> <th scope="row">{{i.id}}</th> <td>{{i.title}}</td> <td><a href="/books/{{i.id}}">Views</a></td> </tr> {% endfor %} </tbody> </table> </form> </div> -
PyCharm Doesn't Recognize Installed Django App
I created a Django project and then started and app, but in project_name/project_name/urls.py, PyCharm doesn't recognize my app_name when I say from app_name import views. But running the project from the command line works. Ideas? I'm using a virtualenv and the Anaconda distribution of Python 3.7.3. Pycharm 2020.1 on Windows. -
multiline chart.js + Django graph does not rendering properly
i have spent the whole day trying to figure out what is going on with this graph not rendering in html. I can't find out what I am doing wrong here. the closest post that I found was this one Django and Chart.js Not Rendering Graph Correctly the help provided there does not do the trick. My underlying issue is that I am not sure how to pass my data inside of the graph. here is my js script function setChart(){ var ctx5 = document.getElementById('myChart5').getContext('2d'); var myChart5 = new Chart(ctx5, { type: 'line', data: { labels: ["days-15","days-14", "days-13","days-12","days-11","days-10","days-9","days-8","days-7","days-6","days-5","days-4","days-3","days-2","days-1"], datasets: [{ label: 'Number of orders placed', data: [ {% for dr in tableau1 %}{{ dr.number_of_orders_placed}}, {% endfor %}], backgroundColor: [ 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(54, 162, 235, 0.2)', ], borderWidth: 1 }, { label: 'purchased_quantity', data: [{% for dr in tableau1 %}{{ dr.purchased_quantity}},{% endfor %}], backgroundColor: [ 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(54, 162, 235, 0.2)', ], borderWidth: 1 }, { label: 'sold_quantity', data: [{% for dr in tableau1 %}{{ dr.sold_quantity}},{% endfor %}], backgroundColor: [ 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(54, 162, 235, 0.2)', ], borderWidth: 1 } ], options: { scales: { yAxes: … -
on Django, how can i pull data from database to a new html template from a html form, using a non logged in user input?
I have a form that is saving the data to the database and i want to open the template with the values from the database that I already calculated on models.py and saved to the database, this is the first tool I am developing on python so maybe I am asking the wrong question. So far the info that I want to pull is already saved on the Django Database. I want to pull the data from the "current user" form submission. so my question is how do I call current user DB info to the template when they click "get an estimate". This is what I have on views: class RackView(TemplateView): template_name = 'estimate/estimate_details.html' def get(self, request): form = RackForm() racks = Rack.objects.all() users = User.objects.all() args = {'form': form, 'racks': racks, 'users': users} return render(request, self.template_name, args) def post(self, request): form = RackForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user #try changing here to "pk" or "id" instead of user if it doesnt work or try dreating a user with name and email post.save() text = form.cleaned_data['post'] form = RackForm() args = {'form': form, 'text': text} return redirect('estimate_details: estimate_details') def estimate_details(request,pk=None): if pk: user = User.objects.get(pk=pk) else: … -
Django Admin Panel multiple choice all selected
I am adding a model to my admin panel in Django. It looks like this.. class Property(models.Model): event = models.ManyToManyField(Event) name = models.CharField(max_length=255) applicable_devices = models.ManyToManyField(Device) property_type = models.CharField(max_length=20, choices=TYPE_CHOICES) expected_value = models.CharField(max_length=255) For the field event it corresponds to another model of mine. In the admin panel it gives me a mutliple choice field to select the ones it applies to. I am trying to find a way to make it select all of them by default. When I going to be adding these properties, it will be applying to all events the majority of the time. I am just trying to save some clicks from selecting all. -
send list of object with data attr in django template
I built an image sharing website with django and jquery and I want when clicking on image rise comment of image with modal but for doing so we need to send list of my comment of image. If we want to send only one object we can use data-* attribute and jquery but for sending a list of objects this mehod doesn't work any more. Is this any way for sending list of object with data-* attribute? -
Django case when else in filter
I need a similar code to this SQL: SELECT * FROM tab WHERE a = CASE WHEN x IS NULL THEN b ELSE c END my attempt, but to no success: model.objects.filter(a=Q(Case(When(x__isnull=True, then='b'), default='c'))) when I try to run, I get this error: Traceback (most recent call last): File "<input>", line 2, in <module> File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1340, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q check_filterable=check_filterable, File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1249, in build_filter value = self.resolve_lookup_value(value, can_reuse, allow_joins, simple_col) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1058, in resolve_lookup_value value = value.resolve_expression(self, **kwargs) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query_utils.py", line 95, in resolve_expression check_filterable=False, File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q check_filterable=check_filterable, File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1237, in build_filter arg, value = filter_expr TypeError: cannot unpack non-iterable Case object -
How to handle user reports for content e.g. inappropriate posts and profiles?
My Django app will allow users to report inappropriate posts and profiles etc. I want to be able to store these reports so that they can be reviewed by an admin. The ways I'm thinking of doing it is to either create a table in the database and store it there or just store it in a CSV / text file. Is there a better way to handle this feature? -
Passing Javascript variables to python main.views in Django
I am trying to send a variable from javascript to a python function in main.views, and I am using the Django web framework. I am very new to web development and I would really appreciate it if you showed some code for how to do it. Here is my variable (in home.html): <script> var my_var = 10; </script> and I need to send this to a function in main.views. My main.views looks like this so far: from django.shortcuts import render def homepage(request): return render(request, "main/home.html") def get_var(request): my_var = # I WOULD LIKE TO RECEIVE THE VARAIBLE HERE print(my_var) and so far here is my main.urls: from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path("", views.homepage, name="homepage"), ] Thanks for the help! -
getting 'bytes' object has no attribute 'encode'
my task is : upload a CSV file in Django model my model.py is given below from django.db import models # Create your models here. class Chart(models.Model): date=models.DateTimeField(blank=True,null=True) open=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) high=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) low=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) close=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) def __str__(self): return self.str(date) class NSEBHAV(models.Model): symbol=models.CharField(max_length=20,null=True,blank=True) series=models.CharField(max_length=2,null=True,blank=True) open=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) high=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) low=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) close=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) last=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) prev_close=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) tottrdqty=models.IntegerField(null=True,blank=True) tottrdval=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) timestamp=models.DateTimeField(blank=True,null=True) totaltrades=models.CharField(max_length=20,null=True,blank=True) isin=models.CharField(max_length=20,null=True,blank=True) def __str__(self): return self.symbol my view.py is given below import csv,io from django.shortcuts import render from django.contrib import messages from .models import NSEBHAV,Chart # Create your views here. def upload_nse(request): template='upload.html' data=NSEBHAV.objects.all() prompt={ 'order': 'Order of the CSV should be (symbol,series,open,high,low,close,last,prevclose,tottrdqty,tottrdval,timestamp,totaltrades,isin', 'profiles': data } if request.method=='GET': return render(request,template,prompt) csv_file=request.FILES['file'] print(csv_file) # if not csv_file.name.endwith('.csv'): # messages.error(request,'This is not csv file') data_set=csv_file.read().encode('utf-8') io_string=io.StringIO(data_set) next(io_string) for column in csv.reader(io_string,delimiter=',',quotechar="|"): _, created = NSEBHAV.objects.update_or_create( symbol=column[0], series=column[1], open=column[2], high=column[3], low=column[4], close=column[5], last=column[6], prevclose=column[7], tottrdqty=column[8], tottrdval=column[9], timestamp=column[10], totaltrades=column[11], isin=column[12] ) context = {} return render(request, template, context) csv.file sample is error screenshot my html file is is given below: thanks in advance . if i use encode is is giving same error and also i want to check type of uploaded file is csv or not