Прямая форма modelform не проходит валидацию при отправке формы
У меня есть довольно простая ModelForm, которая не проходит валидацию при отправке. Не знаю, как это отладить. Я пробовал различные операторы печати в моем представлении, и все вроде бы правильно.
Вот что у меня есть:
# views.py
def render_entities(request):
"""View to render the entities overview page"""
# Get the logged in user instance
user = User.objects.get(username=request.user.username)
user_cashpool = Cashpool.objects.get(company__user=user)
# Get the info for the site visited
dashboard_site = 'entities'
if request.method == 'GET':
# Return the form and populate with user's company
company = user.company
# Query all entities associated to the cashpool
companies = Company.objects.filter(cashpool=user_cashpool).order_by('name')
# Pass the queryset to the Select Form
CompanyForm.base_fields['company'] = forms.ModelChoiceField(
queryset=companies)
# Return the form
form = CompanyForm()
context = {
'company': company,
'companies': companies,
'dashboard_site': dashboard_site,
'form': form
}
return render(request, 'dashboard/dashboard_entities.html', context)
else:
form = CompanyForm(request.POST)
if form.is_valid(): # fails
# Get the cleaned inputs
company = form.cleaned_data['company']
...
# forms.py
class CompanyForm(forms.ModelForm):
"""
A form to render a select widget with companies associated to a user
"""
company = forms.ModelChoiceField(queryset=Company.objects.exclude(name='exclude-all'), required=True)
class Meta:
model = Company
fields = ['name']
# template
<!-- Select Company -->
<form action="entities" method="post">
{% csrf_token %}
<label for="company">Select a Company</label>
{{ form.company }}
<button type="submit" value="Load Company" class="submit-button">Load Company</button>
</form>
Ошибка
<ul class="errorlist"><li>name<ul class="errorlist"><li>This field is required.</li></ul></li></ul>