Django - Nested loops and template rendering with Forms - django

Is there a way to set a variable after a return statement?
I am trying to execute a for loop with a if clause. At first the if clause is False and after the for loop is executed completely it should render a template with a form and then set the variable to True afterwards. Then the for loop gets executed again but this time it should execute the if statement and submit the Form which is something like ("Are you sure?" and then Continue or Cancel). I tried it with using nested loops (for loop inside a while loop) but the return render statement to render the template with the request is not working with setting the variable afterwards.
This is my views.py
def file_upload(request):
if request.method == "POST":
# Wenn CSV Datei valide ist --> Datei hochladen
csv_file = request.FILES['file']
csv_file.seek(0)
decoded_file = csv_file.read().decode('utf-8').splitlines()
reader = csv.reader(decoded_file)
updated_list = list()
created_list = list()
s = False
form2 = ConfirmationForm(request.POST, request.FILES)
while (True):
for row in reader:
count += 1
try:
datet = datetime.now().date()
datum = datet.strftime("%d.%m.%Y")
row[7] = datum
row[8] = str(request.user)
#d = [row[0], row[1], row[2], row[3], row[4]]
dataset1 = CSV5.objects.filter(gebaeudebereich=row[0],
gebaeudenummer=row[1], ebene=row[2],
raum=row[3], dose=row[4])#.values_list("gebaeudebereich", "gebaeudenummer",
# "ebene", "raum", "dose")
dataset2 = CSV5.objects.filter(switch_ip=row[5], switch_port=row[6])#.values_list("switch_ip", "switch_port")
ds1 = CSV5.objects.values_list("gebaeudebereich", "gebaeudenummer", "ebene",
"raum", "dose")
ds2 = CSV5.objects.values_list("switch_ip", "switch_port")
#print("ds1: ", ds1)
print("count: ", count)
print("dataset1: ", dataset1)
print("dataset2: ", dataset2)
print("dataset1: ", dataset1.exists())
print("dataset2: ", dataset2.exists())
print("s: ", s)
if (dataset1.exists() and not dataset2.exists()):
#instance = get_object_or_404(CSV5, id=count)
print("Fall 1")
ins = CSV5.objects.filter(gebaeudebereich=row[0],
gebaeudenummer=row[1], ebene=row[2],
raum=row[3], dose=row[4])
#liste.append(ins.values_list())
#print("liste: ", liste)
print ("instance: ", ins)
if form2.is_valid() and s == True:
ins.update(switch_ip=row[5], switch_port=row[6], datum = row[7], akteur = row[8])
else:
updated_list.append(ins)
updated_obj += 1
elif not dataset1.exists() and dataset2.exists():
print("Fall 2")
ins = CSV5.objects.filter(switch_ip=row[5], switch_port=row[6])
print("instance: ", ins)
if form2.is_valid() and s == True:
ins.update(gebaeudebereich = row[0], gebaeudenummer = row[1], ebene = row[2], raum = row[3],
dose = row[4], datum = row[7], akteur = row[8])
else:
updated_list.append(ins.values_list())
print("dat2: ", dataset2)
updated_obj += 1
elif (dataset1.exists() and dataset2.exists()):
print("Fall 3")
#liste.append(dataset1)
#print("liste: ", liste)
duplicate_obj += 1
elif not (dataset1.exists() and dataset2.exists()):
print("Fall 4")
if form2.is_valid() and s == True:
ins = CSV5.objects.get_or_create(id=CSV5.objects.count() + 1, gebaeudebereich=row[0],
gebaeudenummer=row[1], ebene=row[2],
raum=row[3], dose=row[4], switch_ip=row[5], switch_port=row[6],
datum=row[7], akteur=row[8])
created_list.append(ins)
ins.save()
created_obj += 1
except IndexError:
print("IndexError")
break
except IntegrityError:
duplicate_obj += 1
print("IntegrityError")
if s != False:
messages.success(request, "objects created: %s " % created_obj)
messages.success(request, "objects updated: %s " % updated_obj)
messages.success(request, "duplicate objects: %s " % duplicate_obj)
break
elif s == False:
messages.success(request, "Einträge die neu hinzugefügt werden: %s " % created_list)
messages.success(request, "Einträge die überschrieben werden: %s " % updated_list)
messages.success(request, "Duplikate: %s " % duplicate_obj)
form = ConfirmationForm()
return render(request, "appp/confirmation.html", {'form' : form})
s = True
form = UploadFileForm()
return render(
request, "appp/file_upload.html", {"form": form}
)
Here is my ConfirmationForm:
class ConfirmationForm(forms.Form):
class Meta:
model = CSV5
fields = ('gebaeudebereich', 'gebaeudenummer', 'ebene', 'raum', 'dose',
'switch_ip', 'switch_port', 'datum', 'akteur',)
confirmation.html
{% extends 'appp/base.html' %}
{% block body %}
<h2>Bestätigung</h2>
{% if user.is_authenticated %}
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" onclick="return confirm('Sollen die angezeigten Daten in der Datenbank gespeicher werden?')">Speichern</button>
</form>
<a href = "{% url 'appp:index' %}">
<button>Cancel</button>
</a>
{% endif %}
{% endblock %}
And finally my models.py
class CSV5(models.Model):
gebaeudebereich = models.CharField(max_length=100, blank=True, null=True)
gebaeudenummer = models.CharField(max_length=100, blank=True, null=True)
ebene = models.CharField(max_length=100, blank=True, null=True)
raum = models.CharField(max_length=100, blank=True, null=True)
dose = models.CharField(max_length=100, blank=True, null=True)
switch_ip = models.CharField(max_length=100, blank=True, null=True)
switch_port = models.CharField(max_length=100, blank=True, null=True)
datum = models.CharField(max_length=100)
akteur = models.CharField(max_length=100)
class Meta:
unique_together = (("gebaeudebereich", "gebaeudenummer", "ebene", "raum", "dose"), ("switch_ip", "switch_port"))
So the for loop iterates through every entry and since s is False. It is doing the validation without actually querying the DB. After the for loop has been executed I use a ConfirmationForm where the data that is about to be changed is displayed to the user and then s is set to True. However because I use a return statement, setting the variable to True is not working.
Any help would be appreciated.

Related

How to save from html select to sql in django

I want to save from HTML select to SQL but "Cannot assign "'27'": "UserProduct.category" must be a "Category" instance." I get an error. What am I doing wrong?
sell.html
<div class="form-group">
<p>Yerləşdirdiyiniz məhsul "İkinci əl məhsullar" kateqoriyasında görünəcək.</p>
<select class="input search-categories" name="up_category">
<option value="0">Kateqoriya seç</option>
{% for category in category %}
{% if category.active %}
{% if category.parent_id %}
<option value="{{category.id}}">{{category.name}}</option>
{% else %}
<option value="{{category.id}}" style="font-weight: bold;">{{category.name}}</option>
{% endif %}
{% endif %}
{% endfor %}
</select>
</div>
views.py
def sell(request):
category = Category.objects.all()
context = {'category': category}
if request.POST:
product_name = request.POST.get('product_name')
up_category = request.POST.get('up_category')
keywords = request.POST.get('keywords')
descriptions = request.POST.get('descriptions')
main_image = request.POST.get('main_image')
price = request.POST.get('price')
detail = request.POST.get('detail')
image1 = request.POST.get('image1')
image2 = request.POST.get('image2')
image3 = request.POST.get('image3')
if product_name == '' or up_category == 'Kateqoriya seç' or keywords == '' or descriptions == '' or price == '' or price == str or detail == '':
messages.warning(request, 'Bütün xanaları doldurduğunuzdan əmin olun!')
else:
newUserProduct = UserProduct(user=request.user,
name=product_name,
category=up_category,
keywords=keywords,
descriptions=descriptions,
detail=detail,
main_image=main_image,
image1 = image1,
image2 = image2,
image3 =image3
)
newUserProduct.save()
messages.warning(request, 'Məhsulunuz satışa çıxdı.')
return render(request, 'forms/sell.html', context)
return render(request, 'forms/sell.html', context)
models.py
class UserProduct(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=False)
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
main_image = models.ImageField(upload_to='static/product_images/%Y/%m/%d/')
detail = models.TextField()
keywords = models.CharField(max_length=50)
description = models.CharField(max_length=1000)
price = models.FloatField()
sale = models.IntegerField(blank=True, null=True, verbose_name="Sale (%)")
image1 = models.ImageField(upload_to='static/product_images/%Y/%m/%d/', blank=True, null=True)
image2 = models.ImageField(upload_to='static/product_images/%Y/%m/%d/', blank=True, null=True)
image3 = models.ImageField(upload_to='static/product_images/%Y/%m/%d/', blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
I want to save from HTML select to SQL but "Cannot assign "'27'": "UserProduct.category" must be a "Category" instance." I get an error. What am I doing wrong?
In your UserProduct class, the field category is a ForeignKey to the Category class. Try getting the Category first from your request.POST, then adding it:
def sell(request):
category = Category.objects.all()
context = {'category': category}
if request.POST:
product_name = request.POST.get('product_name')
up_category = request.POST.get('up_category')
keywords = request.POST.get('keywords')
descriptions = request.POST.get('descriptions')
main_image = request.POST.get('main_image')
price = request.POST.get('price')
detail = request.POST.get('detail')
image1 = request.POST.get('image1')
image2 = request.POST.get('image2')
image3 = request.POST.get('image3')
if product_name == '' or up_category == 'Kateqoriya seç' or keywords == '' or descriptions == '' or price == '' or price == str or detail == '':
messages.warning(request, 'Bütün xanaları doldurduğunuzdan əmin olun!')
else:
cat = Category.objects.get(pk=up_category) # CHANGED
newUserProduct = UserProduct(user=request.user,
name=product_name,
category=cat, # CHANGED
keywords=keywords,
descriptions=descriptions,
detail=detail,
main_image=main_image,
image1 = image1,
image2 = image2,
image3 =image3
)
newUserProduct.save()
messages.warning(request, 'Məhsulunuz satışa çıxdı.')
return render(request, 'forms/sell.html', context)
return render(request, 'forms/sell.html', context)

I filling the fields but do not enter in form.is_valid ():

Experts I am waiting for my problem to be solved on the internet
Why when I finished filling the fields in django do not enter in form.is_valid (): Although the results are presented correctly I hope to solve this problem
class Listing(models.Model):
property_type = models.IntegerField(choices=PROPERTY_TYPE_CHOICES, default=1)
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
price = models.BigIntegerField()
roomsTotal = models.PositiveSmallIntegerField(null=True)
Bathrooms = models.PositiveSmallIntegerField(default=0)
bedrooms = models.PositiveSmallIntegerField(default=0)
Receptionrooms = models.PositiveSmallIntegerField(default=0)
livingArea = models.DecimalField(max_digits=9, decimal_places=1)
lotSize = models.DecimalField(max_digits=9, decimal_places=1)
unitType = models.IntegerField(choices=UNIT_TYPE_CHOICES, default=1)
VOnSea = models.BooleanField(default=False, blank=True)
yearBuilt = models.PositiveIntegerField(
validators=[
MinValueValidator(1900),
MaxValueValidator(datetime.datetime.now().year)],
help_text="Use the following format: <YYYY>")
hoaPrice = models.BigIntegerField(null=True,blank=True)
groundTankSize = models.DecimalField(max_digits=6, decimal_places=1,null=True,blank=True)
garageSize = models.DecimalField(max_digits=6, decimal_places=1,null=True,blank=True)
homeDescription = models.TextField(blank=True)
class ForSaleForm(forms.Form):
property_type = forms.ChoiceField(widget=forms.Select, choices=PROPERTY_TYPE_CHOICES,required=False)
price = forms.IntegerField(required=True)
roomsTotal = forms.IntegerField()
Bathrooms = forms.IntegerField(required=True)
bedrooms = forms.IntegerField(required=True)
Receptionrooms = forms.IntegerField(required=True)
livingArea = forms.DecimalField(required=True)
lotSize = forms.DecimalField(required=True)
unitType = forms.ChoiceField(widget=forms.Select, choices=UNIT_TYPE_CHOICES,required=False)
yearBuilt = forms.DateField(required=True)
def clean(self):
data = self.cleaned_data
if data.get('price', None) or (data.get('Bathrooms', None) and data.get('bedrooms', None)):
return data
else:
raise forms.ValidationError('Provide either a price and Bathrooms or a bedrooms')
form = ForSaleForm(request.POST or None)
for key in request.POST.keys():
if key != 'csrfmiddlewaretoken':
print(key,":",request.POST[key])
if form.is_valid():
propertyType = form.cleaned_data.get('propertyType')
price = form.cleaned_data.get('price')
roomsTotal = form.cleaned_data.get('roomsTotal')
Bathrooms = form.cleaned_data.get('Bathrooms')
bedrooms = form.cleaned_data.get('bedrooms')
Receptionrooms = form.cleaned_data.get('Receptionrooms')
livingArea = form.cleaned_data.get('livingArea')
lotSize = form.cleaned_data.get('lotSize')
unitType = form.cleaned_data.get('unitType')
yearBuilt = form.cleaned_data.get('yearBuilt')
listing = Listing(
user=request.user,
price=price,
roomsTotal=roomsTotal,
Bathrooms=Bathrooms,
bedrooms=bedrooms,
Receptionrooms=Receptionrooms,
livingArea=livingArea,
lotSize=lotSize,
unitType=unitType,
yearBuilt=yearBuilt,
remodelYear=remodelYear
)
listing.save()
print("saved listing")
request.POST Output: propertyType : 1 price : 443 roomsTotal : 44 Bathrooms : 5454 bedrooms : 44 Receptionrooms : 55 livingArea : 45 lotSize : 4334 unitType : 2 yearBuilt : 11 hoaPrice : groundTankSize : garageSize : homeDescription : terms : on
When you press the send button, the form refresh without showing verification messages so that it is supposed to not respond to the wrong information
<div class="md-form mb-5">
<input type='text' placeholder='حدد السعر الخاص بك' id='price' name='price' class='form-control'/>
<label for="price" class="">السعر</label>
{{ form.price.errors }}
</div>
Thanking your cooperation
add {% csrf_token %} before form.
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>

Cannot assign "'2'": "TakenQuiz.question" must be a "Question" instance

I am trying to insert those value I got from radio buttons after the user as taken options. Then I want to insert it into another table which I will use to prepare the final result for the student. After I've taken all my values and created an insert query, I am getting this error.
models.py:
class Question(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='questions')
text = models.CharField('Question', max_length=500)
def __str__(self):
return self.text
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers')
text = models.CharField('Answer', max_length=255)
is_correct = models.BooleanField('Correct answer', default=False)
def __str__(self):
return self.text
class TakenQuiz(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='taken_quizzes')
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='taken_course')
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='taken_question')
selected_choice = models.ForeignKey(Answer, on_delete=models.CASCADE, null=True)
marks_obtained = models.DecimalField('Marks Obtained', default=0, decimal_places=2, max_digits=6)
is_correct = models.BooleanField('Was this attempt correct?', default=False, null=False)
date = models.DateTimeField(auto_now_add=True)
views.py:
#login_required
#student_required
def take_exam(request, pk):
course = get_object_or_404(Course, pk=pk)
student = request.user.student
question = course.questions.filter()
#correct_answers = student.course_answers.filter(answer__question__quiz=course, answer__is_correct=True).count()
total_questions = course.questions.count()
choice = Answer.objects.filter()
marks_obtainable = Details.objects.get(course_id=course)
if request.method == 'POST':
question_pk = request.POST.getlist('question_pk')
choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_pk]
zipped = zip(question_pk, choice_pk)
for x, y in zipped:
correct_answers = Answer.objects.filter(question_id=x, is_correct=True).values('id').first()['id']
#print(type(correct_answers))
#print(choice_pk)
print(x, y, correct_answers)
print(x, y, correct_answers)
if int(y) == correct_answers:
print("correct") #using this to comfirm the the conditional statement above
z = TakenQuiz.objects.create(student=student, question=int(x), course=course, mark_obtained=marks_obtainable, is_correct=True)
z.save()
takenquiz = TakenQuiz()
takenquiz.student = student
takenquiz.question = x
takenquiz.course = course
takenquiz.selected_choice = y
takenquiz.marks_obtained = marks_obtainable
takenquiz.is_correct = True
takenquiz.save()
else:
print("Not correct")
z = TakenQuiz.objects.create(student=student, question=x, course=course, mark_obtained=marks_obtainable, is_correct=False)
z.save()
return render(request, 'classroom/students/take_exam_form.html', {
'course': course,
'question': question,
'course': course,
'total_questions': total_questions,
'choice': choice,
'marks_obtainable': marks_obtainable,
})
take_exam_form.html:
<form method="post" novalidate>
{% csrf_token %}
{% for questions in question %}
<input type="hidden" name="question_pk" value="{{ questions.pk }}">
<h3 class="text-info">{{ questions.text|safe }}</h3>
{% for choices in questions.answers.all %}
<input class="form-check-input" type="radio" name="choice_pk{{ questions.pk }}" id="choices-{{ forloop.counter }}" value="{{ choices.pk }}">
<label class="form-check-label" for="choices-{{ forloop.counter }}">
{{ choices.text|safe }}
</label>
{% endfor %}
{% endfor %}
<button type="submit" class="btn btn-primary">Submit Now →</button>
</form>
question_pk = request.POST.getlist('question_pk')
question_obj = Question.objects.filter(id=int(question_pk)
while save
takenquiz.question = question_obj

Django dynamic forms validation

So I am new to Django and I have created a View which uses a total of 8 forms dynamically. There is one base form which is always displayed and then there are 7 more forms that are displayed only if user selects that option from a drop down (drop down is in the HTML template).
I am now trying to validate the form fields and when I display all 8 forms statically, the validation (clean methods) for each of the forms work perfectly! However when I change that to dynamically display the forms based on user selection, the validation for the base form fails every time.
Any idea why that could be happening? I could provide instances of the forms/view if that would help!
Template:
<form0 id="BaseForm" action="/test_created/" method="post">
{% csrf_token %}
{{create_test_form.as_ul}} <br><br>
</form0>
<form1 id="vc1Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc1_form.as_ul}} <br><br>
</form1>
<form2 id="vc2Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc2_form.as_ul}} <br><br>
</form2>
<form3 id="vc3Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc3_form.as_ul}} <br><br>
</form3>
<form4 id="vc4Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc4_form.as_ul}} <br><br>
</form4>
<form5 id="vc5Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc5_form.as_ul}} <br><br>
</form5>
<form6 id="vc6Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc6_form.as_ul}} <br><br>
</form6>
<form7 id="vc7Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc7_form.as_ul}} <br><br>
</form7>
<div>
<select id="validation_classes_id" name="all_validation_classes" onchange="showForm()">
<option value="%">Choose the validation class</option>
{% for val_class in all_validation_classes %}
<option value="{{ val_class.id }}">{{ val_class.id}} {{val_class.name }}</option>
{% endfor %}
</select> <br> <br>
<form id="submit" action="" method="post">
{% csrf_token %}
<input type="submit" value="Submit" onclick=""/>
</form>
</div>
<br><br>
<script>
function showForm(){
if (validation_classes_id.value == 1){
console.log("Chose validation class 1");
var div = document.getElementById('vc1Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 2){
console.log("Chose validation class 2");
var div = document.getElementById('vc2Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 3){
console.log("Chose validation class 3");
var div = document.getElementById('vc3Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 4){
console.log("Chose validation class 4");
var div = document.getElementById('vc4Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 5){
console.log("Chose validation class 5");
var div = document.getElementById('vc5Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 6){
console.log("Chose validation class 6");
var div = document.getElementById('vc6Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 7){
console.log("Chose validation class 7");
var div = document.getElementById('vc7Form');
console.log(div)
div.style.display='block';
}
}
</script>
View:
def create_test(request):
context = {
'all_validation_classes': ValidationClass.objects.all(),
'create_test_form': CreateTestForm,
'vc1_form': VC1Form,
'vc2_form': VC2Form,
'vc3_form': VC3Form,
'vc4_form': VC4Form,
'vc5_form': VC5Form,
'vc6_form': VC6Form,
'vc7_form': VC7Form
}
if request.method == 'POST':
create_test_form = CreateTestForm(request.POST)
vc1_form = VC1Form(request.POST)
vc2_form = VC2Form(request.POST)
vc3_form = VC3Form(request.POST)
vc4_form = VC4Form(request.POST)
vc5_form = VC5Form(request.POST)
vc6_form = VC6Form(request.POST)
vc7_form = VC7Form(request.POST)
if create_test_form.is_valid():
print("This is where I am")
print("Create Test form looks valid")
vc_list = request.POST.getlist('validation_class', None)
selected_vc = ValidationClass.objects.filter(pk__in=vc_list)
global_val_class = selected_vc
if vc1_form.is_valid():
print("VC1Form is valid")
else:
print("Failing at VC1")
return HttpResponseRedirect('/test_not_created/')
if vc2_form.is_valid():
print("VC2Form is valid")
else:
print("Failing at VC2")
return HttpResponseRedirect('/test_not_created/')
if vc3_form.is_valid():
print("VC3Form is valid")
else:
print("Failing at VC3")
return HttpResponseRedirect('/test_not_created/')
if vc4_form.is_valid():
print("VC4Form is valid")
else:
print("Failing at VC4")
return HttpResponseRedirect('/test_not_created/')
if vc5_form.is_valid():
print("VC5Form is valid")
else:
print("Failing at VC5")
return HttpResponseRedirect('/test_not_created/')
if vc6_form.is_valid():
print("VC6Form is valid")
else:
print("Failing at VC6")
return HttpResponseRedirect('/test_not_created/')
if vc7_form.is_valid():
print("VC7Form is valid")
else:
print("Failing at VC7")
return HttpResponseRedirect('/test_not_created/')
return HttpResponseRedirect('/test_created/')
else:
print("Failing at create_test")
return HttpResponseRedirect('/test_not_created/')
else:
create_test_form = CreateTestForm()
vc1_form = VC1Form()
vc2_form = VC2Form()
vc3_form = VC3Form()
vc4_form = VC4Form()
vc5_form = VC5Form()
vc6_form = VC6Form()
vc7_form = VC7Form()
return render (request, 'create_test.html', context)
Forms:
class CreateTestForm(forms.ModelForm):
class Meta:
model = Test
fields = ['name', 'test_group', 'description', 'query_text', 'failure_condition', 'status']
def clean_status(self):
print("This is where I am")
print(self.cleaned_data)
def getKey(self):
return "create_test_form"
class VC1Form(forms.Form):
expected_relation = forms.ChoiceField(choices = [('<','<'), ('>','>'), ('=','='), ('<=','<='), ('>=','>='), ('!=','!=')], required = True, label = 'Expected Relation: ')
num_rows = forms.IntegerField(initial = 0)
def getKey(self):
return "vc1_form"
class VC2Form(forms.Form):
expected_relation = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation: ')
comparing_value_type = forms.ChoiceField(choices=[('Integer', 'Integer'), ('String', 'String')], required=True, label='Comparing Value Type')
comparing_value = forms.CharField(initial = 0)
def clean_comparing_value(self):
exp_rel = self.cleaned_data['expected_relation']
input_val_type = self.cleaned_data['comparing_value_type']
input_val = self.cleaned_data['comparing_value']
if (input_val_type == 'Integer'):
print("I am in integer")
try:
int(input_val)
print(int(input_val))
return input_val
except ValueError:
print("Getting a value error")
raise forms.ValidationError('Should be an Integer')
elif (input_val_type == 'String'):
print("I am in string")
if (exp_rel != '!=' and exp_rel != '='):
print("I am in here...")
raise forms.ValidationError('Must have either = or != as comparator for String')
try:
int(input_val)
print(int(input_val))
print("getting a value error")
raise forms.ValidationError('Should be a string')
except ValueError:
print("No value error")
return input_val
def getKey(self):
return "vc2_form"
class VC3Form(forms.Form):
comparing_value_2 = forms.CharField(label = 'Comparing Value', initial=" ") #Need to figure out if its needed to make this into an array?
# Not sure for now if there is a need to validate this data
def getKey(self):
return "vc3_form"
class VC4Form(forms.Form):
# # This is mostly not needed as we will only check the values in the first column of the query results (as per documentation)
wanted_value = forms.CharField(label = 'Name of corresponding column', initial=" ") #Need to figure out how the input will be an actual variable from the select query
acceptable_error_rate = forms.IntegerField(min_value = 0, max_value = 100, initial=0)
def getKey(self):
return "vc4_form"
class VC5Form(forms.Form):
expected_relation_2 = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True,label='Expected Relation: ')
comparing_value_type_2 = forms.ChoiceField(choices=[('Integer', 'Integer'), ('String', 'String')], required=True, label='Comparing Value Type')
def clean_comparing_value_type_2(self):
expected_relation_choices = ('<', '>', '=', '<=', '>=', '!=')
exp_rel = self.cleaned_data['expected_relation_2']
input_val_type = self.cleaned_data['comparing_value_type_2']
print("This is the input val type")
print(input_val_type)
if (input_val_type == 'String'):
print("I get in here")
if (exp_rel != '=' and exp_rel != '!='):
raise forms.ValidationError('Must have either = or != as comparator for String')
return exp_rel
def getKey(self):
return "vc5_form"
class VC6Form(forms.Form):
expected_relation_3 = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation: ')
def getKey(self):
return "vc6_form"
class VC7Form(forms.Form):
expected_relation_one = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation to First Value: ')
comparing_value_one = forms.IntegerField(label = 'First comparing value', initial=0)
expected_relation_two = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation to Second Value: ')
comparing_value_two = forms.IntegerField(label = 'Second comparing value', initial=0)
def getKey(self):
return "vc7_form"

This field is required error on Django using formset

I have three forms, forms.py:
class HotelForm(forms.Form):
rooms = forms.IntegerField(label=(u'Rooms'), min_value=1)
class TouristsForm(forms.Form):
adult = forms.IntegerField(label=(u'Adults'), min_value=1, initial=1)
children = forms.IntegerField(label=(u'Children'), min_value=0, initial=0, required=False)
class ChildrenAgeForm(forms.Form):
children_age = forms.IntegerField(label=(u'Children Age'), min_value=2, max_value=10, initial=2, required=False)
That's how i realize formset and validation in views.py:
def bookingForm(request):
TouristsFormSet = formset_factory(TouristsForm, extra = 1, max_num = 15)
ChildrenAgeFormSet = formset_factory(ChildrenAgeForm, extra = 1, max_num = 20)
if request.method == 'POST':
booking_form = HotelForm(request.POST, prefix='booking_form')
tourists_formset = TouristsFormSet(request.POST, prefix='tourists')
childrenage_formset = ChildrenAgeFormSet(request.POST, prefix='childrenage')
if booking_form.is_valid() and tourists_formset.is_valid() and childrenage_formset.is_valid():
rooms = booking_form.cleaned_data['rooms']
for i in range(0, tourists_formset.total_form_count()):
tourists_form = tourists_formset.forms[i]
tourists = tourists_form.cleaned_data
for n in range(0, childrenage_formset.total_form_count()):
childrenage_form = childrenage_formset.forms[n]
childrenage = childrenage_form.cleaned_data
template = get_template("booking/result.html")
context = Context({'tourists_formset':tourists_formset, 'childrenage_formset':childrenage_formset })
html = template.render(context)
return HttpResponse( html )
else:
booking_form = HotelForm()
tourists_formset = TouristsFormSet(prefix='tourists')
childrenage_formset = ChildrenAgeFormSet(prefix='childrenage')
return render(request, 'booking/booking.html', { 'booking_form' : booking_form, 'tourists_formset' : tourists_formset, 'childrenage_formset' : childrenage_formset })
And this is how i realize html file:
{{ tourists_formset.management_form }}
{% for tourists in tourists_formset %}
{{ tourists }}
{% endfor %}
{{ childrenage_formset.management_form }}
{% for childrenage in childrenage_formset %}
{{ childrenage }}
{% endfor %}
Every time when i fill all fields in the form i have an error 'This field is required' for the HotelForm form. I can't understand why it is happen. Thanks for help
You are using a prefix when handling the POST request.
booking_form = HotelForm(request.POST, prefix='booking_form')
You need to use the same prefix for the GET request.
booking_form = HotelForm(prefix='booking_form')