我正在使用python django框架开发一个简单的应用程序,并且我正在使用基于类的视图,当我使用UpdateView并尝试运行我的模板时,我得到了这个错误;
'QuerySet' object has no attribute '_meta'
这是我的视图代码
class UpdateStaff(LoginRequiredMixin, UpdateView):
template_name = 'app/update_staff.html'
form_class = UpdateStaffForm
model = Staff
def get_object(self, queryset=None):
obj = Staff.objects.filter(pk=self.kwargs['staff_id'])
return obj
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST or None,
instance=self.get_object())
if form.is_valid():
obj = form.save(commit=False)
obj.save()
messages.success(self.request, "Staff has been updated")
return self.get_success_url()
else:
messages.error(self.request, "Staff not updated")
return HttpResponseRedirect(reverse('update_staff'))
def get_success_url(self):
return HttpResponseRedirect(reverse('manage_staffs'))
def get_context_data(self, **kwargs):
context = super(UpdateStaff,
self).get_context_data()
context['messages'] = messages.get_messages(self.request)
context['form'] = self.form_class(self.request.POST or None,
instance=self.get_object())
return context
这是我的表格代码:
class UpdateStaffForm(ModelForm):
class Meta:
model = Staff
exclude = (
'profile_picture', 'start_work', 'last_login', 'groups',
'user_permissions', 'is_active', 'is_superuser',
'date_joined', 'end_work', 'can_sell_out_of_assigned_area',
'is_staff')
def __init__(self, *args, **kwargs):
super(UpdateStaffForm, self).__init__(*args,
**kwargs)
for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control'
任何人都有解决这个问题的想法,请帮助。
发布于 2017-08-24 17:41:34
get_object
方法返回queryset
,即记录列表,您可以在filter()
上使用first()
,而不是instance
.To get instance
。这将为您提供第一个实例。
def get_object(self, queryset=None):
obj = Staff.objects.filter(pk=self.kwargs['staff_id']).first()
return obj
发布于 2020-11-27 00:38:24
回答晚了,但值得一试。
from django.shortcuts import get_object_or_404
...
def get_object(self, queryset=None):
obj = get_object_or_404(Staff, pk=self.kwargs['staff_id'])
return obj
如果找不到对象,此方法将返回HTTP 404 Not Found
响应。
https://stackoverflow.com/questions/45856557
复制相似问题