如何在django中创建模板标签并使用Form?

时间:2013-06-28 09:17:58

标签: django django-forms django-templates

我创建自定义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])

我在tempalte文件中使用此标记:

{% 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'),
)

并创建视图以获取网址:

# -*- 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 /”。 Tag创建“Rating”模型的“RatingForm”形式。当查看您的页面并使用表单和表单的人有效时,这是有效的(保存表单并重定向到页面“/ post / name-this-post /”),但是当发生错误时,您被重定向但不显示一个错误。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

首先,将尝试将block包含到您的模板文件中:

{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
    </div>
{% endfor %}

其次,post views.py处的redirect(reverse('post', args=[request.POST.get('url')]), form=form)是否存在?除了url(...) urlpatterns urls.py的{​​{1}}条目存在post之外?如果两者都存在,请将其添加到问题代码