所以我是Django的新手,我正在尝试一些教程。该代码与本教程中的代码完全相同,但对我而言不起作用。
views.py
from .forms import BlogPostForm
def blog_post_create_view(request):
form = BlogPostForm(request.POST or None)
if form.is_valid():
print(form.cleaned_data)
else:
print(form.slug, form.title, form.content)
template_name = "form.html"
context = {"form": None}
return render(request, template_name, context)
forms.py
from django import forms
class BlogPostForm(forms.Form):
title = forms.CharField()
slug = forms.SlugField()
content = forms.CharField(widget=forms.Textarea)
form.html
{% extends "base.html" %}
{% block content %}
{% if title %}
<h1> {{ title }}</h1>
{% endif %}
<form method="POST" action="."> {% csrf_token %}
{{ form.as_p }}
<button type="submit">SEND</button>
</form>
{%endblock%}
因此,当我运行此代码时,编写代码is_valid()
返回False
,我得到:
AttributeError: 'BlogPostForm' object has no attribute 'slug'