Django在每个页面上添加反馈表单

时间:2013-01-15 17:45:09

标签: django django-forms django-views

我有一个用户反馈的表单视图:

urls.py:

url(
    r'^feedback/$',
    'tool.views.Feedback',
    name='feedback'
),
url(
    r'^thanks/$',
    direct_to_template, {
        'template': 'tool_feedback_thanks.html'
    },
    name='feedback_thanks'
),

forms.py:

class FeedbackForm(forms.Form):
    yes_no = forms.ChoiceField(
        choices=YES_NO_CHOICE,
        initial=1,
        widget=forms.RadioSelect(attrs={'class': 'can_reveal_input'}),
        label="Are you happy with Our service?"
    )
    comments = forms.CharField(
        widget=forms.Textarea(attrs={
            'class': 'hidden', 'placeholder': 'Leave us your comments...'
        }),
        required=False,
        label=""
    )

views.py:

def Feedback(request,
                 template_name='tool_feedback.html'):
    title = u'Leave us some feedback'
    form = FeedbackForm(request.POST or None)
    if form.is_valid():
        yes_no = form.cleaned_data['yes_no']
        comments = form.cleaned_data['comments']
        sender = "A Unirac website user"
        recipients = ['person@example.com']
        send_mail(yes_no, comments, sender, recipients)
        return HttpResponseRedirect(
            reverse('feedback_thanks')
        )
    return render_to_response(template_name, {
        'title': title,
        'form': form,
    }, RequestContext(request))

这是一种享受,但现在客户要求每个页面都包含此表单。我想表格可以通过js提交到相应的网址,但是在每个页面上包含未绑定表单的最佳方式是什么?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

我认为包含表单的最简单方法是使用assignment_tag

在模板库中:

@register.assignment_tag
def feedback_form(format_string):
    return FeedbackForm()

在模板中

{% feedback_form as form %}
{# display form... %}
{{ form.as_p }}

答案 1 :(得分:0)

要添加到@bmihelac,谁的答案对我来说真的很有效。由于django 2.0 assignment_tagdeprecated赞成simple_tag。因此,您可以将assignment_tag替换为simple_tag,从而完全按照他的回答,如下所示:

from django import template

from .forms import FeedbackForm

register = template.Library()


@register.simple_tag
def feedback_form():
    return FeedbackForm()

然后只需参考https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/#code-layout,了解有关如何将其导入模板的信息!