Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to log in using rest-auth while I can see the user in my database
I am working on an application to use rest-auth with all-auth to authenticate and manage my userbase. I was following this tutorial, and the registration is working perfectly, and I am using a few custom settings to use the email as the authentication method. # Rest auth EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'none' Unfortunately, when trying to use the login endpoint with the default login view, using Postman and posting the data as formdata or form-urlencoded: path('rest-auth/login/', LoginView.as_view(), name='rest_login'), I get this response. { "non_field_errors": [ "Unable to log in with provided credentials." ] } I am using the exact password/email that is in my database. Using ipdb, I have tracked down the issue to the login view within rest_auth. When attempting to validate the serializer, it fails at this line. self.serializer.is_valid(raise_exception=True) The Login serializer looks like this: LoginSerializer( context={'request': <rest_framework.request.Request object>, 'format': None, 'view': <rest_auth.views.LoginView object>}, data=<QueryDict: {'password': ['asdandapodnapdasnd'], 'email': ['example@h.com']}>): username = CharField(allow_blank=True, required=False) email = EmailField(allow_blank=True, required=False) password = CharField(style={'input_type': 'password'}) What can I do to ensure that the LoginSerializer is valid to allow my users to login? -
Django - How to redirect the user after the first login only
I would like to redirect the user to a custom 'welcome' page when they first log into the website. But anytime they log in after that they just get redirected to the home page '/' like normal. I am thinking I can use the "last login" field that the user has, because when they have not logged in yet it is marked as 'None' I think? I am thinking something like: if request.user.last_login == None: return redirect('welcome_page.html') else: return render(request, '/') But I dont think it will be that simple, and I am not even sure what areas I should be looking in / changing to add that code in. I was hoping someone would have some advice as my research has come up empty so far and I haven't been able to get anything to work. -
Django tuple/choices field is not translating
I have an Integer ModelField with a set of choices. field = models.IntegerField(choices=CHOICES_CONSTANT) This CHOICES_CONSTANT is defined in another file and imported CHOICES_CONSTANT = ( (0, _('One')), (1, _('Two')), ... ) The _ is from from django.utils.translation import ugettext_lazy as _ as the model field requires you to use lazy translations. I also import the CHOICES_CONSTANT into other files (such as reports) where in a report I might say str(dict(CHOICE_CONSTANT)[object.field]) if object.field else ''. This str(dict(CHOICES_CONSTANT)[object.field]) if object.field else '' does not get translated. In fact, if I just print(CHOICES_CONSTANT) it immediately evaluates to the default language (English). In other places I would do object.get_field_display() and that also does not translate. Any help would be much appreciated. -
Error message when attempting to upload profile picture in Django
I have asked a similar question, but believe I have made quite a lot of changes to my code to warrant asking a new one (also the problem seems to be somewhat different). I am trying to allow users to upload a profile image but cannot seem to save the image and now getting the error message: mentorform = MentorProfileForm(instance=user) TypeError: init() got an unexpected keyword argument 'instance' This is what I have in views(teachers.py): def edit_user(request): user = request.user mentorform = MentorProfileForm(instance=user) if request.method == 'POST': form = UserForm(request.POST, request.FILES, instance=user) mentorform = MentorProfileForm(request.POST, request.FILES, instance=user.mentor) if form.is_valid() and mentorform.is_valid(): m = Mentor.objects.get() form.save() m.photo = mentorform.cleaned_data['photo'] m.save() messages.success(request, f'Your profile was successfully updated!') return HttpResponseRedirect('%s' % (reverse('teachers:edit_user'))) # else: # messages.error(request, ('Please correct the error below.')) else: form = UserForm(instance=user) context = {'form':form, 'mentorform':mentorform} return render(request, 'classroom/teachers/app-instructor-profile.html', context) models class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Mentor(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) linkedin = models.URLField(max_length=200,null=True,blank=True) photo = models.ImageField(null=True, blank=True, upload_to='media', default='default.jpg') def __str__(self): return "Profile of user {}".format(self.user.username) @receiver(post_save,sender=User) def create_or_update(sender, instance,created, **kwargs): if created: post_save.connect(create_or_update, sender=User) forms class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name','last_name','email') class MentorProfileForm(forms.Form): photo = forms.ImageField() and my html form: <form … -
Django Forms and Crispy Form help "Failed lookup for key [helper]"
I am learning forms and crispy forms and cannot seem to find the issue with my code. I get the error django.template.base.VariableDoesNotExist: Failed lookup for key [helper] in <ContactForm bound=False, valid=Unknown, fields=(name;email;category;subject;body)> My views are: from django.shortcuts import render from django.http import HttpResponseRedirect from .models import SubID, CustID, AmountAdd from .forms import ContactForm, SnippetForm import stripe def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] print(name, email) form = ContactForm() return render(request, 'form.html', {'form': form}) def snippet_detail(request): if request.method == 'POST': form = SnippetForm(request.POST) if form.is_valid(): form.save() form = SnippetForm() return render(request, 'form.html', {'form': form}) My forms are: from django import forms from .models import Snippet from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit class ContactForm(forms.Form): name = forms.CharField() email = forms.EmailField(label='Email') category = forms.ChoiceField(choices=[('question', 'Question'), ('other', 'Other')]) subject = forms.CharField(required=False) body = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' class SnippetForm(forms.ModelForm): class Meta: model = Snippet fields = ('name', 'body') My Urls are setup with an include in the project folder to my app folder: from django.urls import path from . import views urlpatterns = [ path('STRP_Input/', views.StrpFormView), path('addID/', views.addID), path('deleteID/<int:SubID_id>/', views.deleteID), path('getCust/', views.getCust), … -
Not running migrate command from Elastic Beanstalk (Django)
I'm using Amazon's Elastic Beanstalk and Django 2.5.5. I'm trying cloning about Airbnb. I uploaded makemigration's file (users, rooms, lists etc...) and I want to migrate using django.config but it's not working. (All migrations are working fine even with a fresh database in my local(sqlite3) Here is my container commands, container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true 02_compilemessages: command: "django-admin.py compilemessages" option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config/wsgi.py aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings I have confirmed that it does not run even when I use it with python manage.py What I missed... OTL -
when I am trying to deploy my app on heroku. Its getting error "no default language detected"
git push heroku master Counting objects: 8572, done. Delta compression using up to 4 threads. Compressing objects: 100% (5394/5394), done. Writing objects: 100% (8572/8572), 15.33 MiB | 1.15 MiB/s, done. Total 8572 (delta 2109), reused 8545 (delta 2100) remote: Compressing source files... done. remote: Building source: remote: remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to youtooapp. remote: To https://git.heroku.com/youtooapp.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/youtooapp.git' i also use a .gitignore file but when i try to push it give me this kind of error Guys help me with that i am stuck here.. -
Django select from a subquery to the same table
Basically I need to do the following (credits) in Django select t.*, p_25, p_75 from t join (select district, percentile_cont(0.25) within group (order by sales) as p_25, percentile_cont(0.75) within group (order by sales) as p_75 from t group by district ) td on t.district = td.district I've tried myriads of combinations with annotations and subqueries without any luck. I don't know how to do a join on the same table. SO search yields only posts concerning related fields. -
How to print foreignkey Model relation?
If in My model, Moneybook have a many moneylogs. so, I design a model Moneybook/models.py name = models.CharField(max_length=30, default="행복한 여행!") owner = models.ForeignKey( user_models.User, on_delete=models.CASCADE, related_name="owner") companion = models.ManyToManyField( user_models.User, related_name="companion", blank=True) country = CountryField() location = models.CharField(max_length=50, blank=True) start_date = models.DateTimeField(default=NOW) end_date = models.DateTimeField(default=NOW) Moneylog/models.py moneybook = models.ForeignKey( moneybook_models.Moneybook, on_delete=models.CASCADE, related_name="moneybooks") payer = models.ForeignKey( user_models.User, on_delete=models.CASCADE, related_name="payer") dutch_payer = models.ManyToManyField( user_models.User, related_name="dutch_payer") price = models.IntegerField() category = models.CharField(max_length=10) memo = models.TextField() If i want to load all the moneylogs in the each belonging moneybook. how can i load it? I guess... def moneybook_detail(request, pk): moneylogs=moneylog.filter(moneylog.moneybook.id=request.moneybook.id) return render(request, "moneybooks/detail.html") but error occured. moneylogs = moneylog.filter(request.moneybook.id=request.moneybook.id) SyntaxError: keyword can't be an expression -
Why does FieldDoesNotExist not work on POST.get()?
I want to catch an exception if the form POST does not contain a value for the field 'myfield': try: set_var = request.POST.get('myfield') except FieldDoesNotExist: raise FieldDoesNotExist("Your field is not here.") Why does this not raise an exception? -
How to safely inherit from django models.Model class?
I have a following DB structure: class Word(models.Model): original = models.CharField(max_length=40) translation = models.CharField(max_length=40) class Verb(Word): group = models.IntegerField(default=1) In my view, I need to create a Word object first, and after determination of its group (depending on Word.original), create a Verb object, and save it. What is the best way to inherit from the Word class and save the object as Verb ? There are several solutions that I've tried: 1) Modification of the __init__ method in Verb : class Verb(Word): group = models.IntegerField(default=1) def __init__(self, base_word): self.original = base_word.original self.translation = base_word.translation This causes a lot of errors, since I'm overriding the django's built-in __init__ method. 2) Using super().__init__(): class Verb(Word): group = models.IntegerField(default=1) def __init__(self, base_word): super().__init__() self.original = base_word.original self.translation = base_word.translation Apparently, this works pretty well: base_word = Word() new_verb = Verb(base_word) new_verb.save() But there are two problems: It causes an error when trying to see the objects in django admin page: __init__() takes 2 positional arguments but 9 were given This is still too much code, it doesn't feel right. I still need to write this: self.original = base_word.original self.translation = base_word.translation in every subclass. And this is just an example. In real project, … -
sending message from celery task to django channels problem in code
hey guys according to my previous Question : https://stackoverflow.com/questions/59681947/django-websocket-return-number-in-loop-as-same-as-other-recieves i have write some codes to create a loop in celery task and send it to all connected clients : so i do this: consumer.py : from channels.generic.websocket import WebsocketConsumer from .models import Crash , Crash_bets import time import random import string import hashlib import numpy import time import json from asgiref.sync import async_to_sync class ChatConsumer(WebsocketConsumer): def connect(self): if self.scope["session"]["email"]: self.accept() async_to_sync(self.channel_layer.group_add)("chat", self.channel_name) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)("chat", self.channel_name) def crash_zarib(self, event): # Send message to WebSocket self.send(text_data=event["text"]) def receive(self, text_data): self.send("hi") task.py: # Create your tasks here from __future__ import absolute_import, unicode_literals from celery import shared_task import time from channels.layers import get_channel_layer from asgiref.sync import async_to_sync @shared_task def crash(): while True: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)("chat", {"type": "crash_zarib", "text": "hii"}) but i cant send message to clients ! what is problem? -
social login drf django
i'm trying to implement social login with facebook and google.I am using Django-rest-framework-social-oauth2 serializers.py: class SocialSerializer(serializers.Serializer): provider = serializers.CharField(max_length=255, required=True) access_token = serializers.CharField(max_length=4096, required=True, trim_whitespace=True) views.py: class SocialLoginView(generics.GenericAPIView): serializer_class = serializers.SocialSerializer permission_classes = [permissions.AllowAny] def post(self, request): """Authenticate user through the provider and access_token""" serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) provider = serializer.data.get('provider', None) strategy = load_strategy(request) try: backend = load_backend(strategy=strategy, name=provider, redirect_uri=None) except MissingBackend: return Response({'error': 'Please provide a valid provider'}, status=status.HTTP_400_BAD_REQUEST) try: if isinstance(backend, BaseOAuth2): access_token = serializer.data.get('access_token') user = backend.do_auth(access_token) except HTTPError as error: return Response({ "error": { "access_token": "Invalid token", "details": str(error) } }, status=status.HTTP_400_BAD_REQUEST) except AuthTokenError as error: return Response({ "error": "Invalid credentials", "details": str(error) }, status=status.HTTP_400_BAD_REQUEST) try: authenticated_user = backend.do_auth(access_token, user=user) except HTTPError as error: return Response({ "error":"invalid token", "details": str(error) }, status=status.HTTP_400_BAD_REQUEST) except AuthForbidden as error: return Response({ "error":"invalid token", "details": str(error) }, status=status.HTTP_400_BAD_REQUEST) if authenticated_user and authenticated_user.is_active: #generate JWT token login(request, authenticated_user) data={ "token": jwt_encode_handler( jwt_payload_handler(user) )} #customize the response to your needs response = { "email": authenticated_user.email, "username": authenticated_user.username, "token": data.get('token') } return Response(status=status.HTTP_200_OK, data=response) urls.py: path('auth/oauth/login/', views.SocialLoginView.as_view()) settings.py: SOCIAL_AUTH_FACEBOOK_KEY = key SOCIAL_AUTH_FACEBOOK_SECRET = 'secret' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email' } FACEBOOK_EXTENDED_PERMISSIONS = ['email'] SOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username', 'first_name', … -
Ctrl+C Doesn't Let Me Quit the Server | Python Django
I am using PythonAnywhere to create a Django application following Corey Schafer's Youtube series on Django. For some reason in the BASH console I cannot exit the server in order to restart it using CTRL-C. When I do CTRL-C-enter nothing happens, and to check that it hasn't stopped, I run "python3.6 manage.py runserver" and it says that the port is still in use, hence proving that it the CTRL-C has not worked. How else can I close the server? Thank you -
templatetags vs custom template tags and filter in django
What is the difference between templatetags like the simple_tag vs the templatetag tag reference?. To better phrase my question, is the templatetag used for the purpose of Custom Template Tags and Filters or is it intended for another purpose entirely? -
Multiple Databases for Multiple Applications in Django - Can't route to the related database for a specific app
I've been setting up multiple databases for multiple applications. I want my app1 application use the db_app1 database. I've done everything in the tutorials but when I try to authenticate, it doesn't route to db_app1 database in the settings file, instead it routes to the default database. I need to use the db_app1 database for the app1 application. What am I missing? This is my dbRouter.py file: class App1DbRouter(object): route_app_labels = ['app1'] """ A router to control app1 app db operations """ def db_for_read(self, model, **hints): """ Attempts to read app1 models go to db_app1. """ if model._meta.app_label in self.route_app_labels: return 'db_app1' return None def db_for_write(self, model, **hints): """ Attempts to read app1 models go to db_app1. """ if model._meta.app_label in self.route_app_labels: return 'db_app1' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the app1 app is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'db_app1' return None My settings.py file .... INSTALLED_APPS = [ 'app1', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', ] .... .... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': … -
How do I pull the selected values from a select tag in HTML?
I've created a Django template and I'm trying to get the selected value from an options tag using JavaScript. However, while my current code runs without issue, there is no response when I click submit. The other webpage isn't loaded, regardless of what option I select. Can anyone help with why this is happening? <!doctype html> <h1>Searching for a particular tag?</h1> <input type="text" id="target"/> <select single="single" name="tag_options" id="tag_options"> <option value="0">Hello</option> <option value="1">Goodbye</option> </select> <button type="submit" onclick="search()">Submit</button> <br> <a href="{% url 'frontpage' %}">Front Page</a> <script> function search(){ var values = $('#tag_options').val(); this.document.location.href = "http://127.0.0.1:8000/searchtableresults/"+values; } </script> Additionally, I would eventually like to change the options from static choices to choices based on values I load in from a view, like so <!doctype html> <h1>Searching for a particular tag?</h1> <input type="text" id="target"/> <select single="single" name="tag_options" id="tag_options"> {% for possible_tag in possible_tags %} <option value="{{possible_tag}}">{{possible_tag}}</option> {% endfor %} </select> <button type="submit" onclick="search()">Submit</button> <br> <a href="{% url 'frontpage' %}">Front Page</a> <script> function search(){ var values = $('#tag_options').val(); this.document.location.href = "http://127.0.0.1:8000/searchtableresults/"+values; } </script> Would this work or do I need to try something else? -
Django post request is not functioning
I a currently working on a page that when a user clicks on an option from one table, that will change what data is populated on the other tables on the page. The post request is sent through and recieves a 200 message but the page does not reload. I even printed out all the variables in my views.py to make sure that I was collecting and correct data from the database and from the POST request. I am working with a Neo4j database and using neomodel to make my queries. My html page has a csrf token and that is being properly seen by my jquery. an example of one of the tables needed to be populated: <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Staff Needed: </div> <h1>{{ staffNeeded }}</h1> </div> <div class="col-auto"> <i class="fas fa-dollar-sign fa-2x text-gray-300"></i> </div> </div> my views.py: def staffinganalysis(request): contracts = ContractDataTable.getContractdata() allPositions = PositionsDataTable.getAllPositions() fillings = PositionsDataTable.getFillings() currentlyStaffed = len(fillings) if request.method == 'POST'(): postData = request.POST.copy() selectedContract = postData.get('contract') openings = PositionsDataTable.getOpenings(selectedContract) staffNeeded = len(openings) print(selectedContract) print(openings) return render(request,'staffingAnalysis.html', {'contracts': contracts, 'openings': openings, 'allPositions': allPositions, 'fillings': fillings, 'staffNeeded': staffNeeded, 'currentlyStaffed': currentlyStaffed}) if request.method == 'GET': return render(request, … -
Django: Local server gets the file sended by postman, remote server gets empty QueryDict
I have a problem with Django, on the local server I did tests with the sending of a file and it receives it well, instead when I uploaded the changes to the remote server and did the same tests, I found that the file is not received, if receives variables, only the file is what it does not receive. I tried other views where files are used and they work correctly. Any ideas to solve this :(? -
Why does application turn off after log in django-admin?
I am working on the web applications using Django (Django 3.0.2 and Python 3.7). I am doing using the tutorial based on Django Documentations. I do step by step and I do not add anything that is not in tutorial. I end tutorial01 and tutorial02. I am able to display prepared subpages, but when I want to log in Django Admin, the applications turns off. The only message which I receive is "Process finished with exit code -1" No error message causes that I do not know where is the problem. Maybe you have the same problem and you can solve it? I will be very glad for some help -
Django: filter on a self-reference foreign key attribute
In my Django 2.2 app, I have a model like this: class Folder(models.Model): name = models.CharField(max_length=100) parent_folder = models.ForeignKey("Folder", null=True, on_delete=models.SET_NULL) Basically, a folder can have a parent, this folder's parent itself can have a parent, and so on. So what I would like to do is, order the folders on their name attributes and starting with the top-level folders (so, the folders with no parent_folder) and then descending in the folder hierarchy. To illustrate, given the following objects in the table: +----+---------+---------------+ | id | name | parent_folder | +----+---------+---------------+ | 1 | fuel | <None> | | 2 | blabla | 1 | | 3 | volcano | 2 | | 4 | awful | 2 | | 5 | apple | 1 | | 6 | amazing | <None> | | 7 | wow | 6 | +----+---------+---------------+ The ordered output I except is: +----+---------+---------------+ | id | name | parent_folder | +----+---------+---------------+ | 6 | amazing | <None> | | 7 | wow | 6 | | 1 | fuel | <None> | | 5 | apple | 1 | | 2 | blabla | 1 | | 4 | awful | 2 | | 3 … -
Anonymous user has no attribute _meta in custom user model
I've been facing this problem for so long now and I'm done experimenting. Since I'm a newbie in Django kindly help. So, I've been using a custom user model but for some reason this Registration form doesn't work properly. I can't login using the method login(), though it'saving the data fine. Also, the login form doesn't allow any other user login other than the superuser. Here is the Error: AttributeError at /register/ 'AnonymousUser' object has no attribute '_meta' Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 2.2.4 Exception Type: AttributeError Exception Value: 'AnonymousUser' object has no attribute '_meta' Exception Location: C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py in inner, line 257 Python Executable: C:\Users\hello\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.4 Here is the code: models.py from django.db import models from django.conf import settings from django.contrib.auth import get_user_model from django.forms import ModelForm from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class CustomUserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, name ,password=None,is_active= True, is_staff=False, is_admin=False): if not name: raise ValueError("Users must've a name") if not email: raise ValueError("Users must've a email") if not password: raise ValueError("User must've a password") user_obj= self.model( email=self.normalize_email(email) , name= name ) user_obj.set_password(password) # Change password for the User user_obj.staff= is_staff user_obj.admin= is_admin user_obj.active= is_active user_obj.save(using =self._db) return user_obj def … -
Can't check profile model in django python shell
I am trying to run the django shell to understand what is happening to the photos when I upload them. However when I try to filter for particular users python manage.py shell rom django.contrib.auth.models import User user = User.objects.filter(username='name').first() I get the error message: AttributeError: Manager isn't available; 'auth.User' has been swapped for 'classroom.User' I am guessing this has something to do with this in settings.py AUTH_USER_MODEL = 'classroom.User' What should I be typing to get to look at the profile model -
Django: Is there a way to filter a model and ignore a stored hyphen?
I have a model that is like this: class Product(models.Model): name = models.CharField(max_length=5) An example of what the name would be is: A-123 Is there anyway to filter this name field so I can either input a hyphen or leave it out, and get the same result? For example, querying "A-123" and "A123" would return the same item. Using a regular filter I only get the result when I do "A-123". And if not, would the best solution be to make an on_save trigger that populates a secondary "searchable" field? That was going to be my original idea, but I worry that would be inefficient. -
Why is my html form not returning values to views.py through ajax?
Here is my html script. Basically, I'm trying to send the values (fruit_id and year_id) from my dropdown menus of the html form when I click the submit button, into the 'get_values' function in my views.py. {% load static %} <html> <head> <meta http-equiv="Content-Type" content="application/json; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet" /> <link href="{% static 'main.css' %}" rel="stylesheet" /> <link rel="shortcut icon" href="{% static 'images/favicon.ico' type='image/x-icon' %}"> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet"/> </head> <body> <div class="s01"> <form action="get_values/" method="POST" id="post-form">{% csrf_token %} <fieldset> <legend>Fruits</legend> </fieldset> <div class="inner-form"> <div class="dropdown1"> <div class="select"> <select name="dropdown1" id="dropdown1"> <option value="" disabled selected>Fruit Type</option> <option value="1">Mango</option> <option value="2">Orange</option> <option value="3">Lemon</option> <option value="4">Banana</option> </select> </div> </div> <div class="dropdown2"> <div class="select"> <select name="dropdown2" id="dropdown2"> <option value="" disabled selected>Harvest year</option> <option value="1">2020</option> <option value="2">2019</option> <option value="3">2018</option> <option value="4">2017</option> </select> </div> </div> <div class="search"> <button onclick="buttonclick(); "class="searchbtn" type="submit">Search</button> </div> </div> </form> </div> <script type="text/javascript"> var csrftoken = $("[name=csrfmiddlewaretoken]").val(); var g_e = document.getElementById("dropdown1"); var fruit_id = g_e.options[g_e.selectedIndex].value; var y_e = document.getElementById("dropdown2"); var year_id = y_e.options[y_e.selectedIndex].value; function sendtoserver(values) { $.ajax({ type: 'POST', headers:{ "X-CSRFToken": csrftoken }, data: { fruit_id:values[1], year_id:values[2] }, url: '{% url 'get_values' %}', success: function(data){ return (data); } …