“提交”按钮不起作用。 无法保存在数据库中
{% block content %}
<form class="" action="{% url 'post_create_url' %}" method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
{% if field.errors %}
<div class="alert alert-danger">
{{ field.errors }}
</div>
{% endif %}
{{ field.label }}
{{ field }}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Create Post</button>
</form>
{% endblock %}
这是我的views.py代码
class PostCreate(View):
def get(self, request):
form = PostForm()
return render(request, 'blog/post_create_form.html', context={'form': form})
def post(self, request):
bound_form = PostForm(request.POST)
if bound_form.is_valid():
new_post = bound_form.save()
return redirect(new_post)
return render(request, 'blog/post_create_form.html', context={'form': bound_form})
这是我的表单代码
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'slug', 'body', 'tags']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'slug': forms.TextInput(attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control'}),
'tags': forms.SelectMultiple(attrs={'class': 'form-control'}),
}
def clean_slug(self):
new_slug = self.cleaned_data['slug'].lower()
if new_slug == 'create':
raise ValidationError('Slug may not be "Create"')
return new_slug`
答案 0 :(得分:0)
Class PostCreate(View): def get(自己,要求): 形式= PostForm() 返回render(request,'blog / post_create_form.html',context = {'form':form})
def post(self, request):
bound_form = PostForm(request.POST)
if bound_form.is_valid():
### new_post = bound_form.save() That's the problem.
bound_form.save()
###return redirect(new_post)
return HttpResponseRedirect('new_post')
return render(request, 'blog/post_create_form.html', context={'form': bound_form})