在Django中,def formfield_for_manytomany
是一个可编辑的表单字段,它允许对ManyToManyField
中的多个表进行编辑。要为一个可编辑对象指定ID,可以在formfield_for_manytomany
方法中返回一个IDField
对象,如下所示:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.forms.models import inlineformset_factory
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['name', 'description', 'my_m2m_field']
my_m2m_field = forms.ModelChoiceField(
queryset=MyModel.objects.all(),
widget=forms.Select(attrs={'id': 'my-m2m-field'})
)
class MyModelFormSet(inlineformset_factory(MyModelForm)):
class Meta:
model = MyModel
fields = ['name', 'description', 'my_m2m_field']
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == 'my_m2m_field':
kwargs['widget'] = forms.Select(attrs={'id': 'my-m2m-field'})
return forms.IDField(widget=forms.HiddenInput(), required=False)
return super().formfield_for_manytomany(db_field, request, **kwargs)
class UserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
在上面的代码中,我们首先定义了一个MyModelForm
,它继承自ModelForm
,并且包含了name
、description
和my_m2m_field
这些字段。其中my_m2m_field
是一个ManyToManyField
,它关联了MyModel
和MyModel
。
接下来,我们定义了一个MyModelFormSet
,它继承自inlineformset_factory
,并且也关联了my_m2m_field
。在formfield_for_manytomany
方法中,我们返回了一个IDField
对象,它的widget
属性指定了使用Select
控件,并且attrs
属性指定了控件的属性。因为我们希望这个IDField
对象是由Select
控件来实现的,所以我们不能直接返回forms.IDField
对象。
最后,我们在UserForm
中使用了UserCreationForm
来创建用户表单,并且在Meta
属性中指定了模型和字段。在formfield_for_manytomany
方法中,我们同样返回了一个IDField
对象,但是与MyModelFormSet
不同的是,我们没有在widget
属性中指定使用Select
控件,而是指定了forms.HiddenInput
。这是因为在UserForm
中,我们没有必要让用户选择User
对象的ID,因为用户已经创建了一个User
对象,我们只需要将用户对象返回即可。
没有搜到相关的文章