gpt4 book ai didi

django 自定义表单标签

转载 作者:行者123 更新时间:2023-12-02 06:37:59 26 4
gpt4 key购买 nike

我在 Django 表单中自定义标签时遇到问题

这是文件 contact_form.py 中的表单代码:

from django import forms

class ContactForm(forms.Form):
def __init__(self, subject_label="Subject", message_label="Message", email_label="Your email", cc_myself_label="Cc myself", *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)

self.fields['subject'].label = subject_label
self.fields['message'].label = message_label
self.fields['email'].label = email_label
self.fields['cc_myself'].label = cc_myself_label

subject = forms.CharField(widget=forms.TextInput(attrs={'size':'60'}))
message = forms.CharField(widget=forms.Textarea(attrs={'rows':15, 'cols':80}))
email = forms.EmailField(widget=forms.TextInput(attrs={'size':'60'}))
cc_myself = forms.BooleanField(required=False)

我使用它的 View 看起来像:

def contact(request, product_id=None):
.
.
.
if request.method == 'POST':
form = contact_form.ContactForm(request.POST)
if form.is_valid():
.
.
else:
form = contact_form.ContactForm(
subject_label = "Subject",
message_label = "Your Message",
email_label = "Your email",
cc_myself_label = "Cc myself")

用于初始化标签的字符串最终将是取决于语言的字符串,即英语、荷兰语、法语等。

当我测试表单时,电子邮件未发送,表单返回的不是重定向页面:

<QueryDict: {u'cc_myself': [u'on'], u'message': [u'message body'],
u'email':[u'info@umx.com'], u'subject': [u'test message']}>:

主题标签之前的位置。这显然是一个代表表单字段及其内容的字典。

当我将文件 contact_form.py 更改为:

from django import forms

class ContactForm(forms.Form):
"""
def __init__(self, subject_label="Subject", message_label="Message", email_label="Your email", cc_myself_label="Cc myself", *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)

self.fields['subject'].label = subject_label
self.fields['message'].label = message_label
self.fields['email'].label = email_label
self.fields['cc_myself'].label = cc_myself_label
"""
subject = forms.CharField(widget=forms.TextInput(attrs={'size':'60'}))
message = forms.CharField(widget=forms.Textarea(attrs={'rows':15, 'cols':80}))
email = forms.EmailField(widget=forms.TextInput(attrs={'size':'60'}))
cc_myself = forms.BooleanField(required=False)

即禁用初始化然后一切正常。表单数据通过电子邮件发送,并显示重定向页面。很明显,初始化代码不正确。但什么?

我真的很感激一些帮助。

最佳答案

您应该更改表单init声明,打印的QueryDict是您在初始化表单时作为第一个参数传递的request.GET或request.POST。

我想改变这个

def __init__(self, subject_label="Subject", ...

到此

def __init__(self, data=None, subject_label="Subject", ... ...):
super(ContactForm, self).__init__(data, *args, **kwargs)
...

将解决您的问题。

关于django 自定义表单标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2726306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com