简体   繁体   English

在Django的选择小部件中可以选择request.user

[英]request.user as a choice in select widget in Django

I have a model field 我有一个模特领域

is_anonymous = BooleanField(default=False)

I also have a ModelForm . 我也有一个ModelForm I want this field to be represented with a select widget. 我希望用select小部件来表示该字段。

It would be 这将是

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['is_anonymous']
        widgets = {
            'is_anonymous': forms.NullBooleanSelect(),
        }

It works. 有用。 But I want the select widget to only have two choices true (1) and false (0) and the represented text in each option should be Anonymous for true and self.request.user for false . 但是我希望select小部件只有两个选择true (1)和false (0),并且每个选项中表示的文本对于true应当为Anonymous ,对于false应当为self.request.user

I think I have to do this replacement in the views as self.request.user is not available in the ModelForm . 我认为我必须在视图中进行此替换,因为self.request.userModelForm不可用。

How can I do this? 我怎样才能做到这一点?

It's not 100% clear what you want, but if you want to display a select dropdown with only two choices; 并不是100%清楚您想要什么,但是如果您想显示一个只有两个选项的选择下拉列表; "Anonymous" which maps to True and "myusername" (ie the username of the current user) which maps to False, you need to override the is_anonymous field's widget's choices attribute: 映射为True的“匿名”和映射为False的“ myusername”(即当前用户的用户名),您需要覆盖is_anonymous字段的小部件的choices属性:

class MyModelForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['is_anonymous'].widget = forms.Select(choices=[
            (True, "Anonymous"),
            (False, user.username)
        ])

    class Meta:
        model = MyModel
        fields = ['is_anonymous']

because we need the user object in our form, we need to pass it manually as a parameter when defining the form in our view. 因为我们需要表单中的user对象,所以在视图中定义表单时需要手动将其作为参数传递。 This depends on the type of view you are using, but assuming it's a generic class based CreateView , you need the following: 这取决于您使用的视图类型,但是假设它是基于CreateView的通用类,则需要满足以下条件:

class MyCreateView(CreateView):
    form_class = MyModelForm
    ...

    def get_form(self, form_class):
        return self.form_class(self.request.user, **self.get_form_kwargs())

    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM