在 __init__ 时间将值插入 ModelForm 字段

发布于 2024-10-01 00:50:09 字数 1067 浏览 0 评论 0原文

我想将 first_namelast_nameemail 字段添加到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

握住你手 2024-10-08 00:50:09

要在 init 方法中设置初始值,您可以使用 fields 字典。

def __init__(self, *a, **k):
    # < snip >
    self.fields[ 'email' ].initial = self.user_instance.email
    # ... and any others

To set the initial values in the init method you can use the fields dictionary.

def __init__(self, *a, **k):
    # < snip >
    self.fields[ 'email' ].initial = self.user_instance.email
    # ... and any others
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文