I am new to Django, and I am trying to use django-friends in my website.
我是Django的新手,我正在尝试在我的网站上使用django-friends。
Here is a form from django-friends:
这是来自django-friends的表格:
>>> from django import forms
>>> class UserForm(forms.Form):
...
... def __init__(self, user=None, *args, **kwargs):
... self.user = user
... super(UserForm, self).__init__(*args, **kwargs)
...
>>> f = UserForm({})
>>> f.is_bound
False
The document said that "passing an empty dictionary creates a bound form with empty data", but why the result is unbound (f.is_bound is False)?
文档说“传递一个空字典会创建一个带有空数据的绑定表单”,但为什么结果是未绑定的(f.is_bound是False)?
Thank you so much!
非常感谢!
2 个解决方案
#1
5
What is happenning here is that UserForm
uses the first argument (user
) to initalize its internal state, so it doesn't pass anything to forms.Form
. To get the expected behaviour, you can pass an extra argument:
这里发生的是UserForm使用第一个参数(user)初始化其内部状态,因此它不会将任何内容传递给forms.Form。要获得预期的行为,您可以传递一个额外的参数:
>>> f = UserForm(None, {})
>>> f.is_bound
True
#2
10
Your __init__
statement is swallowing the first argument.
你的__init__声明正在吞下第一个参数。
Remove user=None
from your init statement, and perhaps pull it from the kwargs
instead.
从init语句中删除user = None,也许从kwargs中取出它。
class UserForm(forms.Form):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(UserForm, self).__init__(*args, **kwargs)
# now the form is actually receiving your first argument: args[0] == {}
#1
5
What is happenning here is that UserForm
uses the first argument (user
) to initalize its internal state, so it doesn't pass anything to forms.Form
. To get the expected behaviour, you can pass an extra argument:
这里发生的是UserForm使用第一个参数(user)初始化其内部状态,因此它不会将任何内容传递给forms.Form。要获得预期的行为,您可以传递一个额外的参数:
>>> f = UserForm(None, {})
>>> f.is_bound
True
#2
10
Your __init__
statement is swallowing the first argument.
你的__init__声明正在吞下第一个参数。
Remove user=None
from your init statement, and perhaps pull it from the kwargs
instead.
从init语句中删除user = None,也许从kwargs中取出它。
class UserForm(forms.Form):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(UserForm, self).__init__(*args, **kwargs)
# now the form is actually receiving your first argument: args[0] == {}