I'm using two forms in one of my pages one for closing tickets and one for sending replies.
But problem is when I submit one of them another one is submitted too! and shows the flash massages. So I have two flash massages !
That gets more complicated since I'm checking some conditions to show first form and in that case which that form even doesn't again I have two flash massages !
#app.route('/edit-ticket', methods=['GET', 'POST'])
def edit_ticket():
if session['logged_in'] == True:
trackingNumberLink = int(request.args.get('trackingNumber'))
closeForm = CloseTicket()
editForm = EditTicket()
GetTicketStatus = tickets.find_one({"trackingNumber": trackingNumberLink})
if closeForm.validate_on_submit():
tickets.update_one({"trackingNumber": trackingNumberLink},
{"$set": {"status": "پاسخ داده شده", "order": 2}})
flash(u"تیکت مورد نظر با موفقیت بسته شد.")
if editForm.validate_on_submit():
replyDate = jdatetime.datetime.now()
tickets.update_one({"trackingNumber": trackingNumberLink},
{"$set": {"status": "در حال بررسی", "order": 1}})
tickets.update_one({"trackingNumber": trackingNumberLink},
{"$push": {"replies": {"rep": {"mass": editForm.ticketMassage.data,
"date": replyDate.strftime("%H:%M:%S %d-%m-%y "),
"HowSent": "user"}}}})
flash(u"پاسخ با موفقیت ارسال شد.")
return render_template('edit-ticket.html', Title="ویرایش تیکت", closeForm=closeForm,
editForm=editForm, CanUserCloseTicket=GetTicketStatus)
else:
return redirect(url_for('Login'))
HTML:
{% extends "layout.html" %}
{% block content_main %}
<div class="container content-box">
<div class="row">
<div class="col-sm-12">
<div class="FormSection center-form">
<fieldset class="form-group">
<legend class="border-bottom mb-4">ویرایش تیکت</legend>
</fieldset>
<form method="post" action="">
{{ editForm.hidden_tag() }}
<div class="form-group">
{{ editForm.ticketMassage.label(class="form-control-label") }}
{% if editForm.ticketMassage.errors %}
{{ editForm.ticketMassage(class="form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in editForm.ticketMassage.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ editForm.ticketMassage(class="form-control-lg") }}
{% endif %}
</div>
<div class="form-group">
{{ editForm.submit(class="btn btn-outline-info") }}
</div>
</form>
</div>
{% if CanUserCloseTicket['status'] != "پاسخ داده شده" %}
<div class="FormSection center-form">
<form method="post" action="">
{{ closeForm.hidden_tag() }}
<div class="form-group">
{{ closeForm.submitCloseTicket(class="btn btn-outline-info") }}
</div>
</form>
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock content_main %}
Forms Class:
class EditTicket(FlaskForm):
ticketMassage = TextAreaField('متن پیام:',
description=u'پاسخ خود را بنویسید.',
validators=[data_required(), Length(min=20, max=500)], )
submit = SubmitField('ویرایش تیکت')
class CloseTicket(FlaskForm):
submitCloseTicket = SubmitField('بستن تیکت')
Render the form tag with an id attribute and for the submit and input tags use the form attribute.
<form id="edit-ticket">
{{ form.submit(form="edit-ticket") }}
The form element that the input element is associated with (its form owner). The value of the attribute must be an id of a element in the same document. If this attribute isn't used, the element is associated with its nearest ancestor element, if any. This attribute lets you to place elements anywhere within a document, not just as descendants of form elements.
Update Use different names for submit then in your views.py if close_form.validate_on_submit() and close_form.close.data:
from flask import Flask, render_template
from flask_wtf import FlaskForm, CSRFProtect
from wtforms.fields import SubmitField, TextAreaField
app = Flask(__name__)
app.config['SECRET_KEY'] = '^%huYtFd90;90jjj'
app.config['UPLOADED_FILES'] = 'static/files'
csrf = CSRFProtect(app)
class EditTicketForm(FlaskForm):
ticket_message = TextAreaField()
edit = SubmitField()
class CloseTicketForm(FlaskForm):
message = TextAreaField()
close = SubmitField()
#app.route('/edit-ticket', methods=['GET', 'POST'])
def edit_ticket():
close_form = CloseTicketForm()
edit_form = EditTicketForm()
if close_form.is_submitted() and close_form.close.data:
if close_form.validate():
x = close_form.message.data
return x.upper()
if edit_form.is_submitted() and edit_form.edit.data:
if edit_form.validate():
y = edit_form.ticket_message.data
return y.upper()
return render_template('edit-ticket.html', close_form=close_form, edit_form=edit_form)
if __name__ == "__main__":
app.run(debug=True)
edit-ticket.html
<form method="post" id="edit-form" novalidate></form>
<form method="post" id="close-form" novalidate></form>
{{ edit_form.csrf_token(form="edit-form") }}
{{ close_form.csrf_token(form="close-form") }}
{{ edit_form.ticket_message(form="edit-form") }}
{{ edit_form.edit(form="edit-form") }}
{{ close_form.message(form="close-form") }}
{{ close_form.close(form="close-form") }}
Put an action on your forms instead of leaving it blank:
<form method="post" action="/close-ticket"> ... </form>
<form method="post" action="/edit-ticket"> ... </form>
Define explicit functions to handle each action. One action, one function - keep it simple. Split out and re-use the logged-in logic for each.
#app.route('/close-ticket', methods=['POST'])
def close_ticket():
if session['logged_in'] != True:
return redirect(url_for('Login'))
# closeForm handling, etc....
#app.route('/edit-ticket', methods=['POST'])
def edit_ticket():
if session['logged_in'] != True:
return redirect(url_for('Login'))
# editForm handling, etc....
Related
I'm trying to check if the user is logged in or not to change nav elements and to do more stuff and here is my code
And when I do this
print(attempted_account.is_authenticated) result => True
I think that the problem will be in base.html file so I hope you can help me.
routs.py:
#app.route('/login',methods=['GET','POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
attempted_account = Account.query.filter_by(email=form.email.data).first()
print(attempted_account.is_authenticated)
if attempted_account and attempted_account.check_password(attempted_password=form.password.data):
login_user(attempted_account)
flash('Success login ',category='success')
return redirect(url_for('page',id=1))
elif not attempted_account:
flash("The E-mail doesn't exist",category='danger')
else:
flash('Tha password is incorrect',category='danger')
return render_template('login.html',form=form)
base.html
<nav>
<ul>
<li><a class="home" href="{{ url_for('home') }}">Market</a></li>
<li>Go shopping</li>
</ul>
{% if current_user.is_authenticated %}
<ul>
<li>Logout</li>
</ul>
{% else %}
<ul>
<li>Sign up</li>
<li>Login</li>
</ul>
{% endif %}
</nav>
login.html
{% extends 'base.html' %}
{% block title %}
Login
{% endblock %}
{% block content %}
<div class="container">
<form method="POST" class="form-register" style="text-align: center;">
{{ form.hidden_tag() }}
{{ form.csrf_token }}
{{ form.email.label() }}
{{ form.email(class='form-control',placeholder='example#example.com') }}
<br>
{{ form.password.label() }}
{{ form.password(class='form-control',placeholder='Password') }}
<br>
{{ form.submit(class='btn btn-lg btn-block btn-primary') }}
</form>
</div>
{% endblock %}
Please note that I called my model Account not User
Edit:
Here is models.py:
from market import db
from market import bcrypt,login_manager
from flask_login import UserMixin
#login_manager.user_loader
def load_user(user_id):
return Account.query.filter_by(id=user_id)
class Account(db.Model,UserMixin):
id = db.Column(db.Integer,primary_key = True)
first_name = db.Column(db.String(length = 50),nullable = False)
last_name = db.Column(db.String(length = 50),nullable =False)
email = db.Column(db.String(length = 100),nullable =False,unique = True)
password_hashed = db.Column(db.String(length = 25),nullable = False)
#country = db.Column(db.String,nullable = False)
items = db.relationship('Item',backref = 'owner',lazy = True)
#property
def password(self):
return self.password
#password.setter
def password(self,plain_text_password):
self.password_hashed = bcrypt.generate_password_hash(plain_text_password).decode('utf-8')
def check_password(self,attempted_password):
return bcrypt.check_password_hash(self.password_hashed,attempted_password)
The issue is probably because you're returning a query result in the user_loader callback instead of an Account object.
Instead of returning Account.query.filter_by(id=user_id) try returning Account.query.filter_by(id=user_id).first().
Hope it works.
views.py
#login_required()
def Info_anlegen(request, id=None):
item = get_object_or_404(Kunden, id=id)
kontaktform_form = InfoForm(request.POST or None, instance=item)
if WindowsHome.objects.filter(KN=item.KN).exists():
item1 = WindowsHome.objects.get(KN=item.KN)
winform_form = InfoWinForm(request.POST or None, instance=item1)
if kontaktform_form.is_valid():
return redirect('/Verwaltung/KontaktAnlegen')
else:
form = acroniform(instance=item)
return render(request, 'blog/infokontakt.html',
{'kontaktform_form': kontaktform_form, 'winform_form': winform_form})
infokontakt.html
{% extends 'blog/base.html' %}
{% load bootstrap4 %}
{% block supertitle %} InfoPage {% endblock %}
{% block Content %}
{% load static %}
<html>
<div class="p-2 mb-1 bg-white text-black">
<head>
<div class="d-flex justify-content-center align-items-center container ">
<img src="{% static 'blog/Gubler.jpeg' %}" alt="Gubler" height="300" width="700">
</div>
</head>
<br>
<body>
<form class="form-row" action="" method="post">
<div style="margin-left: 2.5em;">
<font color="black">
<div class="col-sm-10 col-form-label">
{% csrf_token %}
{% bootstrap_form kontaktform_form %}
</div>
</font>
</div>
</form>
<form class="form-row" action="" method="post">
<div style="margin-left: 2.5em;">
<font color="black">
<div class="col-sm-10 col-form-label">
{% csrf_token %}
{% bootstrap_form winform_form %}
</div>
</font>
</div>
</form>
My Problem is:
if WindowsHome.KN exists it gets displayed
but if it does not exist i get the error
UnboundLocalError at /Verwaltung/InfoKontakt/6
local variable 'winform_form' referenced before assignment
Request Method: GET
Request URL: http://127.0.0.1:8000/Verwaltung/InfoKontakt/6
Django Version: 3.0.1
Exception Type: UnboundLocalError
Exception Value:
local variable 'winform_form' referenced before assignment
How do i say that if the db entry does not exist it should not display the form ?
OR
if the db entry does not exist just display a spacing " "
You try to send winform_form to your template but it is not set when WindowsHome.objects.filter(KN=item.KN).exists() is false.
You should probably do something like this:
#login_required()
def Info_anlegen(request, id=None):
context = {}
item = get_object_or_404(Kunden, id=id)
kontaktform_form = InfoForm(request.POST or None, instance=item)
if WindowsHome.objects.filter(KN=item.KN).exists():
item1 = WindowsHome.objects.get(KN=item.KN)
winform_form = InfoWinForm(request.POST or None, instance=item1)
context['winform_form'] = winform_form
if kontaktform_form.is_valid():
return redirect('/Verwaltung/KontaktAnlegen')
else:
form = acroniform(instance=item)
context['kontaktform_form'] = kontaktform_form
return render(request, 'blog/infokontakt.html', context)
You can initialize winform_form as None in the begining of your method, so that it will not throw that error. (i.e)
def Info_anlegen(request, id=None):
winform_form = None # Do like this
item = get_object_or_404(Kunden, id=id)
and also in your template you can use django template tags {% if %} ... {% endif %}
i.e
{% if winform_form %}
<form class="form-row" action="" method="post">
<div style="margin-left: 2.5em;">
<font color="black">
<div class="col-sm-10 col-form-label">
{% csrf_token %}
{% bootstrap_form winform_form %}
</div>
</font>
</div>
</form>
{% endif %}
So... I'm trying to dynamically fill option from a selectfield using data coming from a firestore database.
I initialise a new object from my Items class, I load my form named AjouterForm(), then I call my function getItemsDB() that populate the var fields (it's a list) using data from firestore db, and finally I try to populate the selectfield itemFields.
I can launch the program but when I go on "ajouter" I get an error :
ValueError: too many values to unpack (expected 2)
routes.py
#app.route("/ajouter", methods=['GET', 'POST'])
def ajouter():
try:
items = Items()
form = AjouterForm()
items.getItemsDB()
form.itemsFields.choices = items.fields
except ValueError:
flash("Problème", 'danger')
return render_template('ajouter.html', title='Ajouter', form=form)
ajouter.html
<div class="content-section">
<form method="POST" action="">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Ajouter</legend>
<div class="row">
<div class="col">
<div class="form-group">
{{ form.type.label }}
{{ form.type }}
</div>
</div>
<div class="col">
<div class="form-group">
{{ form.customer.label }}
{{ form.customer }}
</div>
</div>
</div>
<div class="output">
<div id="INVOICE" class="hidden INVOICE">
<!--A compléter-->
</div>
<div id="ORDER" class="hidden ORDER">
{{ form.block.label }}
{{ form.block }}
</div>
<div id="SERVICE_REQUEST" class="hidden SERVICE_REQUEST">
<!--A compléter-->
</div>
<div class="output2">
<div id="ITEMS" class="hidden2 ITEMS">
{{ form.itemsFields.label }}
{{ form.itemsFields }}
</div>
<div id="PARTNERS">
</div>
<div id="fields">
</div>
</div>
</div>
</fieldset>
</form>
</div>
forms.py
class AjouterForm(FlaskForm):
type = SelectField("Type", choices=[("INVOICE","invoice"), ("ORDER","order"), ("SERVICE_REQUEST", "service_request")], id="type")
block = SelectField("Block", choices=[("ITEMS","items"), ("PARTNERS","partners"), ("fields","fields")], id="block")
itemsFields = SelectField("Champs", choices=[], coerce=list, id="itemsField")
tailleDocX = IntegerField("Taille X", validators=[DataRequired()])
tailleDocY = IntegerField("Taille Y", validators=[DataRequired()])
customer = SelectField("Customer", choices=[("mlt", "mlt")])
submit = SubmitField('Confirmer')
models.py
class Items(object):
def __init__(self):
self.fields = []
def getItemsDB(self):
doc_ref = db.collection("customizing").document("FORMS")
doc = doc_ref.get()
datas = doc.get("ORDER").get("ITEMS").get("fields")
for data in datas:
self.fields.append(data)
I'm kinda new to python, flask and firestore database and I can't manage to find what is causing this error, hope my english isn't to bad ! :-)
FINALLY I FIXED IT !
I found out that selectfields only accept tuple, I did this :
items = Items()
items.getItemsDB()
form.itemsFields.choices = []
for fields in items.fields:
form.itemsFields.choices += [(fields, fields)]
I'm trying to implement both searching posts and create a post in single view.
views.py
class HomeView(TemplateView):
template_name = 'home/home.html'
def get(self, request):
post_list = None
form = HomeForm(self.request.GET or None)
form1 = CommentForm(self.request.GET or None)
posts = Post.objects.filter(user = request.user).order_by('-created')
comments = Comment.objects.all()
users = User.objects.exclude(id=request.user.id)
query = request.GET.get('q')
if query:
post_list = Post.objects.filter(
Q(post__icontains=query)
)
context = {
'posts_list': post_list, }
print(post_list)
args = {
'form': form, 'posts': posts, 'users': users, 'form1':form1,
'comments':comments,'post_list':post_list,
}
return render(request, self.template_name, args)
def post(self, request):
form1 = CommentForm()
text = ''
if request.method=='GET' and 'btn1' in request.POST:
post_list = Post.published.all()
query = request.GET.get('q')
if query:
post_list = Post.objects.filter(
Q(post__icontains=query)
)
context = {
'posts_list': posts_list,
}
return redirect('home:home')
if request.method=='POST' and 'btn' in request.POST:
form = HomeForm(request.POST,request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
text = form.cleaned_data['post']
form = HomeForm()
form1 = CommentForm()
return redirect('home:home')
html code
<form enctype="multipart/form-data" class="form-inline my-2 my-lg-0" action=".">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name='q'>
<button class="btn btn-outline-success my-2 my-sm-0" name="btn1" type="submit">Search</button>
{% block body %}
<div class="container">
<div class="col-md-8">
<h2>Home</h2>
<form method="POST" enctype="multipart/form-data" type = 'file'>
{% csrf_token %}
{{ form.post }}
{{ form.image }}
<br>
<button name="btn" type="submit">Submit</button>
</form>
<h2>{{ text }}</h2>
{% for post in posts %}
<h1>{{post.id}}.{{ post.post }}</h1>
<br>
<img src="{{ post.image.url }}" width = 240 >
<p>Posted by {{ post.user.get_full_name }} on {{ post.created }}</p>
<!-- <form action="{% url 'home:cmnt' pk=post.id %}" method="POST" enctype="multipart/form-data" type = 'file'>
{% csrf_token %}
{{ form1.content }}
<br>
<button type="submit">Submit</button>
</form> -->
{{comments.count}} comment{{comments|pluralize}}<br>
{% for comment in post.comment_set.all %}
<small><b>{{ comment.comment }}</b></small>
<p>commented by {{ comment.user.get_full_name }} on {{ comment.created }}</p>
{% endfor %}
{% endfor %}
</div>
</div>
{% endblock %}
from this code I get the query value entered by the user.
when I implement this code I need to fill both the forms post create and search form but, I need to submit only one form at a time
when I fill both the forms and submit I get URL like this
http://127.0.0.1:8000/home/?q=django+&csrfmiddlewaretoken=OsNRlkvRjSHHuNYMxhZS9MFushCzCTZtjFvgEb5qFFybovBhWI3X0uufvd8bO8WS&post=asdsad&image=7653_1792089421024273_590924154993413545_n.jpg&btn=
I need a code which implements:
when submitted post create form create the post and return
when submitted search form load the respective results from database
I am trying to set up two different forms on the same Flask page with validators, but it keeps telling me my forms are not defined. I get error:
The code is designed to allow users to input a number and check if it is abundant, perfect, or deficient, and then with a separate form to allow users to define a range and get how many abundant, perfect or deficient numbers there are within that range.
My code is as follows:
from flask import Flask, render_template, request
from flask_wtf import Form
from wtforms import IntegerField
from wtforms.validators import InputRequired
from perfect_numbers import classify, listInRange
app = Flask(__name__)
app.config['SECRET_KEY'] = 'DontTellAnyone'
class PerfectForm(Form):
inputNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')])
class PerfectRangeForm(Form):
startNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')])
endNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')])
#app.route('/', methods=['GET', 'POST'])
def index():
form1 = PerfectForm(request.form, prefix="form1")
num = 1
Classify = classify(num)
if form.validate_on_submit() and form.data:
num = request.form1['inputNumber']
Classify = classify(form1.inputNumber.data)
return render_template('index.html', form1=form1, num=num, classify=Classify)
return render_template('index.html', num=1, form1=form1, classify=Classify)
#app.route('/aliRange', methods=['GET', 'POST'])
def aliRange():
form2 = PerfectRangeForm(request.form2, prefix="form2")
startNumber = 1
endNumber = 1
aliquot = 'abundant'
Classify = classify(num)
ListInRange = listInRange(startNumber, endNumber, aliquot)
if form2.validate_on_submit() and form2.data:
startNumber = request.form2['startNumber']
endNumber = request.form2['endNumber']
aliquot = request.form2['aliquot']
ListInRange = listInRange(startNumber, endNumber, aliquot)
return render_template('index.html', form2=form2, startNumber=startNumber, endNumber=endNumber, ListInRange=listInRange)
return render_template('index.html', form2=form2, startNumber=startNumber, endNumber=endNumber, ListInRange=listInRange)
if __name__ == '__main__':
app.run(debug=True)
index.html:
{% from "_formhelpers.html" import render_field %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>WTForms</title>
</head>
<body>
<div>
<form action="/" method="POST">
<dl>
{% if form1 %}
{{ form1.csrf_token }}
{{ render_field(form1.inputNumber) }}
{% endif %}
<input type="submit" value="submit1">
</dl>
</form>
</div>
<div>
{{ num }} is {{ classify }}
</div>
<div></div>
<div>
<form action="/aliRange" method="POST">
<div class="form-group">
<p>Input a start number and an end number to return a list of...</p>
<select class="form-control" action="/aliRange" name="aliquot" method="POST">
<option value = 'abundant'>Abundant</option>
<option value = 'perfect'>Perfect</option>
<option value = 'deficient'>Deficient</option>
</select>
<p>...numbers within that range</p>
<form action="/aliRange" method="POST">
<dl>
{% if form2 %}
{{ form2.csrf_token }}
{{ render_field(form2.startNumber) }}
{{ render_field(form2.endNumber) }}
{% endif %}
<input class="btn btn-primary" type="submit" value="submit">
</dl>
</form>
</div>
</form>
The {{ aliquot }} numbers between {{ startNumber }} and {{ endNumber }} are:
{{ listInRange }}
</div>
</body>
</html>
Error I get atm is: AttributeError: 'Request' object has no attribute 'form1'
EDIT:
You can simplify your code using a single view, using the submit value to differentiate the handling of the first form and the second one.
The modified code is:
class PerfectForm(Form):
inputNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')])
class PerfectRangeForm(Form):
startNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')])
endNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')])
aliquot = StringField('input a kind', default='perfect')
#app.route('/', methods=['GET', 'POST'])
def index():
form1 = PerfectForm(request.form, prefix="form1")
form2 = PerfectRangeForm(request.form, prefix="form2")
num = 1
Classify = classify(num)
startNumber = 1
endNumber = 1
aliquot = 'abundant'
ListInRange = listInRange(startNumber, endNumber, aliquot)
if request.form.get('submit') == 'submit-1':
if form1.validate_on_submit() and form1.data:
num = form1.data['inputNumber']
Classify = classify(num)
elif request.form.get('submit') == 'submit-2':
if form2.validate_on_submit() and form2.data:
startNumber = form2.data['startNumber']
endNumber = form2.data['endNumber']
aliquot = form2.data['aliquot']
ListInRange = listInRange(startNumber, endNumber, aliquot)
return render_template('index.html',
num=num, classify=Classify,
startNumber=startNumber, endNumber=endNumber, aliquot=aliquot, ListInRange=ListInRange,
form1=form1, form2=form2)
if __name__ == '__main__':
app.run(debug=True)
and the modified template index.html is:
{% from "_formhelpers.html" import render_field %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>WTForms</title>
</head>
<body>
<div>
<form action="/" method="POST">
<dl>
{{ form1.csrf_token }}
{{ render_field(form1.inputNumber) }}
<input type="submit" name="submit" value="submit-1">
</dl>
</form>
</div>
{% if num %}
<div>
{{ num }} is {{ classify }}
</div>
{% endif %}
<hr />
<div>
<form action="/" method="POST">
{{ form2.csrf_token }}
<div class="form-group">
<p>Input a start number and an end number to return a list of...</p>
<select class="form-control" action="/aliRange" name="aliquot" method="POST">
<option value = 'abundant'>Abundant</option>
<option value = 'perfect'>Perfect</option>
<option value = 'deficient'>Deficient</option>
</select>
<p>...numbers within that range</p>
<dl>
{{ render_field(form2.startNumber) }}
{{ render_field(form2.endNumber) }}
</dl>
<input class="btn btn-primary" type="submit" name="submit" value="submit-2">
</div>
</form>
<div>
The {{ aliquot }} numbers between {{ startNumber }} and {{ endNumber }} are:
{{ listInRange }}
</div>
</div>
</body>
</html>
OLD:
You are using form1 in the template but passing form inside the template context:
render_template('index.html', form=form1, num=num, classify=Classify)
You can either change form1 to form inside the template, or pass form1=form1 in the above line.
If you are rendering multiple forms inside the same template, you have to pass all the respective form variables: form1, form2, ... from all the views rendering that template. Otherwise the template rendering will raise the error you are seeing.
If you are interested in having a single form rendered among all the possible ones inside the template, you can use conditional rendering using
{% if form1 %}
<div>
<form action="/" method="POST">
<dl>
{{ form1.csrf_token }}
...
</dl>
</form>
</div>
{% endif %}
{% if form2 %}
<form action="/aliRange" method="POST">
...
</form>
{% endif %}
...
Also, your html seems incorrect to me, because you have a form nested inside another form. Not sure about what you are trying to obtain there.