我创建了自定义 django 模板并使用了 Form:
这是文件 ratings.py 使用标签:
from django import template
from django.contrib.contenttypes.models import ContentType
from Ratings.forms import RatingsForm
register = template.Library()
class RatingFormNode(template.Node):
def __init__(self, content, id, varname):
self.content = content.split('.')
self.varname = varname
self.id = template.Variable(id)
def render(self, context):
id = self.id.resolve(context)
content = ContentType.objects.get(app_label=self.content[0], model=str(self.content[1]).lower())
context[self.varname] = RatingsForm(initial={'content_type': content, 'object_id': id})
return ''
@register.tag(name='rating')
def rating(parser, token):
"""
{% rating appname.Modelname 1 as Newsletter_Form %}
"""
bits = token.split_contents()
if bits[3] != 'as':
raise template.TemplateSyntaxError, "third argument to the get_latest tag must be 'as'"
return RatingFormNode(bits[1], bits[2], bits[4])
我在模板文件中使用这个标签:
{% rating appname.Modelname id as rating_form %}
<form action="{% url 'ratings_add' %}" method="POST">
{% csrf_token %}
{{ rating_form }}
<input type="hidden" name="url" value="{{ post.slug }}" />
<input type="submit" value="Wyślij" />
</form>
这是 urls.py:
from django.conf.urls import patterns, url
urlpatterns = patterns('Ratings.views',
url(r'^add/$', 'ratings_add', name='ratings_add'),
)
并创建视图以获取 url:
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.http.response import Http404
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from Ratings.forms import RatingsForm
def ratings_add(request):
if not request.method == 'POST':
return Http404
form = RatingsForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('post', args=[request.POST.get('url')]))
else:
request.session['form_data'] = request.POST
return redirect(reverse('post', args=[request.POST.get('url')]), form=form)
我在模板中使用这个标签和 url:“/post/name-this-post/”。标记创建模型“Rating”的“RatingForm”形式。当查看您的页面并使用表单和表单的人有效时,这是有效的(保存表单并重定向到页面“/post/name-this-post/”),但是当发生错误时,您会被重定向但不显示一个错误。我该如何解决?