Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using django forms with separate models for labels and fields
I apologize in advance if this ends up sounding cryptic... I'm building a site using Django where users can select a topic from a list and then fill out a form that contains questions specific to that topic. I have 2 models: the Topic model is for the different topics and contains the specific questions for each. The Answers model is for the answers that are submitted in the form. The Answers model is linked to the Topic model with a foreign key. I currently have everything working the way that I want it to, but very messily. I am using purely html forms, and each input label is populated with the question text saved in the Topic model. What I am doing is running JavaScript when the form is submitted, querying all the form fields, and then using fetch to send a POST request with all the field text. Then in my views.py, I receive the request, get all the data, and save a new instance of the Answers model. I'm not well versed in form security, other than knowing to use a csrf token. Out of consideration for any SQL injection vulnerabilities, I started doing some research and … -
How to redirect http://127.0.0.1:8000/ to login page if the user is not logged in
In my Django project I am trying to make the http://127.0.0.1:8000/ which is the home page to redirect to the Login in Page if user is not logged in however there is a user who is logged in I want http://127.0.0.1:8000/ to become http://127.0.0.1:8000/username/ I have tried different answers but nothing specific lead to this answer: Here is the login view after login: class LoginView(LoginView): template_name = 'login.html' def get_success_url(self): user=self.request.user.username return f'/{user}/' Here is the login urls: path('accounts/login/', LoginView.as_view(redirect_authenticated_user=True,template_name='users/login.html'), name='login'), Here is the home views: class home(LoginRequiredMixin, ListView): model = Item template_name = 'app/home.html' context_object_name = 'items' Here is the app urls: path('<str:username>/', home.as_view(), name='home'), My question: How to redirect home page to http://127.0.0.1:8000/username/ if user is logged in and if not to login page -
Django tests not isolated when testing authentication
I am testing my authentication with the django.test.Client and two tests cases fail because once I test my test_login_success test case, the other tests fail because the user remains authenticated, even when I am instantiating a new client in the class setUp and even deleting the user in the tearDown. My code: from django.test import Client, TestCase from app.users.models import User class TestLogin(TestCase): def setUp(self): super().setUp() self.email = 'test@test.com' self.password = 'SomeRandomPass96' User.objects.create_user(email=self.email, password=self.password) self.client = Client() def tearDown(self): User.objects.filter(email=self.email).delete() super().tearDown() def test_not_authenticated(self): # success the first time, fails after test_login_success is executed for the first time. user = User.objects.get(email=self.email) assert not user.is_authenticated def test_login_success(self): # always success self.client.post( '/users/login/', {'email': self.email, 'password': self.password} ) user = User.objects.get(email=self.email) assert user.is_authenticated def test_login_wrong_credentials(self): # success the first time, fails after test_login_success is executed for the first time. self.client.post( '/users/login/', {'email': self.email, 'password': 'wrongPassword123'} ) user = User.objects.get(email=self.email) assert not user.is_authenticated -
DJANGO + ReactJS | Error when the response is not 200
Getting the below error when sending a 401 (un-authorized) response. As per the error, when I change it to 200, it works well. But here I need to send 401 itself. Access to fetch at 'http://127.0.0.1:8888/employees/api/fetch/home/data/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. Frontend : ReactJS Backend : Django Any help would be greatly appreciated. -
Django Dynamic URL from Forms
TL;DR - I failed implementing dynamic urls for too long. My plan is: Whenever the form is submitted, it would redirect you to a page (with a pk as the url), that sums up your choices. I'm aware that this was asked multiple times and I was able to implement Dynamic URLs perfectly fine with a new project. Yet, my current one is simply not making any sense to me. I have a simple form with CharField as fields. It renders them from the Models file which states pretty much the same. I added to the Models.py: > task_id = models.AutoField(primary_key=True) The form is inside "hunting.html", and you access it through the navbar: > <a class="nav-link {% if 'hunting' in segment %} active {% endif %}" href="/hunting.html"> My view is quite simple, I recently opted to Class-based (when using function-base it did not work as well): app/views.py class Hunting(LoginRequiredMixin, View): def get(self, request): form = HuntForm() print('Access Hunting') return render(request, 'home/hunting.html', {'form': form}) def post(self, request): form = HuntForm(request.POST, request.FILES) name = request.POST['name'] limit = request.POST['limit'] os = request.POST.getlist('os') mal = request.POST.getlist('mal') my_type = request.POST.getlist('my_type') if form.is_valid(): form.save() print('Hunt information is saved') return redirect('home/index.html') return redirect('home/index.html') app/urls.py: path('', views.index, name='home'), … -
Custom User class, password isn't saved from the form
I've coded my own AbstractBaseUser and BaseUserManager. Creating users and superusers via terminal works fine. But there is a problem with creating users via form. All user fields are saved properly except password field, which is blank. My models.py: from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomAccountManager(BaseUserManager): def create_superuser(self, email, first_name, last_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, first_name, last_name, password, **other_fields) def create_user(self, email, first_name, last_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **other_fields) user.set_password(password) user.save() return user class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email And my forms.py: from django import forms from .models import MyUser class MyUserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = MyUser fields = ['email', 'first_name', 'last_name'] I think there is … -
I'm receiving the error: PermissionError: [Errno 13] Permission denied: '/app/vol'
The full error: The Dockerfile: FROM python:3.9-alpine3.13 LABEL maintainer="arithmeticatuition.com" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app COPY ./scripts /scripts WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-deps \ build-base postgresql-dev musl-dev linux-headers && \ /py/bin/pip install -r /requirements.txt && \ apk del .tmp-deps && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/static && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts ENV PATH="/scripts:/py/bin:$PATH" USER app CMD ["run.sh"] The docker-compose-deploy file: version: '3.9' services: app: build: context: . restart: always volumes: - static-data:/vol/web environment: - DB_HOST=db - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - SECRET_KEY=${SECRET_KEY} - ALLOWED_HOSTS=${ALLOWED_HOSTS} depends_on: - db db: image: postgres:13-alpine restart: always volumes: - postgres-data:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASS} proxy: build: context: ./proxy restart: always depends_on: - app ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: I've tried everything from similar stack exchange requests but none seem to be working... I've rewatched lots of tutorials and I don't seem to be getting anywhere, who would've … -
How can I test the URLS for my Class Based Views in Django?
I'm trying to test the URL resolutions for my first Django project- I have successfully tested my function-based views, however I am having trouble testing my Class Based Views. I'm getting the below error when I run the test on my CBV: AssertionError: <function UpdateHealth at 0x7f538f023e50> != <HealthHub.views.UpdateHealth object at 0x7f538d7aec10> Tests.py (CBV test in question): def test_health_hub_update_url_is_resolved(self): url = reverse('HealthHub:health_hub_update') self.assertEqual(resolve(url).func, views.UpdateHealth()) views.py (view in question): class UpdateHealth(View): '''View for the Update Health page. Uses StatUpdateForm to allow the user to update their stats.''' def get(self, request, *args, **kwargs): stats = HealthStats update_form = StatUpdateForm context = { 'stats': stats, 'update_form': update_form, 'user': stats.user, 'weight': stats.weight, 'date': stats.date, } return render(request, 'health_hub_update.html', context) def post(self, request, *args, **kwargs): update_form = StatUpdateForm(data=request.POST) if update_form.is_valid(): obj = update_form.save(commit=False) obj.user = request.user obj.save() return redirect("HealthHub:health_hub") Urls.py: path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'), Any help would be much appreciated, as I seem to have hit a dead-end. -
DJANGO: How can I create a custom User with a OneToOne relationship to Person
I have a custom user model, I would like my CustomUser model to have a OneToOne relationship with the Person model; Since I want to first register persons and then create a username for them, since not all registered people need to have a username. I have tried the code shown below; but what I get is the following error: Cannot assign "1": "CustomUser.dni" must be a "Person" instance. But, the ID number is already registered in the Person table P.S. If anyone has a better suggestion for getting people to register first and then create a username for them when strictly necessary, I'd really appreciate it. models.py from .managers import CustomUserManager class Person(models.Model): dni = models.CharField('Número de DNI', max_length=8, unique=True) ... class CustomUser(AbstractBaseUser, PermissionsMixin): dni = models.OneToOneField(Person, on_delete=models.CASCADE, unique=True) email = models.EmailField('Correo electrónico', max_length=355, unique=True) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'dni' REQUIRED_FIELDS = ['email'] ... managers.py from django.contrib.auth.models import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, dni, email, password=None): if not dni: raise ValueError('Debe ingresar el número de DNI.') person = self.model( dni=dni, email=self.normalize_email(email), ) person.set_password(password) person.save(using=self._db) return person def create_superuser(self, dni, email, password=None): person = self.create_user( dni, password=password, … -
How oauth works for saving users data?
I am building simple booking app in django, so flow of the app is that user's can do a booking and then their bookings will be saved into the database, However as I'll be using oatuh in my app, So my question is if user has made a booking and I want to fetch all of the bookings user's has made how do I implement this using oauth? what data of user data do I store in my own database so that each time user login using oauth I can fetch specifically that user's data (bookings). -
Passing variable into custom template filter
I've got the following custom filter myfilters.py @register.filter def my_custom_filter(value, arg): some python stuff Within my template, I'm registering the filters {% load myfilters %} I'm then applying the template tag and then trying to pass in the variable a_template_value {{ form.body|my_custom_filter:{{a_template_value}}|safe }} I'm then getting the following error: my_custom_filterrequires 2 arguments, 1 provided Thanks! -
How to make nginx serve static files from multiple directories for django project?
I have a django project. It has static files in multiple applications, that I can put together by running python3 manage.py collectstatic. All files will be moved to the static folder, which is located in the root folder of my project. Additionally, I have 200GB pictues, located in another folder /var/images/user-profile-images/subfolder/image.jpg. In both cases image url is like so: /static/path-to-image. So in first case I have static folder, in second case I don't have. this is my location block: location ~ ^\/static\/(.*) { try_files /project-root-folder/static/$1 /var/images/user-profile-images/$1; } it is supposed to serve urls /static/style.css and /static/subfolder/image.jpg respectively, but doesn't work in both cases. I have double checked everything many times, searched around stackoverflow, but no answer. Seems it's also not possible to debug this, since nginx is not logging not found cases. Actually, I see django 404 error, so probably it does not even match. -
Django static css doesn't make any change and images don't appear
Django static files are not working in my application, I defined STATICFILES_DIRS, STATIC_URL, and STATIC_ROOT in settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'social_media') ] and here's base.html: {% load static %} <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type= "text/css" href="{% static 'style.css' %}"> </head> <body> {% block navbar %} {% include 'parts/navbar.html' %} {% endblock %} {% block content %} {% endblock %} </body> </html> I use this in my pages: {% extends 'base.html' %} {% load static %} {% block content %} <!--stuff--> {% endblock content %} I tried using InPrivate(incognito but MS Edge version) window and nothing changed, I also tried deleting style.css file and making it again and collecting static files again but it also didn't work. -
How can I ensure enough space is left to avoid content moving down the page if a warning message appears?
I have a server-side rendered application (Django) with a login page which provides a username and password field, submit button, instructions for forgotten password and so on. This is what I will call the "main content". Sometimes, there will an extra div above the main content with a message such as "Invalid username or password". I would like it so that if the user submits an invalid login and this message appears, the main content doesn't move. (I'm aware that this will involve leaving a white space above the main content, but there's a lot of blank space on this page anyway so it doesn't matter) I considered rendering <div class="warning-message">Invalid username or password</div> if required and some kind of placeholder <div class="placeholder"></div> otherwise, but I was struggling to style them so that the empty div would always be the same height as the warning message one. I did also consider positioning either the main content or the warning message with position:absolute, but this sometimes leads to overlapping on small screens. -
error rendering the page template when placing the site on Heroku
Good afternoon. I have a problem with a website that I posted using the Heroku platform. The error "Error during template rendering" occurred. The most interesting thing is that everything works fine on the local server. I tried to re-upload the project to Heroku, but it didn't give any results. -
Django hide password fields on user creation form
I have a custom user model and a form that allows admins to add users without having to go to the admin section. I want hide the password fields and set the password to a random generated string. Then send an email to the new user with a link to reset their password. So far I haven't been able to figure out the first part - hiding the password fields. The form.py: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class AddCompanyEmployeeForm(UserCreationForm): class Meta: model = CustomUser fields = UserCreationForm.Meta.fields + ('email', 'full_name', 'age') the view: from django.views.generic import CreateView, ListView from django.urls.base import reverse from .forms import CustomUserCreationForm, AddCompanyEmployeeForm from .models import CustomUser class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' class AddCompanyEmployee(CreateView): model = CustomUser template_name = 'manage/add_employee.html' form_class = AddCompanyEmployeeForm #success_url = reverse_lazy('directory') def get_success_url(self): return reverse('userprofile_detail', kwargs={'pk': self.object.userprofile.pk}) I have tried a number of approaches including changing the form to class AddCompanyEmployeeForm(UserCreationForm): class Meta: model = CustomUser fields = ('email', 'full_name', 'age') So far the password fields continue to be visible regardless of what I try. Any suggestions? -
Someone help me in this error TypeError at /contact 'method' object is not subscriptable
Views.py # Create your views here. def home(request): return render(request, 'home.html') def about(request): return render(request, 'about.html') def project(request): return render(request, 'project.html') def contact(request): if request.method=='POST': name=request.POST.get['name'] email=request.POST.get['email'] phone=request.POST.get['phone'] concern=request.POST.get['concern'] print(name,email,phone,'concern') obj=Contact(name='name', email='email',phone='phone',concern='concern') obj.save() return render(request, 'contact.html') I am trying to connect my contact form with database but after post method it doesn't allow me. -
I am trying to render docx file in my django project, using the data from JSON field, but it couldn't find the docx file in my system
This is my views.py from pathlib import Path from django.conf import settings from rest_framework import viewsets from rest_framework import mixins from rest_framework.decorators import action from django.http import HttpResponse from . import models from . import serializers from docxtpl import DocxTemplate import pypandoc class TemplateViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): queryset = models.Template.objects.all() serializer_class = serializers.TemplateSerializer def get_serializer_class(self): return { 'list': serializers.TemplateSerializer, 'retrieve': serializers.TemplateSerializer, 'generate_document': serializers.DocumentGenerateSerializer, }.get(self.action, serializers.TemplateSerializer) @action(detail=True, url_name='generate-document', methods=['POST', 'GET']) def generate_document(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) context_data = serializer.data['context'] document_extension = serializer.data['extension'] instance = self.get_object() versions = instance.versions.all() documents = versions.get(id=instance.id) document = DocxTemplate(open('src/media/{}'.format(documents.upload.name.split('.')[0] + '.docx'))) # document = documents.upload document.render(context_data) if document_extension == 'docx': response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument' '.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename="{}"'.format(document.name.split('.')[0] + '.docx') return response else: pypandoc.convert_file(document, 'pdf', outputfile=document) response = HttpResponse(document, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="{}"'.format(document.name.split('.')[0] + '.pdf') return response This is my forms.py, where I am getting JSON field from django import forms from django.contrib.auth import get_user_model from .models import Template, Version User = get_user_model() class TemplateCreationForm(forms.ModelForm): class Meta: model = Template fields = ('name',) def save(self, commit=True): self.instance.user = self.request.user return super().save(commit) class VersionCreationForm(forms.ModelForm): class Meta: model = Version fields = ('template', 'upload', 'start_from', 'end_to') Template is being created through my … -
Api for Shoping App (Flutter) with Python
I need to make an Api to use for a shopping app built with Flutter and i want to use Python to as i already have decent exprince in and i heard that it could be done using Python and Django as a database I never tried to do so before -
Why shows this error when adding the file "Object of type InMemoryUploadedFile is not JSON serializable"?
My target is to build a form that besides charfields will have a file field and all data of the fields will be stored in the database. The form does store the charfield's data, but after adding a new field as filefield It not working when I submit, and shows the below error😥. Why is not store the filefield's data? views.py: def employeeListView(request): if request.method == 'POST': serializer = EmployeeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return redirect("/") def InsertAndInfo(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') file = request.FILES['filedf'] #if 'filedf' in request.FILES else None data = { 'name':name, 'email':email, 'phone':phone, 'file':file } headers = {'Content-Type': 'application/json'} requests.post('http://127.0.0.1:8000/api/employees/',json=data,headers=headers) return redirect("/api/") employeeInfoApiLink = requests.get('http://127.0.0.1:8000/api/AllElmployeeInfo/').json() context = { "employeeInfo":employeeInfoApiLink } return render(request, 'InsertAndInfo.html',context) models.py: class Employee(models.Model): name = models.CharField(max_length=30) email = models.EmailField(max_length=30) phone = models.CharField(max_length=30, null=True) file = models.FileField(upload_to="file/",null=True) serializer.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = "__all__" form.html: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" class="form-control" name="name" id="name"> <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp"> <input type="text" name="phone" class="form-control" id="phone"> <input type="file" name="filedf" class="form-control" id="file"> <button type="submit" class="btn btn-primary">Submit</button> </form> -
Django Channels on azure
I can't connect to the websocket in my azure app. To be concise my issue is exactly same as this question. I saw its answer too and it says that custom port 6379 is not allowed. Is there any way for this to work. How can I add the port 6379 to my web app. Or if not Are there any alternatives? -
Getting the average rating from a book in a bookstore api
Written in python. I am having an issue that the average won't work on my code. I don't know if I can use annotate or aggregate. I want it so I can choose what book I want and show the average once I choose it. class AverageRatingViewSet(generics.ListAPIView): serializer_class = BookratingsSerializer def get_queryset(self): queryset = Bookratings.objects.all() try: user_input = self.request.query_params.get('rating') except AttributeError as abc: return Bookratings.objects.none() if user_input is not None: **** ***queryset = queryset.filter(bookid=user_input).aggregate(Books_average=Avg('rating')*)**** ** return queryset I started messing around with the queryset.filter but I keep getting error on the local host -
Trigger python script with Django user input
I am trying to trigger a pyfirmata script that will load onto an arduino device when a user checks a checkbox on a django view. I am trying to implement some comparison code in my view that will check if user submitted check box is true then trigger pyfirm.py. Background: Py firmata will drive the arduino pins directly without needing an arduino IDE. Should I hard code my pyfirmata in my view or can I trigger a full script some how? Iam using a raspberry pi as a single board computer that is connected to arduino as a device driver. I am considering the pi device as a user. Any tips on this? I have my check box working and i am printing the POST results to the terminal. just need to check if box is true and trigger script some how. Haven't had any luck triggering a script. I see a couple questions related to this but i am curious for pyfirmata specific directions on this. -
Loading choices from utils.py results in unexpected error: TypeError: 'CharField' object is not iterable in Django
I have a models.py file in Django, and it was working perfectly. I have an extensive model named Media, and since it contains quite some columns with elaborate choices in nested tuples, I decided to move these nested tuples to an utils.py file located in the same app. I found that it is working for all columns in my Media model, except for one. It is shown below: #This was how it was initially and working: #Umbrella UMBRELLA = ( ("DH", "DH"), ("SE", "SE"), ("PA", "PA"), ("PF", "PF") ) class Media(models.Model): umbrella = models.CharField(max_length=20, choices=UMBRELLA, default='Undefined', null=True, blank=True) second_umbrella = models.CharField(max_length=20, choices=UMBRELLA, default='Undefined', null=True, blank=True) #Problematic? Changed it to: utils.py: #Umbrella def UMBRELLA(): UMBRELLA = ( ("DH", "DH"), ("SE", "SE"), ("PA", "PA"), ("PF", "PF")) return(UMBRELLA) models.py: from database.utils import * umbrella=UMBRELLA() class Media(models.Model): umbrella = models.CharField(max_length=20, choices=umbrella, default='Undefined', null=True, blank=True) #This one is not problematic second_umbrella = models.CharField(max_length=20, choices=umbrella, default='Undefined', null=True, blank=True) #This one is problematic The strange thing here is that if I only change (first) umbrella choiches to umbrella from utils.py it works fine. However, if i change choices from second_umbrella to umbrella from utils.py it crashes?? I meticulously checked the db.sqlite3 with django admin, but the choices … -
Django AttributeError: 'list' object has no attribute 'sort_values'
I'm getting AttributeError: 'list' object has no attribute 'sort_values' in below code, task.py: from __future__ import absolute_import,unicode_literals from celery import shared_task from time import sleep import eda import os @shared_task def aync_task(amz_columns_dict, download_path, file_name, data): sleep(10) eda_object = eda.eda(col_dict=amz_columns_dict) save_path = download_path name_of_file = file_name file_path = os.path.join(save_path, name_of_file+".html") eda_object.create_report(data=data, filename=file_path) return 'task complete' views.py : def eda_flow(request): path = '/Unilever/satyajit/us_amz.csv' mode = 'rb' df = pd.read_csv("/home/satyajit/Desktop/opensource/data/us_amz.csv", low_memory=False) df = df.head(100) json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'data': data, 'message': 'data loaded successfully.'} if request.method == 'POST': id_col = request.POST.get('id_col') file_name = request.POST.get('file_name') download_path = request.POST.get('download_path') amz_columns_dict = {'id_col': id_col} try: if os.path.exists(download_path): status = aync_task.delay(amz_columns_dict, download_path, file_name, data) return render(request,'home/index.html', {'message': 'Save Complete'}) else: return render(request,'home/index.html', {'message': 'download path is not exist'}) except Exception as e: print('error is---->', e) return render(request,'home/index.html', {'message': 'Error while generating EDA'}) return render(request, "home/tables-simple.html", context) The error of this code on below as screenshot: I've also tried to search similar question here (similar question) but that does not helpful to me. Any help would be much appreciated. thanks in advance.