'QuerySet' object has no attribute '_meta'

Joseph Daudi picture Joseph Daudi · Aug 24, 2017 · Viewed 22.1k times · Source

i am developing a simple app with python django framework and i am using Class based Views, when i use the UpdateView and try to run my template i get this error;

'QuerySet' object has no attribute '_meta'

This is my view codes

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

and this is my form codes:

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'

Anyone having an idea to solve this please help.

Answer

Rajez picture Rajez · Aug 24, 2017

The get_object method returns queryset i.e list of records, instead of instance.To get instance you can use first() on filter() . This will gives you first occurrence.

def get_object(self, queryset=None):
    obj = Staff.objects.filter(pk=self.kwargs['staff_id']).first()
    return obj