我有一个问题: 我想更新特定的数据/产品,但a无法使用get\u object\u或\u 404
视图.py
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
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):
# queryset = Product.objects.all()[0].pk_id <-- I tried this
# queryset = Product.objects.get() <-- and this
queryset = Product.objects.all()
product1 = get_object_or_404(queryset, pk=pk)
#product1 = get_object_or_404(Product, pk=pk) <-- and this
if request.method == 'POST':
productUpdate_form = ProductForm(data=request.POST,files=request.FILES,instance=request.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 HttpResponseRedirect(reverse('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=request.product1)
context = {'productUpdate_form': productUpdate_form,}
return render(request, 'base/update.html',context)
url.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, name='product-update'), <--this link is ok
]
错误:
属性错误位于/1/更新/
“WSGIRequest”对象没有属性“product1”
请求方法:获取 请求URL:http://127.0.0.1:8000/1/update/ Django版本:3.1.1 异常类型:AttributeError 异常值:
“WSGIRequest”对象没有属性“product1”
异常位置:C:\Users\rodrigo negao\Desktop\PROJETOS\MyDjango\ECAPI\pages\views.py,ProductUpdateView中的第78行 Python可执行文件:C:\Users\rodrigo negao\Anaconda3\envs\ECAPI\Python.exe Python版本:3.8.5 Python路径:
['C:\Users\rodrigo negao\Desktop\PROJETOS\MyDjango\ECAPI', 'C:\Users\rodrigo negao\Anaconda3\envs\ECAPI\python38.zip', 'C:\Users\rodrigo negao\Anaconda3\envs\ECAPI\DLLs', 'C:\Users\rodrigo negao\Anaconda3\envs\ECAPI\lib', 'C:\Users\rodrigo negao\Anaconda3\envs\ECAPI', 'C:\Users\rodrigo negao\Anaconda3\envs\ECAPI\lib\site packages']
服务器时间:周四,2020年10月1日21:36:44-0300
因此,我无法在获取对象或404中比较pk,我需要它来找到并使用特定的数据/产品
还有什么方法可以使用获取\u对象\u或\u 404或比较链接/主键和数据/产品
请帮忙
最好使用ClassViewhttps://docs.djangoproject.com/en/3.1/ref/class-based-views/generic-editing/#django.views.generic.edit.UpdateView
问题位于以下位置:
request
不包含product1
属性,只需传递product1
对象:然而,这不是一个
UpdateView
:这不是一个基于类的视图,它也不是UpdateView
的子类相关问题 更多 >
编程相关推荐