在Django ModelForm中传递相关对象的字段 [英] Pass related object's field in Django ModelForm
问题描述
我有一个Django模型类,该类扩展了 django.contrib.auth.models.User
:
class MyModel(models.Model):user = models.OneToOneField(User,models.CASCADE,unique = True)bio = models.TextField()date_of_birth = models.DateField()
根据这个模型,我正在制作一个ModelForm:
class MyModelForm(forms.ModelForm):类Meta:型号= MyModel字段= ['bio','date_of_birth']
如何告诉MyModelForm接受用户的字段,例如 username
, first_name
, last_name
?
类别Meta字段中的示例我可以添加 ['bio','date_of_birth','user']
,但这将为我提供一个下拉列表,以选择MyModel与MyModelForm有关.
执行 ['bio','date_of_birth','user.first_name']
会引发异常 django.core.exceptions.FieldError:未知字段(user.first_name)为MyModel指定的
这是回溯 https://pastebin.com/0T42VKEP
我通过重写ModelForm的 __ init __
方法找到了自己的解决方案:
class MyModelForm(forms.ModelForm):first_name = Forms.CharField()类Meta:型号= MyModel字段= ['bio','date_of_birth']def __init __(self,* args,** kwargs):超级(MyModelForm,self).__ init __(* args,** kwargs)my_user = kwargs.get('instance')first_name = my_user.user.first_nameself.fields ['first_name'].initial = first_name#当我请求实例时,这将在html页面中显示名字
当我实例化表单时,我只是将MyModel的实例作为kwarg: form = MyModelForm(instance = my_model_instance)
I have a Django model class that extends the django.contrib.auth.models.User
:
class MyModel(models.Model):
user = models.OneToOneField(User, models.CASCADE, unique=True)
bio = models.TextField()
date_of_birth = models.DateField()
and out of this model I'm making a ModelForm:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['bio', 'date_of_birth']
How can I tell the MyModelForm to take in the User's fields such as username
, first_name
, last_name
?
Example in the class Meta fields I can add ['bio', 'date_of_birth', 'user']
but that will just provide me with the dropdown to select to whom shall the MyModel in the MyModelForm be related to.
Doing ['bio', 'date_of_birth', 'user.first_name']
throws an exception django.core.exceptions.FieldError: Unknown field(s) (user.first_name) specified for MyModel
Edit: here's the traceback https://pastebin.com/0T42VKEP
I kinda found my own solution, by overriding ModelForm's __init__
method:
class MyModelForm(forms.ModelForm):
first_name = forms.CharField()
class Meta:
model = MyModel
fields = ['bio', 'date_of_birth']
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
my_user = kwargs.get('instance')
first_name = my_user.user.first_name
self.fields['first_name'].initial = first_name #this will show the first name in the html page when i request the instance
And when I'm instantiating my form I just pass an instance of MyModel as a
kwarg: form = MyModelForm(instance=my_model_instance)
这篇关于在Django ModelForm中传递相关对象的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!