我的Django表单有问题。当我单击表单中的提交按钮时,没有数据保存到数据库中。我发现数据已绑定,但没有通过form.is_valid()
函数传递。以下分别是forms.py
,views.py
,urls.py
和new-event.html
的代码:
forms.py
from django import forms
class EventForm(forms.Form):
name = forms.CharField(label='event-name',
max_length=50,
widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'event-name', 'name': 'event-name'}))
start_datetime = forms.DateTimeField(
widget=forms.DateTimeInput(attrs={'class': 'form-control', 'id': 'start-datetime', 'name': 'start-datetime', 'type': 'datetime-local'}))
end_datetime = forms.DateTimeField(
widget=forms.DateTimeInput(attrs={'class': 'form-control', 'id': 'end-datetime', 'name': 'end-datetime', 'type': 'datetime-local'}))
event_category = forms.ChoiceField(widget=forms.Select(attrs={'class': 'custom-select', 'id': 'event-type'}),
choices=((None, 'Please select an option'), ('Daily Life', 'Daily Life'), ('Study', 'Study'), ('Social', 'Social'), ('Work', 'Work')))
description = forms.CharField(max_length=250, widget=forms.Textarea(attrs={'class': 'form-control', 'id': 'description', 'name': 'description'}), required=False)
views.py
from django.shortcuts import render, redirect
from .models import Entry
from .forms import EventForm
from django.views.decorators.http import require_POST
# request is required that represents HttpResponse
# return value can be response, JSON or template
def index(request):
entries = Entry.objects.order_by('-date_added')
context = {'entries': entries}
return render(request, 'event/list-events.html', context)
def new_event(request):
form = EventForm()
context = {'form': form}
return render(request, 'event/new-event.html', context)
@require_POST
def add_event(request):
if request.method == 'POST':
form = EventForm(request.POST)
if form.is_bound: print('form is bound')
else: print('form is unbound')
if form.is_valid():
print('form is valid')
new_entry = Entry(name=form.cleaned_data['name'], start_datetime=form.cleaned_data['start_datetime'],
end_datetime=form.cleaned_data['end_datetime'], category=form.cleaned_data['event_category'],
description=form.cleaned_data['description'])
new_entry.save()
else:
print('form is invalid')
return render(request, 'event/new-event.html', {'form': form})
return redirect('index')
# else:
# form = EventForm()
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('new-event/', views.new_event, name='new_event'),
path('add-event/', views.add_event, name='add_event')
]
new-event.html
{% extends 'todo/base.html' %}
{% block title %}New Entry{% endblock %}
{% block content %}
<form action="{% url 'add_event' %}" method="POST" class="container-fluid">
{% csrf_token %}
<div class="form-group row">
<label for="event-name" class="col-sm-2 col-form-label">Event</label>
<div class="col-sm-10">
{{ form.name }}
</div>
</div>
<div class="form-group row">
<label for="event-type" class="col-sm-2 col-form-label">Event type</label>
<div class="col-sm-10">
{{ form.event_category }}
</div>
</div>
<div class="form-group row">
<label for="start-datetime" class="col-sm-2 col-form-label">Start Time</label>
<div class="col-sm-10">
{{ form.start_datetime }}
</div>
</div>
<div class="form-group row">
<label for="end-datetime" class="col-sm-2 col-form-label">End Time</label>
<div class="col-sm-10">
{{ form.end_datetime }}
</div>
</div>
<div class="form-group">
{{ form.description }}
</div>
<input type="submit" name="submit" value="Submit" class="btn btn-primary">
</form>
{% endblock %}
终端上的输出为:form is bound form is invalid
...我确信我不会陷入 bound 和 instance 之间的概念混淆。谁能给我一些有关这种情况的提示?
答案 0 :(得分:1)
我不确定您为什么认为这是一个问题。您的表单已正确绑定到POST数据;然后,该数据经过验证,发现未通过验证。
要了解原因-并允许用户纠正问题-您应该在模板上输出{% set company_tag = 'company' %}
,或为每个字段使用单独的错误属性,例如{{ form.errors }}
等。