我正在按照以下教程学习如何创建Django表单。我真的坚持为什么表单没有出现在指定的html页面上。
这是我的代码:
评论/ url.py
urlpatterns = [
url(r'^$', views.review_list, name='review_list'),
url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'),
url(r'^wine/$', views.wine_list, name='wine_list'),
url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'),
url(r'^wine/(?P<wine_id>[0-9]+)/add_review/$', views.add_review, name='add_review')]
评论/ Forms.py
from django.forms import ModelForm, Textarea
from reviews.models import Review
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = ('user_name', 'rating', 'content')
widgets = {
'content': Textarea(attrs={'cols': 40, 'rows': 15})
}
的评价/ Views.py:
# View that provides wine information and reviews
def wine_detail(request, wine_id):
wine = get_object_or_404(Wine, pk=wine_id)
return render(request, 'reviews/wine_detail.html', {'wine': wine})
# View that contains add review form
def add_review(request, wine_id):
wine = get_object_or_404(Wine, pk=wine_id)
form = ReviewForm(request.POST)
if form.is_valid():
# Retrieves values entered
rating = form.cleaned_data['rating']
content = form.cleaned_data['content']
user_name = form.cleaned_data['user_name']
review = Review()
review.wine = wine
review.user_name = user_name
review.rating = rating
review.content = content
review.pub_date = datetime.datetime.now()
review.save()
return HttpResponseRedirect(reverse('reviews:wine_detail', args=(wine.id,)))
return render(request, 'reviews/wine_detail.html', {'wine': wine, 'form': form})
模板
<h2>{{ wine.name }}</h2>
<h5>{{ wine.review_set.count }} reviews ({{ wine.average_rating | floatformat }} average rating)</h5>
<h3>Recent reviews</h3>
{% if wine.review_set.all %}
<div>
{% for review in wine.review_set.all %}
<div>
<em>{{ review.content }}</em>
<h6>Rated {{ review.rating }} of 5 by {{ review.user_name }}</h6>
<h5>
<a href="{% url 'reviews:review_detail' review.id %}">
Read more </a>
</h5>
</div>
{% endfor %}
</div>
{% endif %}
<h3>Add your review</h3>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'reviews:add_review' wine.id %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Add" />
</form>
以下是现在的截图:
显然,您可以看到在没有输入表单的情况下生成表单元素。我认为{{form.as_p}}可能是错的。我不知道为什么会这样。我检查了语法,我没有发现任何会导致表单丢失的错误。 任何帮助将非常感激。