2 回答

TA貢獻1880條經驗 獲得超4個贊
問題出在:
productUpdate_form = ProductForm(instance=request.product1)
不request包含product1屬性,您只需傳遞product1對象即可:
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib import messages
from django.views.generic import (
UpdateView,
DeleteView
)
from product.models import Product
from pages.forms import ProductForm
def ProductUpdateView(request, pk):
product1 = get_object_or_404(Product, pk=pk)
if request.method == 'POST':
productUpdate_form = ProductForm(data=request.POST,files=request.FILES,instance=product1))
# Check to see the form is valid
if productUpdate_form.is_valid(): # and profile_default.is_valid() :
# Sava o produto
productUpdate_form.save()
# Registration Successful! messages.success
messages.success(request, 'Produto Modificado com Sucesso')
#Go to Index
return redirect('index')
else:
# One of the forms was invalid if this else gets called.
print(productUpdate_form.errors)
else:
# render the forms with data.
productUpdate_form = ProductForm(instance=product1)
context = {'productUpdate_form': productUpdate_form,}
return render(request, 'base/update.html',context)
然而,這不是一個UpdateView:這不是一個基于類的視圖,并且它不是從UpdateView.
注意:函數通常用Snake_case編寫,而不是PerlCase,因此建議將函數重命名為product_update_view, not ProductUpdateView。

TA貢獻1829條經驗 獲得超7個贊
最好使用 ClassView
# views.py
from django.views.generic.edit import UpdateView
from product.models import Product
from django.contrib import messages
from pages.forms import ProductForm
class ProductUpdateView(UpdateView):
? ? model = Product
? ? form_class = ProductForm
? ? template_name = 'base/update.html'
? ? def form_valid(self, form):
? ? ? ? self.object = form.save()
? ? ? ? messages.success(self.request, 'Produto Modificado com Sucesso')
? ? ? ? return redirect('index')
?
? ? def get_context_data(self, **kwargs):
? ? ? ? if 'productUpdate_form' not in kwargs:
? ? ? ? ? ? kwargs['productUpdate_form'] = self.get_form()
? ? ? ? return super().get_context_data(**kwargs)
? ? ? ? ?
# urls.py
from django.urls import include, path
from pages.views import (ProductListView,
? ? ? ? ? ? ? ? ? ? ? ? ProductUpdateView,
? ? ? ? ? ? ? ? ? ? ? ? ProductDeleteView)
urlpatterns = [
? ? path('listProduct/', ProductListView, name='listProduct'),
? ? path('<int:pk>/update/', ProductUpdateView.as_view(), name='product-update'),
]
添加回答
舉報