Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got this error while executing command pip install jinja
Collecting Jinja Using cached Jinja-1.2.tar.gz (252 kB) ERROR: Command errored out with exit status 1: command: 'C:\Program Files\Python38\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\siddh\\AppData\\Local\\Temp\\pycharm-packaging\\Jinja\\setup.py'"'"'; __file__='"'"'C:\\Users\\siddh\\AppData\\Local\\Temp\\pycharm-packaging\\Jinja\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\siddh\AppData\Local\Temp\pycharm-packaging\Jinja\pip-egg-info' cwd: C:\Users\siddh\AppData\Local\Temp\pycharm-packaging\Jinja\ Complete output (6 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\siddh\AppData\Local\Temp\pycharm-packaging\Jinja\setup.py", line 28 except DistutilsError, e: ^ SyntaxError: invalid syntax ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
"kafka.errors.NoBrokersAvailable: NoBrokersAvailable" problem
i investigate too much topic in stackoverflow but i couldn't find solution for me. I have a docker-compose file and i am trying to set true parameters for configuration. Other than that i have a django api that manages web requests. My goal is when a user visits someone elses "post" i want to send a message to kafka "x user visited y users 'z' titled post". Finished all my configurations. In endpoint i configured a producer that sends message to kafka. After request to endpoint it gives me that error in title. How can i solve that ? django view.py; def get(self,request,post_id,format=None): """ Gets a post """ post = self.get_post(post_id) serializer = PostSerializer(post) send_data(post.owner, request.user, post, datetime.now().strftime("%d/%m/%Y %H:%M:%S") ) return Response(serializer.data) send data func; def send_data(visitor_user:User, owner_user:User, visitedPost:Post, timestamp:date): from kafka.errors import KafkaError from kafka import KafkaProducer producer = KafkaProducer( bootstrap_servers=['kafka:9092'] ) visitor = visitor_user.first_name + " " + visitor_user.last_name + "(username:" + visitor_user.username + ") " owner = owner_user.first_name + owner_user.last_name + "(username:" + owner_user.username + ") " post = "'" + visitedPost.title + "' titled post." message = timestamp + "->" + visitor + "read" + owner + " 's " + post result = producer.send( 'visitation-log', … -
Django ORM inner join between tables having foriegn key of third table
I want to perform an inner join between tables that holds the foreign key of another table in VIEW.PY The raw query that I am trying to make in django is "SELECT * FROM table3 t3 inner join table2 t2 on t2.C=t3.E where t2.B=0 and t2.D=t3.F and ( (t3.G =1234 and t3.H=0) or (t3.H!=0 and t3.G is null) )" how to do this in django Views -
Event Stream in Django
I want to write an app to get Cryptocurrency price and Update Data via Event Stream. I write a code to get price from free API, but now i can note update this data and want to use Event Stream. -
Ascii encoding error during sending a mail in python
I'm working on django app and i have a form contains multiple fields, i can get the fields values through views.py file and when i just fill the fields in english everything is working like a charm but in case of my app i need to fill them in arabic. When i was trying to do this and see if it is working the same i got the error below on my screen: UnicodeEncodeError at / 'ascii' codec can't encode characters in position 24-27: ordinal not in range(128) This is my code: def index(request): if request.POST.get('sendEmail'): pname = request.POST.get('patient_name') cr = request.POST.get('city_region') mz = request.POST.get('mazq') hno = request.POST.get('house_no') yn = request.POST.get('your_name') mob = request.POST.get('mobile') if (pname != '' and cr != '' and mz != '' and hno != '' and yn != ''): server = smtplib.SMTP('smtp.gmail.com', 587) server.connect("smtp.gmail.com",587) server.starttls() server.login(username, password) FROM = yn print(FROM) TO = ["alisattarbarani@gmail.com"] SUBJECT = "New Subject" TEXT = pname + "\n" + cr + "\n" + mz + "\n" + hno ms = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT + '\n' + '\n' + FROM) server.sendmail(FROM, TO, ms) server.quit() msg = "Successfull Email" return render(request, "index.html", {"msg": msg}) msg = "Empty Fields!" return render(request, "index.html", {"msg": … -
Django 3 - CreateView with initial ForeignKey field
and in advance thanks for your time. So I am trying to create a "restaurant rating" app on Django 3. I have set up the following models: # Table storing the different restaurants class Restaurant(models.Model): restaurant_name = models.CharField(max_length=200, unique=True) restaurant_address = models.CharField(max_length=200) restaurant_street_number = models.CharField(max_length=10) restaurant_city = models.CharField(max_length=200) restaurant_cuisine_type = models.CharField(max_length=200) def __str__(self): return self.restaurant_name + ' - ' + self.restaurant_city class UserReview(models.Model): # Defining the possible grades Grade_1 = 1 Grade_2 = 2 Grade_3 = 3 Grade_4 = 4 Grade_5 = 5 # All those grades will sit under Review_Grade to appear in choices Review_Grade = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5') ) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) user_review_grade = models.IntegerField(default=None, choices=Review_Grade) # default=None pour eviter d'avoir un bouton vide sur ma template user_review_comment = models.CharField(max_length=1500) def get_absolute_url(self): return reverse('restaurants:reviews', args=[self.id]) This is the form I am using: # Form for user reviews per restaurant class UserReviewForm(forms.ModelForm): class Meta: model = UserReview # restaurant = forms.ModelChoiceField(queryset=Restaurant.objects.filter(pk=id)) fields = [ 'restaurant', 'user_review_grade', 'user_review_comment' ] widgets = { 'restaurant': forms.HiddenInput, 'user_review_grade': forms.RadioSelect, 'user_review_comment': forms.Textarea } labels = { 'user_review_grade': 'Chose a satisfaction level:', 'user_review_comment': 'And write your comments:' } Here are my URLs: app_name = 'restaurants' urlpatterns … -
Saving photo modified by PIL - Python 3+ Django 2+
I am trying to save my photo recive from my form changed by PIL in the ImageField field. file = cd['custom_img'] #get my file from my form #resize image image = Image.open(file) (w, h) = image.size if (w > 1000): h = int(h * 1000. / w) w = 1000 image = image.resize((w, h), Image.ANTIALIAS) rgb_image = image.convert('RGB') #save in object thumb_io = BytesIO() #create a BytesIO object rgb_image.save(thumb_io, 'JPEG', quality=80) # save image to BytesIO object thumbnail = File(thumb_io) #create a django friendly File object owner.basic_img = thumbnail owner.save() My code does not return any result. Nothing is still written in my field. My attempts: 1.) Checking if the file will be saved I tried to check if my picture was saved correctly. Everything works well. A modified photo is created from the form sent. #resize image print(file) image = Image.open(file) print(image) (w, h) = image.size if (w > 1000): h = int(h * 1000. / w) w = 1000 image = image.resize((w, h), Image.ANTIALIAS) rgb_image = image.convert('RGB') #save rgb_image.save('my_image.jpg') 2.) I tried to save the photo according to this tutorial thumbnail = File(thumb_io, name=image.name) # create a django friendly File object My code raises an error here AttributeError: … -
Downloadable static file for authenticated users
I want to have a button for authenticated users to download a static file. I want to be sure only authenticated users can access these files. I know how to do something like this: <a href="/images/myw3schoolsimage.jpg" download> <img src="/images/myw3schoolsimage.jpg" alt="W3Schools"> </a> But that doesn't offer the security I'm looking for. I don't even know where to start with this -
Django - Foreign Keys and the Admin Page
Preface: I've been scouring stackoverflow but have found a solution - please point me in the correct direction if one does exist. I am trying to display the foreign key relations on the admin change page (i.e. the www.some.url/admin/<app>/<model>/<id>/change/ page): I have two models linked together via a foreign key relationship like so: # models.py class Bank(models.Model): name = models.CharField(max_length=100) class Branch(models.Model): bank = models.ForeignKey('Bank', on_delete=models.CASCADE, related_name='branches') name = models.CharField(max_length=100) And I have a model-admin like so: # admin.py class BankAdmin(admin.ModelAdmin): list_display = ('id', 'name',) How can I add the list of branches associated to a given bank on the django-admin-change page? Can I add something to my BankAdmin class that will achieve this? i.e. If I were to visit the admin page and click on a bank instance (i.e. www.some.url/admin/<app>/bank/2/change/) I would like to see the name of the bank and all of its foreign-key related branches. -
Stripe Checkout Client-only integration with Django
My goal is to integrate a Stripe Checkout Client-only integration with a Django app using these instructions. I copied the code provided by stripe into a html template. When I run the template, the checkout button appears but the stripe script is not executed when the button is clicked (no errors). I expected to be redirected to the stripe checkout page. I have tried moving the javascript to separate files in the static folder with the same result. Is the issue linking the button click to the javascript? Here is the html template with the stripe code inserted: {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <title></title> <!-- Load Stripe.js on your website. --> <script src="https://js.stripe.com/v3"></script> </head> <body> <!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. --> <button style="background-color:#6772E5;color:#FFF;padding:8px 12px;border:0;border-radius:4px;font-size:1em" id="checkout-button-sku_GyczP1qEmsj6eZ" role="link" > Checkout </button> <div id="error-message"></div> <script> (function() { var stripe = Stripe('pk_test_yWdjuG9EAuGjwpVenyzR6Ykn00AsFHsmGC'); var checkoutButton = document.getElementById('checkout-button-sku_GyczP1qEmsj6eZ'); checkoutButton.addEventListener('click', function () { // When the customer clicks on the button, redirect // them to Checkout. stripe.redirectToCheckout({ items: [{sku: 'sku_GyczP1qEmsj6eZ', quantity: 1}], // Do not rely on the redirect to the successUrl for fulfilling // purchases, customers may … -
adding a new column to postgres db django
I am trying to add a new column to an existing table with django in my postgres db. I did python3 makemigrations and python3 migrate but the new column does not appear. I also cleared migrations. It would still say the column does not exist on the db. The only workaround is to manually enter it in commandline or clear the whole database and start from scratch. Is there another alternative? -
Querying BigQuery Dataset from Django App Engine
I have data stored in BigQuery - it is a small dataset - roughly 500 rows. I want to be able to query this data and load it in to the front end of Django Application. What is the best practice for this type of data flow? I want to be able to make calls to the BigQuery API using Javascript. I will then parse the result of the query and serve it in the webpage. The alternative seems to be to find a way of making a regular copy of the BigQuery data which I could store in a Cloud Storage Bucket but this adds a potentially unnecessary level of complexity which I could hopefully avoid if there is a way to query the live dataset. -
updating values in django template in html input?
i am making a shopping cart , i want to update the value as the user updates the input field.. here is my code.. `<tr> <th scope="row">1</th> <td>${object['name']}</td> <td><input type="number" value=1 id=${object['id']}></td> <td>${object['price']*this.value}</td> </tr>`; the input field has a default value of 1. In the last tag i am multiplying value by the price. i am using "this" keyword because i want to apply the multiplied amount to the same row. It doesn't give me any error but it just prints "NaN" in the table not the figure. -
Is there any security issue while giving only "select" and "insert" permissions on all tables with psycopg2?
I think that writing a python script that includes admin credentials for postgresql database is not secure way. So I am trying to add another side: Django web server. But I have concerns yet again. I wanted to increase security by giving only "select" and "insert" permissions to a user and giving all other jobs (creating table, updating, again inserting) to a Django server. But I've started to think it's a bad idea. However I don't have another idea to do it securely. What do you think about that? -
Cannot set Django migrations in the right order
I added a new app 'portfolio' in my project, but since then migrations won't work anymore because Django seems to be trying to do them in the wrong order. Running migrations: Applying core.0001_initial... OK Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying user.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying data.0001_initial... OK Applying data.0002_auto_20200306_1522...Traceback (most recent call last): File "/opt/miniconda3/envs/cert_tool/lib/python3.7/site-packages/django/apps/registry.py", line 155, in get_app_config return self.app_configs[app_label] KeyError: 'portfolio' During handling of the above exception, another exception occurred: [...] LookupError: No installed app with label 'portfolio'. portfolio is listed in my INSTALLED_APPS : LOCAL_APPS = ( 'core', 'portfolio', 'user', 'data', 'editor', ) INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS + THIRD_PARTY_APPS If I add a dependency in the problematic data.0002_auto_20200306_1522 migration : class Migration(migrations.Migration): dependencies = [ ('data', '0001_initial'), ('portfolio', '0001_initial'), ] Other errors occur : django.db.migrations.exceptions.NodeNotFoundError: Migration data.0002_auto_20200306_1522 dependencies reference nonexistent parent node ('portfolio', '0001_initial') Traceback (most recent call last): File "/opt/miniconda3/envs/cert_tool/lib/python3.7/site-packages/django/db/migrations/loader.py", line 166, in check_key return self.graph.root_nodes(key[0])[0] IndexError: list index out of range During handling … -
What is the replacement for AWS infrastructure for Celery and Redis?
My application is written in django f/w which uses celery and redis for asynchronous tasks. I would like to autoscale workers according load/no.of messages in queue. For this, I would like to make use of different options provided by AWS. What is the replacement for AWS infrastructure for Celery and Redis? -
Where to save file that gets updated nightly?
I have a cron job that runs nightly and updates a json file, the json file is used by the site to build a map. Right now I am saving it to the MEDIA_ROOT is this a good practice, if not where should this file be saved to? -
Why PDF is not showing in angular
How can I show a pdf file while using a url? Frontend is in angular and backend is in django. PDF files can have dynamic links but those PDF are hosted on my own server. I know about X-Frame and X-Frame is DENY but I have tried all other options and still unable to fix it. I have tried almost every possible solution available online!! This is how I am trying to show my PDF in html file <div [innerHTML]="innerHtml"> </div> Here my code which inititalize innerHtml constructor( public sanitizer: DomSanitizer ) { } public setInnerHtml(pdfurl: string) { this.innerHtml = this.sanitizer.bypassSecurityTrustHtml( "<object data='" + pdfurl + "' type='application/pdf' class='embed-responsive-item' style='width: 100%; height: 90vh'>" + "Object " + pdfurl + " failed" + "</object>"); } but its showing this error on console and not showing any pdf Refused to display 'FULL_URL_OF_MY_PDF_FILE' in a frame because it set 'X-Frame-Options' to 'deny'. -
OpenCV videocapture returns False when calling isOpened(), although, another code example works well
So, I have a Django app, that manages some USB webcameras(all Logitech C525) This app takes frame from a VideoCapture object, when the GET request comes on specified API-endpoint and sends this frame to a server, to do some classification of object on image (usually fruits/vegetables) App receiving requests from clients, each client's IP address(app and clients are in the same local network) is binded to unique webcam ID Here's a snippet, that shows, how I'm searching binding between camera ID and logical device in /dev/video* to create a VideoCapture object: import re import subprocess class CameraBinder(object): def __init__(self): self.cam = 'C525' self.cam_id_list_in_dev_video = [] self.binding_between_udev_dev = None def find_cam_in_dev_video(self): cmd = ['/usr/bin/v4l2-ctl', '--list-devices'] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() out, err = out.strip(), err.strip() for line in [i.split("\n\t".encode()) for i in out.split("\n\n".encode())]: if self.cam.encode() in line[0]: cam_id_from_dev = re.search(r'(?<=/dev/video).*', line[1].decode('utf-8')) self.cam_id_list_in_dev_video.append(cam_id_from_dev.group(0)) process.kill() return self.cam_id_list_in_dev_video def bind_cam_between_dev_udev(self, cam_id): cmd = ['/bin/udevadm', 'info', '--attribute-walk', f'--name=/dev/video{cam_id}'] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() out, err = out.strip(), err.strip() kernel_for_udev_rules = re.search(r'(?<=KERNELS==\")[^\"]*', out.decode('utf-8')).group(0) serial = re.search(r'(?<=ATTRS{serial}==\")[^\"]*', out.decode('utf-8')).group(0) self.binding_between_udev_dev = f'{kernel_for_udev_rules} {serial}' process.kill() return self.binding_between_udev_dev Than, I have some Django management commands, that are configurating my system (collecting camera … -
Connecting to Aurora Serverless from Lambda Django?
I want to connect to my Aurora Serverless mysql database inside of my django Lambda function. Currently, I have: a Lambda function inside of the default VPC Uses the default security group Uses two public subnets I created Allows inbound requests from TCP ports 1024 - 65535 Allows outbound requests to Aurora/Mysql on Aurora security group an Aurora cluster inside of the default VPC Uses the same (default) VPC as the Lambda Uses two private subnets I created Allows inbound requests on port 3306 from Lambda security group an internet gateway for the default VPC a NAT gateway which pipes communications to the internet gateway a public routing table with the target ID of the internet gateway a private routing table with the target ID of the NAT gateway When I try to deploy my Lambda function to API gateway, the request times out: START RequestId: [request id] Version: $LATEST Instancing.. END RequestId: [request id] REPORT RequestId: [request id] Duration: 30030.15 ms Billed Duration: 30000 ms Memory Size: 512 MB Max Memory Used: 49 MB [time] [request id] Task timed out after 30.03 seconds When I remove the Lambda function from the VPC (setting the VPC to none in the … -
Django manage.py
after creating a new django project I wrote in powershell(run as administrator):PS C:\Users\User\Desktop\new> python manage.py runserver Then it shows something like this python : Python was not found but can be installed from the Microsoft Store: https://go.microsoft.com/fwlink?linkID=2082640 At line:1 char:1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Python was not ...?linkID=2082640:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError -
**SERIOUS ISSUE** django multiple search issue
my problem is when I'm adding simple functionality to individual search fields, it's working fine as I expected, like after adding functionality for location field it's working fine as i wanted but when I add same functionality for another field it's not showing results, even though 1st field was showing the results but now none of them showing anything. I'm not sure where's the problem I'm hanging around last 2 days. please help HTML search form <form action="{% url 'search-page' %}" method=""> <div class="row"> <div class="col-12 col-lg-10"> <div class="row"> <div class="col-12 col-md-6 col-lg-3"> <select name="location" id="" class="form-control"> <option value="">Location</option> {% for key,value in location_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-12 col-md-6 col-lg-3"> <select name="types" id="" class="form-control"> <option value="all-types">All Types</option> {% for key,value in property_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-12 col-md-6 col-lg-3"> <select name="city" id="" class="form-control"> <option value="01">All City</option> {% for key,value in city_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-12 col-md-6 col-lg-3"> <select name="status" id="all" class="form-control"> <option value="01">Status</option> {% for key,value in status_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div … -
failed Manage.py runserver command
i am a biginer in web developing, i am using pycharm and django 2.1 framework i installed django using ('py -m pip install django==2.1') and it is done. i started myweb project using ('py -m django-admin startproject myweb .') and it also done but when i try ('manage.py runserver') command, this is the result: enter code here (venv) C:\Users\مرحبا\PycharmProjects\Myweb>manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 27, 2020 - 20:08:58 Django version 3.0.4, using settings 'myweb.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread <bound method Thread.name of <Thread(django-main-thread, started daemon 5152)>>: Traceback (most recent call last): File "C:\Users\مرحبا\AppData\Local\Programs\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\مرحبا\AppData\Local\Programs\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\django\core\management\commands\runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\django\core\servers\basehttp.py", line 206, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\django\core\servers\basehttp.py", line 67, in __init__ super().__init__(*args, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\socketserver.py", line 449, in __init__ self.server_bind() File "C:\Users\مرحبا\AppData\Local\Programs\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\مرحبا\AppData\Local\Programs\lib\http\server.py", line 139, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\مرحبا\AppData\Local\Programs\lib\socket.py", line 680, in getfqdn aliases.insert(0, hostname) AttributeError: … -
Getting Following ! ACCESS to my shope/models
Traceback (most recent call last): File "h:/Django Framwork/WebCard/Shope/views.py", line 3, in from .models import product ImportError: attempted relative import with no known parent package I cant Import or use product.objects and get access to product.objects.aLL() funcs i want to see my models of product shope/views.py from django.shortcuts import render from django.http import HttpResponse from .models import product product.objects.all() def Index(request): return render(request,'Shope/index.html') def about(request): return render(request,'Shope/about.html') def contant(request): return HttpResponse('This page is working') def tracker(request): return HttpResponse('This page is working') def search(request): return HttpResponse('This page is working') def productview(request): return HttpResponse('This page is working') def checkout(request): return HttpResponse('This page is working') # print(product.objects.all()) # m = django.apps.apps.get_models() # print(m)** Shope\Model.py from django.db import models import django.db # Create your models here. class product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) product_catagory = models.CharField(max_length=50) product_subcatagory = models.CharField(max_length=50) product_desc = models.CharField(max_length=300) product_pricse = models.IntegerField(max_length=50,default=0) product_pub_date = models.DateField() product_imag = models.ImageField(upload_to='shope/images') def __str__(self): return self.product_name # print(product.objects.all()) enter image description here -
local variable 'routingForm' referenced before assignment
Am trying to do a form submit,but getting the error"local variable 'routingForm' referenced before assignment".please help me to solve this. *****forms.py***** from django import forms class routingForm(forms.Form): areaDigit = forms.CharField(label='areaDigit', max_length=100) product = forms.CharField(label='product', max_length=100) *****views.py***** from django.shortcuts import render from .forms import routingForm # Create your views here. from django.http import HttpResponse,HttpResponseRedirect from .models import Product,Routing_Dest_Area def get_route_list(request): #areaDigit= request.POST.get('areaDigit', False) #data=Routing_Dest_Area.objects.filter(areaDigit_pk=request.POST['areaDigit']) if request.method == "POST": #Get the posted form routingForm = routingForm(request.POST) if routingForm.is_valid(): areaDigit = routingForm.cleaned_data['areaDigit'] else: MyLoginForm = routingForm() return render(request, 'routing/test.html',{'areaDigit':areaDigit}) *****home.html***** <form method="POST" action="{% url 'get_route_list'%}" id="routingForm" name="routingForm"> {% csrf_token %} <div class="form-content"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input type="text" class="form-control" placeholder="Area String *" name"areaDigit" id="areaDigit" value="{{areaDigit}}"/> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="sel1">Select list (select one):</label> <select class="form-control" id="Product" name="product"> <option> 1</option> <option> 21</option> </select> </div> </div> </div> <button type="submit" class="btnSubmit">Submit</button>