我想创建一个表单,用户可以在其中选择模型对象,但是会根据用户过滤选择。然后,我想将该对象传递到html模板页面,以便可以在页面上显示对象字段。
我获得了可以正确显示对象的表单,因此get函数可以正常工作,但是当用户提交表单时,出现了一个属性错误,提示“ QueryDict对象没有属性'user'”。所以我假设我的post函数出了问题。
错误堆栈跟踪
File "/Users/wsm-app/env/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "/Users/wsm-app/polls/views.py", line 244, in post
form = calendarForm(request=request.POST)
File "/Users/wsm-app/polls/forms.py", line 25, in __init__
user = request.user
AttributeError: 'QueryDict' object has no attribute 'user'
forms.py
class calendarForm(forms.Form):
inputDate = forms.ModelChoiceField(label="Select a date", queryset = None, empty_label="No date selected")
def __init__(self, *args, **kwargs):
request = kwargs.pop('request', None)
super().__init__(*args, **kwargs)
if request:
user = request.user
self.fields['inputDate'].queryset = Analysis.objects.filter(user=user).order_by('sessionID__startDate')
views.py
class MultiView(generic.TemplateView):
template_name = 'polls/analysis.html'
def get(self,request):
if self.request.user.is_authenticated:
form = calendarForm(request=request)
userid = self.request.user.id
args = {'form': form,'obj':Analysis.objects.filter(user=userid).order_by('sessionID__startDate').last()}
else:
args = {'form': form}
return render(request, self.template_name,args)
def post(self,request):
form = calendarForm(request=request.POST)
if self.request.user.is_authenticated:
if form.is_valid():
obj = form.cleaned_data['inputDate']
form = calendarForm(request=request)
args = {'form':form,'obj':obj}
else:
form = calendarForm(request=request)
args = {'form':form}
return render(request, self.template_name, args)
答案 0 :(得分:0)
用户位于请求对象内部,而不位于POST参数内部
def post(self,request):
form = calendarForm(request=request)
通过request.POST.user
而不是请求本身时,您将获得request.POST
(通过request.user
访问用户