У меня есть вид, который позволяет пользователю ввести Ввести категорию и подкатегорию. Форма перенесет пользователя в другую, у меня есть три формы, и форма будет загружена из выбранного значения в категории. Теперь у меня есть три формы на моей странице, но одна может только загрузить. Проблема сейчас в том, что форма не показывает допустимую ошибку после публикации. Более того, при печати is.valid () я получаю False, но я получаю сообщение об ошибке при печати ошибки.
models.py
@login_required
def AdCategory(request):
template_name = 'adcategory.html'
#form = AdCategoryForm()
form = ProcessItemForm()
if request.method == 'POST':
form = ProcessItemForm(request.POST)
if form.is_valid():
request.session['category'] = request.POST['category']
request.session['subcategory'] = request.POST['subcategory']
return redirect(addItem)
return render(request, template_name, {'form': form})
@login_required
def addItem(request):
template_name = 'additem.html'
form1 = ForSaleForm()
form2 = VehiclesForm()
form3 = JobsForm()
category = request.session.get('category')
subcategory = request.session.get('subcategory')
context = {'form1': form1, 'form2': form2, 'form3': form3, 'category': category, 'subcategory': subcategory}
if request.method == 'POST' and category == '1':
#if 'job' in request.POST and category == '1' and form3.is_valid():
form3 = JobsForm(request.POST or None, request.FILES)
print(form3.is_valid())
print(form3.errors)
if form3.is_valid():
if CustomUser.objects.filter(email=request.user).filter(first_name=''):
messages.warning(request, 'Update Your Profile Before Submitting Ad!')
return redirect('profile')
else:
if Profile.objects.filter(user=request.user).filter(approval=True).exists():
p = form3.save(commit=False)
p.user = request.user
p.save()
messages.success(request, 'The Item Has been Added Successully!')
return redirect('dashboard')
elif not Profile.objects.filter(user=request.user).exists():
messages.error(request, 'Upload Your Account Profile Now!')
return redirect('personalprofile')
elif Profile.objects.filter(user=request.user).filter(approval=False):
messages.error(request, 'Your Account Profile is yet to be approve!')
return redirect('dashboard')
else:
messages.warning(request, 'Update Your User Profile Before Submitting Ad!')
return redirect('personalprofile')
else:
form3 = JobsForm()
if request.method == 'POST' and category == '2':
form2 = VehiclesForm(request.POST or None, request.FILES)
if form2.is_valid():
if CustomUser.objects.filter(email=request.user).filter(first_name=''):
messages.warning(request, 'Update Your Profile Before Submitting Ad!')
return redirect('profile')
else:
if Profile.objects.filter(user=request.user).filter(approval=True).exists():
p = form2.save(commit=False)
p.user = request.user
p.save()
messages.success(request, 'The Item Has been Added Successully!')
return redirect('dashboard')
elif not Profile.objects.filter(user=request.user).exists():
messages.error(request, 'Upload Your Account Profile Now!')
return redirect('personalprofile')
elif Profile.objects.filter(user=request.user).filter(approval=False):
messages.error(request, 'Your Account Profile is yet to be approve!')
return redirect('dashboard')
else:
messages.warning(request, 'Update Your User Profile Before Submitting Ad!')
return redirect('personalprofile')
else:
form2 = VehiclesForm()
if request.method == 'POST' and category == '3':
form1 = ForSaleForm(request.POST or None, request.FILES)
if form1.is_valid():
if CustomUser.objects.filter(email=request.user).filter(first_name=''):
messages.warning(request, 'Update Your Profile Before Submitting Ad!')
return redirect('profile')
else:
if Profile.objects.filter(user=request.user).filter(approval=True).exists():
p = form1.save(commit=False)
p.user = request.user
p.save()
messages.success(request, 'The Item Has been Added Successully!')
return redirect('dashboard')
elif not Profile.objects.filter(user=request.user).exists():
messages.error(request, 'Upload Your Account Profile Now!')
return redirect('personalprofile')
elif Profile.objects.filter(user=request.user).filter(approval=False):
messages.error(request, 'Your Account Profile is yet to be approve!')
return redirect('dashboard')
else:
messages.warning(request, 'Update Your User Profile Before Submitting Ad!')
return redirect('personalprofile')
else:
form1 = ForSaleForm()
return render(request, template_name, context)
forms.py
class ForSaleForm(forms.ModelForm):
STATUS = (
('Used', "Used"),
('New', "New"),
('Fairly Used', 'Fairly Used')
)
ITEM_TYPE = (
('Demand', "Demand"),
('Offer', "Offer"),
)
status = forms.ChoiceField(label='Item Status:', choices=STATUS, initial="1", widget=forms.RadioSelect, required=True)
item_type = forms.ChoiceField(label='Item Type:', choices=ITEM_TYPE, initial="1", widget=forms.RadioSelect, required=True)
class Meta:
model = Item
exclude = ('updated_at', 'created_at', 'user', 'approval', 'featured', 'compensation', 'expire_date', 'year', 'make', 'model', 'sale_type', 'role', 'qualification', 'sold',)
def year_choices():
return [(r,r) for r in range(1984, datetime.date.today().year+1)]
class VehiclesForm(forms.ModelForm):
STATUS = (
('Used', "Used"),
('New', "New"),
('Fairly Used', 'Fairly Used')
)
ITEM_TYPE = (
('Demand', "Demand"),
('Offer', "Offer"),
)
status = forms.ChoiceField(label='Item Status:', choices=STATUS, initial="1", widget=forms.RadioSelect, required=True)
item_type = forms.ChoiceField(label='Item Type:', choices=ITEM_TYPE, initial="1", widget=forms.RadioSelect, required=True)
year = forms.TypedChoiceField(coerce=int, choices=year_choices, initial=current_year)
class Meta:
model = Item
exclude = ('updated_at', 'created_at', 'user', 'approval', 'featured', 'quantity', 'sold', 'qualification', 'role', 'compensation', 'expire_date',)
class JobsForm(forms.ModelForm):
class Meta:
model = Item
exclude = ('updated_at', 'created_at', 'user', 'approval', 'price', 'quantity', 'status', 'item_type', 'featured', 'year', 'make', 'model', 'sale_type', 'sold',)
additem. html
{% csrf_token %}
{% include 'message.html' %}
<input name="category" type="text" value="{{ category }}" />
<input name="subcategory" type="text" value="{{ subcategory }}" />
{% if category == '1' %}
<h1> Job Form </h1>
{{ form3.as_p }}
{% elif category == '2' %}
<h1> Vechicle Form </h1>
{{ form2.as_p }}
{% elif category == '3' %}
<h1> Item Form </h1>
{{ form1.as_p }}
{% endif %}
<button type="submit" name="job" class="btn btn-primary width-100">Search</button>
</form>