Reputation: 90
I am trying to get data from a form and redirect if the form is valid. I am, however, seemingly not grabbing any data. In a test, I fill out each form with "test". I would expect these forms to be valid and redirect to a success page, and am unable to figure out where I am going wrong with my logic.
Error:
form.errors = <ul class="errorlist"><li>category<ul class="errorlist"><li>This field is required.</li></ul></li><li>comment<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
forms.py
from django import forms
class CandidateReportForm(forms.Form):
category = forms.CharField(label='Category', max_length=10)
comment = forms.CharField(label='Comment', max_length=1000)
views.py
from django.shortcuts import render
from django.views import View
from .forms import CandidateReportForm
class CandidateReportView(View):
form_class = CandidateReportForm
form_template = 'Reports/candidate_report.html'
form_submit_template = 'Reports/report_submitted.html'
form_submit_error = 'Reports/report_error.html'
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.form_template, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
return render(request, self.form_submit_template)
else:
print(f"form.errors = {form.errors}")
return render(request, self.form_submit_error)
html
<div class="container">
<div class="card">
<h2 class="card-title">Report</h2>
{{ form.as_p }}
<form action="submit_candidate_report" method="post">{% csrf_token %}
<input class="btn btn-primary" id="report" name="report" type="submit" value="Submit">
</form>
</div>
</div>
Upvotes: 0
Views: 90
Reputation: 21821
You are rendering your form outside the form
tag! Only fields inside the form
tag are submitted to the server, so your html for the form
tag should be:
<form action="submit_candidate_report" method="post">
{% csrf_token %}
{{ form.as_p }}
<input class="btn btn-primary" id="report" name="report" type="submit" value="Submit">
</form>
Upvotes: 1