第一个表单的验证和发布存在问题。第二种形式form2可以正常工作。视图代码是与导致问题的原因相同的结构。
.is_valid()默认情况下应验证字段。我想念什么?
# views.py
def create(request):
if request.method == 'POST':
form = CreateForm(request.POST)
form2 = CreateTimeForm(request.POST)
if form.is_valid():
form.save()
return redirect('organizer-create')
if form2.is_valid():
form2.save()
return redirect('organizer-create')
else:
form = CreateForm()
form2 = CreateTimeForm()
context = {
'form': form,
'form2': form2,
}
return render(request, 'organizer/create.html', context)
# forms.py
class CreateForm(ModelForm):
class Meta:
model = Event
fields = ['title', 'date',]
# models.py
class Event(models.Model):
title = models.CharField(max_length=50)
date = models.DateField()
datetimecreated = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self):
return reverse('organizer-admin')
def __str__(self):
return str(self.date) + ", " + self.title
编辑2: 下面是我的模板。数据库问题会导致数据无法发布吗?我要怎么解决这个问题?
# create.html template
{% block content %}
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Event Creation</legend>
{{ form.as_p }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Create</button>
</div>
</form>
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Add New Time Block</legend>
{{ form2.as_p }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Create</button>
</div>
</form>
{% endblock content %}
答案 0 :(得分:1)
如下更改您的views.py文件:
def create(request):
if request.method == 'POST':
form = CreateForm(request.POST)
form2 = CreateTimeForm(request.POST)
if form.is_valid() and form2.is_valid:
form.save()
form2.save()
return redirect('organizer-create')
else:
form = CreateForm()
form2 = CreateTimeForm()
context = {
'form': form,
'form2': form2,
}
return render(request, 'organizer/create.html', context)
现在的问题是,当编译器编译第一个if语句时:
if form.is_valid():
form.save()
return redirect('organizer-create')
会看起来并认为哦,这是正确的,并执行if语句。然后它将成功重定向“组织者创建”。那就是:
return redirect('organizer-create')
但是不要移动下一个if语句。