我有使用enum的主题下拉的ContactForm,主题是三个不同的字符串: 我有一个问题。 2.帮助/支持 请给我打个电话。
当用户发送消息时必须选择以上三种中的一种,这里是我的代码:
*的 forms.py *
来自django_enumfield import enum
class SubjectEnum(enum.Enum):
subject_one = 'I have a question'
subject_two = 'Help/Support'
subject_three = 'Please give me a call'
class ContactForm(forms.ModelForm):
name = forms.CharField(required=True)
email = forms.EmailField(required=True)
subject = forms.TypedChoiceField(choices=SubjectEnum.choices(), coerce=str)
message = forms.CharField(widget=forms.Textarea)
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(ContactForm, self).__init__(*args, **kwargs)
像belwo那样的view.py文件:
class ContactFormView(FormView):
form_class = ContactForm
template_name = "contact/email_form.jade"
success_url = '/email-sent/'
def form_valid(self, form):
message = "{name} / {email} said: ".format(
name=form.cleaned_data.get('name'),
email=form.cleaned_data.get('email'))
message += "\n\n{0}".format(form.cleaned_data.get('message'))
send_mail(
subject=form.cleaned_data.get('-subject').strip(),
message=message,
from_email="enquiries@example.com",
recipient_list=[settings.LIST_OF_EMAIL_RECIPIENTS],
)
return super(ContactFormView, self).form_valid(form)
联系表格:
- extends "base.jade"
- load crispy_forms_tags
block meta_title
| Contact Us
block content
.jumbotron
h1 Contact Us
.row
.span6
{% crispy form form.helper %}
我收到错误说,ValueError:ModelForm没有指定模型类。伙计们好吗? 感谢
答案 0 :(得分:2)
您应在模型表单中指定Meta
类并设置使用的模型。请注意,您不需要指定与您的模型字段没有区别的表单字段。
class ContactForm(forms.ModelForm)
name = forms.CharField(required=True)
email = forms.EmailField(required=True)
subject = forms.TypedChoiceField(choices=SubjectEnum.choices(), coerce=str)
message = forms.CharField(widget=forms.Textarea)
class Meta:
model = Contact
fields = ['name', 'email', 'subject', 'message']
如果您没有型号Contact
,则应使用Form
代替ModelForm
:
class ContactForm(forms.Form):
name = forms.CharField(required=True)
email = forms.EmailField(required=True)
subject = forms.TypedChoiceField(choices=SubjectEnum.choices(), coerce=str)
message = forms.CharField(widget=forms.Textarea)
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(ContactForm, self).__init__(*args, **kwargs)
See the documentation了解有关ModelForm
及其使用的更多信息。