This field is required error on Django using formset - django

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')

Related

How to display your queries using filter?

So I am trying to set up a filter for my website and it is not working; It does not give me an error and the url updates like a query is being made but when I click "submit" it still shows all of the content in the page. I can't quite figure out what is wrong.
filters.py
import django_filters
from django_filters import DateFilter
from .models import *
class UserpostFilter(django_filters.FilterSet):
start_date = DateFilter(field_name = "date_published", lookup_expr='gte')
end_date = DateFilter(field_name = "date_published", lookup_expr='lte')
class Meta:
model = Userpost
fields = '__all__'
exclude = ['image', 'user', 'date_published']
models.py
class Userpost(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
Year = models.CharField(max_length = 4)
Mileage = models.CharField(max_length = 8)
Make = models.CharField(max_length = 50)
Model = models.CharField(max_length = 50)
Price = models.DecimalField(max_digits=15, decimal_places=2)
email = models.EmailField()
date_published = models.DateField(default = timezone.now)
image = models.ImageField(null = True, blank = True, upload_to = r"C:\Users\gabri\Desktop\test\ecommerce\static\images")
def __str__(self):
return self.Year + " " + self.Make + " " + self.Model
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
views.py
def posts(request):
cars = Userpost.objects.all()
p = Paginator(Userpost.objects.all(), 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
myFilter = UserpostFilter(request.GET, queryset = cars)
cars = myFilter.qs
context = {'cars':cars, 'cars_list':cars_list, "nums":nums, "myFilter":myFilter}
return render(request, 'store/userposts.html', context)
userposts.html
<div class = "row">
<div class="col">
<div class = "card card-body">
<form method="get">
{{myFilter.form}}
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
{% for car in cars_list %}
<div class="col-lg-4">
<img class="thumbnail" src="{{car.imageURL|default:'/images/transparentLogo.png'}}">
<div class="box-element product">
<h6><strong>{{car.Year}} {{car.Make}} {{car.Model}}</strong></h6>
<hr>
<a class="btn btn-outline-success" href="{% url 'post_detail' car.pk %}">View</a>
<h4 style="display: inline-block; float: right"><strong>${{car.Price|floatformat:2}}</strong></h4>
</div>
</div>
{% endfor %}
</div>
I would really appreciate if you guys could help me
EDIT
So I changed the order of the views to first filter and then paginate but it still does the same thing. I get no error, but display all the content from the page rather than the filtered ones.
def posts(request):
cars = Userpost.objects.all()
myFilter = UserpostFilter(request.GET, queryset=cars)
cars = myFilter.qs
p = Paginator(Userpost.objects.all(), 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
context = {'cars':cars, "myFilter":myFilter, 'cars_list':cars_list, "nums":nums}
return render(request, 'store/userposts.html', context)
The paginator should work on the cars not on the orignal queryset, since you are paginate over the filtered results
def posts(request):
cars = Userpost.objects.all()
myFilter = UserpostFilter(request.GET, queryset=cars)
if not myFilter.is_valid():
raise ValidationError('filter is invalid')
cars = myFilter.qs
# This is the change
p = Paginator(cars, 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
context = {'cars':cars, "myFilter":myFilter, 'cars_list':cars_list, "nums":nums}
return render(request, 'store/userposts.html', context)

Changing values ​in two models using one form - did not work. Django

I am trying to make changes in two models at the same time. So, according to one topic on the forum, I created two forms in one view and added it to one html.
I think I am doing something wrong in my second form. Why my value in my model does not change to False?
It looks more or less like that.
views.pl
if request.method == 'POST' and 'btn_massage_order' in request.POST:
ordering_form = OrderingMassageForm(data=request.POST)
if ordering_form.is_valid():
ordering = ordering_form.save(commit=False)
massage_product = query_product # nazwa produkty
masseurs = query_user # massage
massage_time_interval = time # time example 60 min
price_massage = price # price
day_week = clean_my_date # day week
time_compartment = ordering_form.cleaned_data['time']
[...]
ordering.massage_product = massage_product
ordering.masseurs = masseurs
ordering.massage_time_interval = massage_time_interval
ordering.time_compartment = time_compartment
ordering.price = price_massage
ordering.day_week = day_week
[...]
ordering.save()
else:
ordering_form = OrderingMassageForm()
#next form i views
if request.method == 'POST' and 'btn_massage_order' in request.POST:
ordering_form = OrderingMassageForm(data=request.POST)
ordering_form_on_off = TimeOnTimeOff(data=request.POST)
if ordering_form_on_off.is_valid() and ordering_form.is_valid():
ordering_form_on_off = ordering_form_on_off.save(commit=False)
# the value that will be save
reservation = False
# I receive my object
time_compartment = ordering_form.cleaned_data['time']
# assigning my object
ordering_form_on_off.time_compartment = reservation
#save
ordering_form_on_off.save()
else:
ordering_form_on_off = TimeOnTimeOff()
forms.py
class OrderingMassageForm(forms.ModelForm):
class Meta:
model = OrderingMassage
fields = ('time',
'place',
'payment_method',
'name',
'surname',
[...]
class TimeOnTimeOff(forms.ModelForm):
class Meta:
model = Time
fields = ('free_or_no',
)
widgets = {
'free_or_no': forms.HiddenInput(),
}
models.py
(in which I try to change the value through a second form that does not work)
class Time(models.Model):
day_time = models.ForeignKey(DayTime, on_delete=models.CASCADE)
compartment = models.CharField(max_length=11)
free_or_no = models.BooleanField(default=True)
time_equivalent = models.IntegerField()
template
<form action="." method="post">
{% csrf_token %}
{{ ordering_form.as_p }}
<button type="submit" name="btn_massage_order" class="btn btn-primary">Potwierdż rezerwacje</button>
</form>
Any help will be appreciated.

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"

django - mysql selecting data from db does not work well

In main.html:
{% for item in count_list %}
{{ item }}<br>
{% endfor %}
In views.py:
def four(request):
count_list = PDivContent.objects.filter(divv = '5')
return render(request, 'main.html', {'count_list': count_list})
The problem is that the count_list list, contains data repeated for twice like this:
طلا و جواهرات
بدلیجات و نقره سرا
اجناس کادویی
اسباب بازی فروشی
صنایع دستی
فروش و تعمیر ساعت
طلا و جواهرات
بدلیجات و نقره سرا
صنایع دستی
اجناس کادویی
اسباب بازی فروشی
How can I solve it?
models.py:
class PDivContent(models.Model):
chest = models.IntegerField()
divv = models.IntegerField()
txt = models.TextField()
img = models.TextField()
symbol = models.TextField()
def __str__(self):
return self.txt
class Meta:
managed = False
db_table = 'p_div_content'
And in the db, data are not repeated for twice.
How about trying .distinct() in your query?
def four(request):
count_list = PDivContent.objects.filter(divv = '5').distinct()
return render(request, 'main.html', {'count_list': count_list})

Django form with no errors return False for is_valid()

I'm generating a form from metadata
class MeasureForm(forms.Form):
def __init__(self,*args,**kwargs):
super(MeasureForm,self).__init__()
measure_id = kwargs['measure_id']
m = Measure.objects.get(pk=measure_id);
if (m):
# add the measure identifier as a hidden field
self.fields["measure_id"] = forms.IntegerField(initial = m.id , widget=forms.HiddenInput())
for mp in MeasureParameters.objects.filter(measure = m):
# get the NVL'ed copy of the parameter
p = mp.get_parameter_for_measure()
if not p.is_modifiable:
# the file has a constant value
if (p.values and p.default): # constant must have both values and default index
value_ = p.values[p.values.keys()[p.default-1]];
self.fields[p.name] = forms.IntegerField(
label = p.description ,
initial = value_,
help_text = p.help_text)
self.fields[p.name].widget.attrs['readonly'] = True
else:
raise Exception("Parameter set as unmodifiable but has no value. \
[measure: %s, parameter: %s, measureparameter %s]"
% (m.id , p.id , mp.__unicode__()))
elif (p.values):
# convert hstore dict to list of tuples for the choices to read
values_ = [(v, k) for k, v in p.values.iteritems()];
# set default if exists , else take the first item
default_ = values_[p.default-1][0] if p.default else values_[0][0]
self.fields[p.name] = forms.ChoiceField(
label = p.description ,
choices = values_ ,
initial = default_,
help_text = p.help_text)
else:
self.fields[p.name] = forms.IntegerField(label = p.description, help_text = p.help_text)
if (not p.is_visible):
self.fields[p.name].widget = forms.HiddenInput()
else:
raise Exception ("Could not find measure. [measure %s]" % (m.id))
def clean(self):
return self.cleaned_data;
this is my view
def index(request,measure_id = None):
owners = Owner.objects.all()
form = None
result = None
title = None;
msg = None;
# handle the form
if request.method == 'POST': # the form has been submitted
form = MeasureForm(request.POST, measure_id = request.POST.get('measure_id')) # A form bound to the POST data
result = -100
if form.is_valid(): # All validation rules pass
result = 100
msg = "%s" % repr(form.errors) # list of validation errors
else:
if (measure_id):
title = Measure.objects.get(pk=measure_id).name;
# make an unbound form
form = MeasureForm(measure_id = measure_id)
return render(request, 'calc/index.html' ,
{'owners' : owners,
'form' : form ,
'title' : title ,
'result' : result,
'debug' : msg })
this is a snippet from my template
<div class="content">
{{ form.errors }}
{{ form.non_field_errors }}
{% if form %}
<h2>{{ title }}</h2>
<form action="/calc/{{m.id}}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Calculate" />
</form>
{% if result %}
The Result is <span class="result"> {{ result }} </span>
{% endif %}
</div>
So i get empty braces {} for "%s" % repr(form.errors), form.errors and form.non_field_errors returns nothing. the form posts and I can see the raw data in the request but i keep getting false from is_valid(). why is that ?
EDIT: when checking if the form is bound i also get false. guessing this is the problem. why isn't the form bound after the call for form = MeasureForm(request.POST, measure_id = request.POST.get('measure_id')) ?
** django newbie, Thanks.
Because you're not passing the arguments into the super call. You should do this:
super(MeasureForm,self).__init__(*args, **kwargs)
otherwise the form will never actually be initialised with the POST data.
Edit after comment The answer to that question didn't recommend removing all the arguments from the super call. If you're passing in measure_id you'll simply need to remove it from kwargs beforehand:
def __init__(self, *args, **kwargs):
measure_id = kwargs.pop('measure_id', None)
super(MeasureForm,self).__init__(*args, **kwargs)