在 __init__ 时间将值插入 ModelForm 字段
我想将 first_name
、last_name
和 email
字段添加到 UserProfile 管理页面。因此,您可以在 UserProfile 管理中更改所有用户的详细信息,而不必转到其他页面来更改电子邮件和其他一些字段。
这就是我的自定义表单的样子:
class CustomProfileForm(forms.ModelForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.EmailField()
class Meta:
model = UserProfile
def __init__(self, *a, **k):
super(CustomProfileForm, self).__init__(*a, **k)
self.user_instance = None
if self.instance:
self.user_instance = self.instance.user
def clean_first_name(self):
self.user_instance.first_name = self.cleaned_data['first_name']
def clean_first_name(self):
self.user_instance.last_name = self.cleaned_data['laset_name']
def clean(self):
self.user_instance.save()
return self.cleaned_data
class UserProfileAdmin(admin.ModelAdmin):
form = CustomProfileForm
我不知道该怎么做才能完成此操作。我需要将 user_instance
详细信息提供给正确的表单类。
I want to add first_name
, last_name
, and email
fields to the UserProfile admin page. So you can change all the user's details from within the UserProfile admin instead of having to go to a different page to change email and some other fields.
This is what my custom form looks like:
class CustomProfileForm(forms.ModelForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.EmailField()
class Meta:
model = UserProfile
def __init__(self, *a, **k):
super(CustomProfileForm, self).__init__(*a, **k)
self.user_instance = None
if self.instance:
self.user_instance = self.instance.user
def clean_first_name(self):
self.user_instance.first_name = self.cleaned_data['first_name']
def clean_first_name(self):
self.user_instance.last_name = self.cleaned_data['laset_name']
def clean(self):
self.user_instance.save()
return self.cleaned_data
class UserProfileAdmin(admin.ModelAdmin):
form = CustomProfileForm
I don't know what to do to complete this. I need to give the user_instance
details to the proper form class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要在 init 方法中设置初始值,您可以使用 fields 字典。
To set the initial values in the init method you can use the fields dictionary.