:Django表单 - 输入框未在模板

时间:2016-11-13 20:05:36

标签: python django

我无法让我的表单显示在我渲染的模板上。提交按钮在那里,但没有别的。我有两种形式,一种可以正常使用我无法显示的EstimateForm

编辑:我忘了提到估算表单是基本模板的一部分,特别是它在网站页脚中。联系人模板正在扩展基本模板。基本模板中的表单未显示在任何模板上。很抱歉没有首先提供此信息。

这是模板

<form role="form" action="" method="post" class="contact-form" style="margin-top: 25px">
     {% csrf_token %}
     {{ estimate_form.as_p }}
    <button type="submit" class="thm-btn">Submit</button>
</form>

这是呈现的内容

<form role="form" action="" method="post" class="contact-form" style="margin-top: 25px" novalidate="novalidate">
  <input type="hidden" name="csrfmiddlewaretoken" value="lfudMn6U8TBJ2czhZM4UZTINnP6xoLZs">

   <button type="submit" class="thm-btn">Submit</button>
</form>

形式。吡啶

class ContactForm(forms.Form):
    contact_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Name*'}))
    contact_email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Email*'}))
    contact_phone = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Phone Number*'}))
    content = forms.CharField(
        required=True,
        widget=forms.Textarea(attrs={'placeholder': 'Your comments'})
    )


class EstimateForm(forms.Form):
    contact_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Name*'}))
    contact_email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Email*'}))
    contact_phone = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Phone Number*'}))

    def __init__(self, *args, **kwargs):
        super(BottomForm, self).__init__(*args, **kwargs)
        self.fields['contact_name'].label = ""
        self.fields['contact_email'].label = ""
        self.fields['contact_phone'].label = ""

views.py

def contact(request):
    form_class = ContactForm

    if request.method == 'POST':
        form = form_class(data=request.POST)

        if form.is_valid():
            contact_name = request.POST.get(
                'contact_name'
                , '')
            contact_email = request.POST.get(
                'contact_email'
                , '')
            contact_phone = request.POST.get(
                'contact_phone'
                , '')
            form_content = request.POST.get('content', '')

            # Email the profile with the
            # contact information
             template = get_template('contact_template.txt')
            context = Context({
               'contact_name': contact_name,
                'contact_email': contact_email,
                'contact_phone': contact_phone,
                'form_content': form_content,
            })
            content = template.render(context)
            send_mail('Email from your website', content, context['contact_email'],
                      ['email'],
                      fail_silently=False)
        return redirect('/contact')
    return render(request, 'main/contact.html', {
        'form': form_class,
    })


def estimate(request):
form_class = EstimateForm

if request.method == 'POST':
    form = form_class(data=request.POST)

    if form.is_valid():
        contact_name = request.POST.get(
            'contact_name'
            , '')
        contact_email = request.POST.get(
            'contact_email'
            , '')
        contact_phone = request.POST.get(
            'contact_phone'
            , '')
        form_content = request.POST.get('content', '')

        # Email the profile with the
        # contact information
        template = get_template('contact_template.txt')
        context = Context({
            'contact_name': contact_name,
            'contact_email': contact_email,
            'contact_phone': contact_phone,
            'form_content': form_content,
        })
        content = template.render(context)
        send_mail('Email from your website', content, context['contact_email'],
                  ['@gmail.com'],
                  fail_silently=False)
    return redirect('/contact')
return render(request, 'main/contact.html', {
    'estimate': form_class,
})

3 个答案:

答案 0 :(得分:1)

您正在传递带有'估计'键的表单

return render(request, 'main/contact.html', {
    'estimate': form_class,
})

但是在模板中,您试图通过

访问它
{{ estimate_form.as_p }}

只需将其更正为{{ estimate.as_p }}

即可

答案 1 :(得分:0)

在视图中,您只需将ContactForm定义为form_class。但是你没有定义estimate_form,这就是为什么你没有看到它。 所以你的观点必须如下:

def contact(request):
form_class = ContactForm

if request.method == 'POST':
    form = form_class(data=request.POST)

    if form.is_valid():
        contact_name = request.POST.get(
            'contact_name'
            , '')
        contact_email = request.POST.get(
            'contact_email'
            , '')
        contact_phone = request.POST.get(
            'contact_phone'
            , '')
        form_content = request.POST.get('content', '')

        # Email the profile with the
        # contact information
         template = get_template('contact_template.txt')
        context = Context({
           'contact_name': contact_name,
            'contact_email': contact_email,
            'contact_phone': contact_phone,
            'form_content': form_content,
        })
        content = template.render(context)
        send_mail('Email from your website', content, context['contact_email'],
                  ['email'],
                  fail_silently=False)
    return redirect('/contact')
return render(request, 'main/contact.html', {
    'form': form_class, 'estimate_form': estimate_form
})

答案 2 :(得分:0)

这里至少有四个问题,但并非所有问题都与您提出的问题有关。

首先,您将表单类而不是实例传递给模板。您需要首先实例化该类。

其次,您将其传递到名称为estimate的模板中,但在模板中您将其称为estimate_form。您需要使用相同的名称。

第三,当表单无效时,您不会将带有错误的实例化表单传递回模板,因此用户永远不会知道它为何无效。

第四,当表单有效时,您应该从form.cleaned_data获取数据,而不是直接从POST获取数据。

全部放在一起:

def estimate(request):
    form_class = EstimateForm

    if request.method == 'POST':
        form = form_class(data=request.POST)

        if form.is_valid():
            contact_name = form.cleaned_data['contact_name']
            contact_email = form.cleaned_data['contact_email']
            contact_phone = form.cleaned_data['contact_phone']
            form_content = form.cleaned_data['content']

            # Email the profile with the
            # contact information
            template = get_template('contact_template.txt')
            context = Context({
                'contact_name': contact_name,
                'contact_email': contact_email,
                'contact_phone': contact_phone,
                'form_content': form_content,
            })
            content = template.render(context)
            send_mail('Email from your website', content, context['contact_email'],
                      ['binford.blake@gmail.com'],
                      fail_silently=False)
        return redirect('/contact')
    else:
        form = form_class()
    return render(request, 'main/contact.html', {
        'estimate_form': form,
    })