我正在尝试访问request.user或获取当前登录用户以便用户过滤内容,即仅由登录用户获取奖杯或bag_list。
我的表单中有一个或多个元素,如下所示。
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']
任何帮助都将不胜感激。
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'
答案 0 :(得分:7)
如果您使用HuntingReportFrom(user=request.user)
初始化表单,则应该有效:
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)