开发者

django forms not accepting request.user

开发者 https://www.devze.com 2023-01-29 16:53 出处:网络
I am trying to access request.user or get the current logged in user in order to filter content by the user ie only get the trophies or bag_list by the logged-in user.

I am trying to access request.user or get the current logged in user in order to filter content by the user ie only get the trophies or bag_list by the logged-in user.

my forms has a mixture or elements as seen below.

class HuntingReportForm(ModelForm):
    date_travel_started = forms.DateField(widget=extras.SelectDateWidget(years=range(1970,2012)))
    date_travel_ended = forms.DateField(widget=extras.SelectDateWidget(years=range(1970,2012)))
    wish_list = forms.ModelMultipleChoiceField(queryset=Specie.objects.all(), widget=FilteredSelectMultiple("verbose name", is_stacked=False), required=False)
    bag_list = forms.ModelMultipleChoiceField(queryset=Trophies.objects.all(), widget=FilteredSelectMultiple("verbose name", is_stacked=False), required=False)

    class Meta:
        model = HuntingReport
        exclude = ['user',]

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        self.validate = kwargs.pop('validate', False)
        super(HuntingReportForm, self).__init__(*args, **kwargs)

        self.fields['bag_list'].queryset = Trophies.objects.filter(user = self.user)
        users = User.objects.filter(userprofile__outfitter=True)
        self.fields['outfitter'].choices = [('', '')] + [(user.pk, user.get_full_name()) for user in users]
        self.fields.keyOrder = ['title', 'date_travel_started', 'date_travel_ended', 'outfitter', 'wish_list', 'bag_list','report']

Any help would be appreciated.

Traceback:
File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response
  99.                     response = callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.6/site-packages/django/contrib/auth/decorators.py" in __call__
  78.             return self.view_func(request, *args, **kwargs)
File "/Users/ApPeL/Sites/Django/omu2/../omu2/hunting_report/views.py" in create
  56.         form = HuntingReportForm(initial={'me':request.user}开发者_高级运维)
File "/Users/ApPeL/Sites/Django/omu2/hunting_report/forms.py" in __init__
  31.         self.fields['bag_list'].queryset = Trophies.objects.filter(user = self.user)

Exception Type: AttributeError at /hunting-reports/new/
Exception Value: 'HuntingReportForm' object has no attribute 'user'


If you initialize the form with HuntingReportFrom(user=request.user), this should work:

 def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        self.validate = kwargs.pop('validate', False)
        super(HuntingReportForm, self).__init__(*args, **kwargs)
        self.fields['bag_list'].queryset = Trophies.objects.filter(user = self.user)
0

精彩评论

暂无评论...
验证码 换一张
取 消