Django 3:获取更新视图的对象或404

2024-06-17 10:40:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题: 我想更新特定的数据/产品,但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或比较链接/主键和数据/产品

请帮忙


Tags: djangofromimportformgetrequestuserspk
2条回答

最好使用ClassViewhttps://docs.djangoproject.com/en/3.1/ref/class-based-views/generic-editing/#django.views.generic.edit.UpdateView

# 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'),
]

问题位于以下位置:

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的子类


Note: Functions are normally written in snake_case, not PerlCase, therefore it is advisable to rename your function to product_update_view, not ProductUpdateView.

相关问题 更多 >