我有一个在对象详细信息页面上出现的django表单。我想用一个隐藏的表单字段预填充它出现的对象详细信息页面的slug。我在同一个表单上也有一个重写的保存方法,这样我就可以提供一些处理并将其保存到正确的模型中。但是,当我在表单上引入重写的 init 以预填充字段(并在表单调用中提供带有slug的 init )时,重写的保存将停止工作。这是为什么?
我的代码:
urls.py
url(r'^my_object_detail/(?P<slug>[A-Za-z0-9-]{1,80})/$', my_object_detail, name = 'my_object_detail'),
views.py
def my_object_detail(request, slug, template_name='my_plan_detail_page.html', **kwargs):
my_object = get_object_or_404(MyObjects, slug=slug)
form = ContactForm(request.POST or None, slug=slug)
if request.method =='POST':
if form.is_valid():
form.save()
forms.py
class ContactForm(forms.Form):
first_name = forms.CharField(label='', max_length=30, required=False, widget=forms.TextInput(attrs={'class':'my-class-1','placeholder':'First Name'}))
last_name = forms.CharField(label='', max_length=30, required=False, widget=forms.TextInput(attrs={'class':'my-class-1','placeholder':'Last Name'}))
email = forms.EmailField(label='', required=False, widget=forms.TextInput(attrs={'class':'my-class-2','placeholder':'Email Address'}))
interested_in = forms.CharField(max_length=50, required=False, widget=forms.HiddenInput())
def __init__(self, request=None, slug=None, *args, **kwargs):
self.request = request
self.slug = slug
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['interested_in'].widget.attrs['value'] = slug
def save(self):
data = self.cleaned_data
first_name = data['first_name']
last_name = data['last_name']
email = data['email']
interested_in = data['interested_in']
if settings.CURRENT_HOST == 'host-1':
lead_source = "host-1"
else:
lead_source = 'host-2'
new_contact = MyContact(first_name=first_name, last_name=last_name, email=email, interested_in=interested_in, lead_source=lead_source)
new_contact.save()
可能是相关的 - 如果我删除重载的init,并在views.py中进行表单调用,如下所示,重写的保存方法可以正常工作:
form = ContactForm(request.POST or None)
感谢您提供的任何见解。
答案 0 :(得分:1)
您已经更改了表单初始化的签名,因此它现在期望请求和slug作为前两个参数,但是您实际上在初始化时将表单数据作为第一个传递。
将其更改为:
def __init__(self, args, **kwargs):
self.request = kwargs.pop('request', None)
self.slug = kwargs.pop('slug', None)
...etc...