Django 表单集问题
我有 2 个模型,
class A(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=200)
class B(models.Model):
id=models.AutoField(primary_key=True)
user=models.ForeignKey(A)
name=models.CharField(max_length=200)
#forms.py
class BForm(ModelForm):
class Meta:
model=B
fields=('name','user')
def __init__(self,user_name,*args,**kwargs):
super(BForm,self).__init__(*args,**kwargs)
if user_name:
self.field['user']=forms.ModelChoiceField(queryset=A.objects.filter(name__icontains=user_name)
#views.py
def myview(request,user_name):
formset=formset_factory(BForm(user_name=user_name),extra=10)
我收到以下错误
“BForm”对象没有属性“名称”
实际上我只想在我的表单集中显示 A 类的选择性值
I have 2 models
class A(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=200)
class B(models.Model):
id=models.AutoField(primary_key=True)
user=models.ForeignKey(A)
name=models.CharField(max_length=200)
#forms.py
class BForm(ModelForm):
class Meta:
model=B
fields=('name','user')
def __init__(self,user_name,*args,**kwargs):
super(BForm,self).__init__(*args,**kwargs)
if user_name:
self.field['user']=forms.ModelChoiceField(queryset=A.objects.filter(name__icontains=user_name)
#views.py
def myview(request,user_name):
formset=formset_factory(BForm(user_name=user_name),extra=10)
I am getting following error
'BForm' object has no attribute 'name'
Actually i only want only selective value of class A to shown in my formset
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里存在一些问题:
首先,
BForm
类中的__init__
方法看起来是错误的。user_name
是一个关键字参数,但下面有条件if user
,而不在任何地方定义 user。其次,在定义表单集时不能使用
user_name
参数初始化表单。看来您正在尝试执行与堆栈溢出问题中相同的操作 传递自定义表单参数到表单集。第三,请提供完整的回溯。仅包含一行回溯,
'BForm' 对象没有属性 'name'
使得更难追踪问题所在。
There are a few issues here:
Firstly, the
__init__
method form theBForm
class looks wrong.user_name
is a keyword argument, but below you have the conditionif user
, without defining user anywhere.Secondly, you can't initialise the form with the
user_name
argument when defining the formset. It looks like you are trying to do the same as in the stack overflow question Passing Custom Form Parameters to Formset.Thirdly, please supply the entire traceback. Only including one line of the traceback,
'BForm' object has no attribute 'name'
makes it harder to track down where the problem is.