Django:模板中的两个FormView

时间:2017-08-02 16:11:32

标签: python django python-3.x django-forms django-views

大家好! 我想在模板中显示表单

我的表格是:

$("#submit").click(function(){
    $("#loading_gif").toggle();
    $("#myForm").submit();
});

我有两个FormView:

class ContactForm(forms.Form):
    contact_name = forms.CharField(
        required=True)
    contact_email = forms.EmailField(
        required=True)
    contact_phone = forms.CharField(
        required=True)
    subject = forms.CharField(
        required=True)
    message = forms.CharField(
        required=True,
        widget=forms.Textarea)

class CVCreateForm(forms.ModelForm):
    class Meta:
        model = CV
        fields = '__all__'

(注意:在第二种形式中,' form_cv'将成为PDF文件,我认为发送电子邮件不是问题,但我不太清楚。) 我想在TemplateView

中显示这两个FormView

谢谢:)

1 个答案:

答案 0 :(得分:1)

在TemplateView中,您只需要在上下文中传递两个表单,如下所示:

from django.views.generic import TemplateView

from .forms import ContactView, CVCreateView


class MyTemplateView(TemplateView):
    template_name = 'path/to/my_template.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['contact_form'] = ContactView()
        context['cv_form'] = CVCreateView()
        return context

在模板中,您将表单action属性设置为指向相应视图的网址ContactViewCVCreateView,如下所示:

<form action="{% url 'contact_form' %}" method="POST">
     {{ contact_form }}
</form>

<form action="{% url 'cv_form' %}" method="POST">
     {{ cv_form }}
</form>

希望这有帮助吗?