Объект 'ModelFormOptions' не имеет атрибута 'concrete_fields' в Django

Я обновляю свою модель, но она показывает мне эту ошибку:

Объект «ModelFormOptions» не имеет атрибута «concrete_fields»

Какую ошибку я делаю?

views.py


class EditProduct(TemplateView):
    template_name = 'stock/editproduct.html'

    def get(self, request, product_id):
        productedit = get_object_or_404(Product, pk=product_id)
        data=Product.objects.get(id=product_id)
        form = EditProductForm(instance=data)
        args = {'form':form, 'productedit':productedit}
        return render(request, self.template_name, args)

    def post(self, request, product_id):
        data = Product.objects.get(id=product_id)
        form = EditProductForm(instance=data)
        form = EditProductForm(request.POST, request.FILES, instance=form)
        if form.is_valid():
            productadded = form.save(commit=False)
            productadded.saler =  request.user
            productadded.pub_date = timezone.datetime.now()
            productadded.save()
            return redirect('stock')
        else:
            args = {'form': form}
            return render(request, self.template_name, args)

ВЫСЛЕЖИВАТЬ

 File "C:UsersAdil IjazAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocorehandlersexception.py", line 34, in inner
    response = get_response(request)
  File "C:UsersAdil IjazAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocorehandlersase.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:UsersAdil IjazAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocorehandlersase.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:UsersAdil IjazAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocontribauthdecorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:UsersAdil IjazAppDataLocalProgramsPythonPython38-32libsite-packagesdjangoviewsgenericase.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:UsersAdil IjazAppDataLocalProgramsPythonPython38-32libsite-packagesdjangoviewsgenericase.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "C:UsersAdil IjazDesktoponlineProjectmarketstockviews.py", line 109, in post
    form = EditProductForm(request.POST, request.FILES, instance=form)
  File "C:UsersAdil IjazDesktoponlineProjectmarketstockforms.py", line 39, in __init__
    super(EditProductForm, self).__init__(*args, **kwargs)
  File "C:UsersAdil IjazAppDataLocalProgramsPythonPython38-32libsite-packagesdjangoformsmodels.py", line 293, in __init__
    object_data = model_to_dict(instance, opts.fields, opts.exclude)
  File "C:UsersAdil IjazAppDataLocalProgramsPythonPython38-32libsite-packagesdjangoformsmodels.py", line 86, in model_to_dict
    for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):
AttributeError: 'ModelFormOptions' object has no attribute 'concrete_fields'

Всего 1 ответ


instance не должен быть EditProductForm , instance :

class EditProduct(TemplateView):
    template_name = 'stock/editproduct.html'

    # …

    def post(self, request, product_id):
        data = Product.objects.get(id=product_id)
        form = EditProductForm(request.POST, request.FILES, instance=data)
        if form.is_valid():
            productadded = form.save(commit=False)
            productadded.saler =  request.user
            productadded.pub_date = timezone.datetime.now()
            productadded.save()
            return redirect('stock')
        else:
            args = {'form': form}
            return render(request, self.template_name, args)

При этом, возможно, было бы лучше использовать UpdateView [Django-doc] и удалить много стандартного кода:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse
from django.views.generic.edit import UpdateView

class EditProduct(LoginRequiredMixin, UpdateView):
    template_name = 'stock/editproduct.html'
    model = Product
    pk_url_kwarg = 'product_id'
    form_class = EditProductForm
    success_url = reverse_lazy('stock')

    def form_valid(self, form):
        form.instance.saler = request.user
        form.instance.pub_date = timezone.datetime.now()
        super().form_valid(form)

Примечание . Вы можете ограничить представления классовым представлением для аутентифицированных пользователей с помощью LoginRequiredMixin [Django-doc] .


Есть идеи?

10000