所以我设法将表单输出到模板。但是由于前端样式已经完成,我在其中一种形式上遇到了一些麻烦。我只是希望能够在已经存在的HTML中输出标签名称等。我可以使用以下内容将表单输出到模板:
<form method="post">
{% csrf_token %}
{{enquiry_form.as_ul}}
<button type="submit" class="submit softcolor">
<span>Submit</span>
</button>
</form>
但是,我在模型上有一个ManytoMany字段,我希望用户能够使用复选框勾选多个选项。当我输出上面的内容时,我会得到一个选择框,其中列出了它所经过的类别。
{% csrf_token %}
{% for fields in enquiry_form %}
<div class="block-365 center clearfix">
<label>{{fields.label}}</label>
<div class="input-line">
<input name="">
</div>
</div>
{% endfor %}
所以我可以做类似上面的事情,这很好。但由于某种原因,CSRF保护停止工作。我还需要能够访问Brochure模型中的项目(manyToMany字段)。
这是我到目前为止的代码:
forms.py
from django.forms import ModelForm
from django import forms
from contact_enquiries import models
class ContactEnquiryForm(ModelForm):
class Meta:
model = models.ContactForm
fields=('name','email','company', 'subject', 'message')
class BrochureRequestForm(ModelForm):
class Meta:
model = models.ContactForm
fields = ('name', 'email', 'company', 'address', 'brochure',)
views.py
from contact_enquiries import forms
from django.shortcuts import render
from django.http import HttpResponseRedirect
def contact(request):
if request.method == 'POST':
form = forms.ContactEnquiryForm(request.POST)
en_form = forms.BrochureRequestForm(request.POST)
print(request.POST)
if form.is_valid():
#print "Form looks good!"
#e = models.ContactEnquiry(form.cleaned_data)
#e.save()
form.save()
return HttpResponseRedirect('/thanks/')
else:
form = forms.ContactEnquiryForm()
en_form = forms.BrochureRequestForm()
return render(request, 'contact.html', {
'contact_form' : form,
'enquiry_form' : en_form,
})
models.py
class ContactForm(models.Model):
name = models.CharField(max_length="300")
company = models.CharField(max_length="200")
email = models.CharField(max_length="300")
subject = models.TextField()
message = models.TextField()
address = models.TextField()
brochure = models.ManyToManyField("Brochure", blank=True)
def __unicode__(self):
self.name
class Meta:
verbose_name = "Contact Enquiry"
verbose_name_plural = "Contact Enquiries"
class Brochure(models.Model):
title = models.CharField(max_length="200")
def __unicode__(self):
self.title
class Meta:
verbose_name = "Brochure"
verbose_name_plural = "Brochures"
上面显示了HTML。在将模板输出到模板时,不确定哪种方法最好,但我需要能够使用HTML / CSS来节省时间重做。此外,我需要能够在宣传册表格上打开复选框。当他们填写表格时,他们可以选择要发送的PDF格式。
有任何问题请咨询!
答案 0 :(得分:1)
好的,事实证明我可以像这样渲染模板:
{% csrf_token %}
{% for fields in enquiry_form %}
<div class="block-365 center clearfix">
<label>{{fields.label}}</label>
<div class="input-line">
<input name="">
</div>
</div>
{% endfor %}
然后在我的类中,我将字段设置为输出到模板,我可以将窗口小部件设置为字段,如下所示:
fields = ('name', 'email', 'company', 'address', 'brochure',)
widgets = {'brochure': forms.CheckboxSelectMultiple()}
然后,这会将ManytoManyField呈现为复选框。
答案 1 :(得分:0)