base.html中的Django脆皮表单

时间:2018-09-21 07:38:54

标签: django django-crispy-forms

我正在尝试在base.html中设置新闻稿形式。但是,由于缺乏个人能力和可用的示例,我找不到在base.html页脚中呈现新闻稿特定形式的方法。 目前,我在BioPyApp / forms / newsletter.py上基于应用程序模型(Newsletter)具有以下模型表单:

from django import forms
from BioPyApp.models import Newsletter
from crispy_forms.bootstrap import Field
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, Column, Row, Div


class NewsletterForm(forms.ModelForm):

    email = forms.EmailField(required=True,label="E-mail",max_length=254)

    class Meta:
       model = Newsletter
       fields = ['email'] 

    def __init__(self, *args, **kwargs):
       super(NewsletterForm, self).__init__(*args, **kwargs)
       self.helper = FormHelper()
       self.helper.form_method = 'post'
       self.helper.form_action = '/newsletter'
       self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success'))
       self.helper.form_class = 'form-vertical'
       self.helper.help_text_inline = False
       self.helper.form_tag = False
       self.helper.layout = Layout(Row(Field('email')))

    def clean_email(self):
        email = self.cleaned_data['email']
        if Newsletter.objects.filter(email=email).exists():
             raise forms.ValidationError("Email already in newsletter.")
        return email

我目前在BioPyApp / views.py上的视图:

from .forms.newsletter import NewsletterForm


    def newsletter(request):
        form = NewsletterForm(request.POST or None)
        if form.is_valid():
            form.save()
            return {'success': True}

我在url中设置为:

path('newsletter/',views.newsletter),

我的问题是:这是全球项目表格的正确结构吗?我应该在base.html中写些什么? (注意:如果我输入{% crispy form %},则显示其他形式(取决于URL)。)

最诚挚的问候

安德烈

0 个答案:

没有答案