Django如何在我的表单类中获取当前用户

时间:2019-07-15 15:22:09

标签: python django

我想让当前用户登录到form.py类中,以便在CharField中显示他的传记(带有占位符或值)

我尝试了 init 方法,但对我来说不起作用,idk我在做什么错了...

这是我的表单类

class ProfileSettingsForm(forms.Form):
    avatar = forms.ImageField(required=False)
    description = forms.CharField(required=False, max_length=230, widget=forms.Textarea(attrs={"value": "here i want the description of the current user"}))


使用 init

class ProfileSettingsForm(forms.Form):

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(ProfileSettingsForm, self).__init__(*args, **kwargs)


    avatar = forms.ImageField(required=False)
    description = forms.CharField(required=False, max_length=230, widget=forms.Textarea(attrs={"value": self.user}))

我尝试过这种方法

class ProfileSettingsForm(forms.Form):

    user = None

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(ProfileSettingsForm, self).__init__(*args, **kwargs)

    avatar = forms.ImageField(required=False)
    description = forms.CharField(required=False, max_length=230, widget=forms.Textarea(attrs={"value": self.user}))

但它返回None


在我的views.py中:

form = forms.ProfileSettingsForm(user=request.user)

1 个答案:

答案 0 :(得分:0)

如果您使用的是基于类的视图,则可以覆盖get_form_kwargs方法。

views.py

# View might not be the correct class for you to inherit from, it's more a example. Having said that, you'd probably use CreateView
class YourView(View):
    def get_form_kwargs(self):
        form = super().get_form_kwargs()
        form['user'] = self.request.user
        return form

forms.py

class ProfileSettingsForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(ProfileSettingsForm, self).__init__(*args, **kwargs)

    avatar = forms.ImageField(required=False)
    description = forms.CharField(required=False, max_length=230, widget=forms.Textarea(attrs={"value": self.user}))