如何使用UpdateView更新Django模型?

时间:2012-02-14 04:34:35

标签: django view

我正在尝试使用基于类的通用视图UpdateView更新Django中的模型。

我阅读页面Updating User model in Django with class based UpdateView试图让我开始,但我收到错误'WSGIRequest'对象没有属性'id'

我是Django的新面孔,所以如果我做些蠢事,请原谅。

// urls.py

url(r'^portfolios/update/(?P<id>\d+)/$',PortfoliosUpdateView.as_view()),

// views.py

class PortfoliosUpdateView(UpdateView):
    form_class = PortfoliosCreateForm
    model = Portfolios
    template_name = 'portfolios/create.html'

    def get(self, request, **kwargs):
        self.object = Portfolios.objects.get(id=self.request.id)
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        context = self.get_context_data(object=self.object, form=form)
        return self.render_to_response(context)

    def get_object(self, queryset=None):
        obj = Portfolios.objects.get(id=self.request.id)
        return obj

它主要只是最初发布的代码的修改版本,但我认为它可行。我知道我正在尝试检索作为GET参数传递的id,但在请求变量中似乎没有。我是以错误的方式解决这个问题吗?

由于

编辑:我想我修好了,但这可能是错的: 我改变了行

self.object = Portfolios.objects.get(id=self.request.id)
obj = Portfolios.objects.get(id=self.request.id)

self.object = Portfolios.objects.get(id=self.kwargs['id'])
obj = Portfolios.objects.get(id=self.kwargs['id'])

我错了。

3 个答案:

答案 0 :(得分:24)

应该是:

def get_object(self, queryset=None):
    obj = Portfolios.objects.get(id=self.kwargs['id'])
    return obj

查看基于类的通用视图调度说明关键字参数已分配给self.kwargs。:

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    self.request = request
    self.args = args
    self.kwargs = kwargs
    return handler(request, *args, **kwargs)

答案 1 :(得分:7)

尝试访问GET查询字符串时,您需要

id = self.request.GET.get('id',None)

但是,您的观点可以简化:

from django.conf.urls import *
from django.views.generic import UpdateView
from yourapp.models import Portfolios
from yourapp.forms import PortfoliosCreateForm

urlpatterns = patterns('',
    url('^portfolios/update/(?P<pk>[\w-]+)$', UpdateView.as_view(
        model=Portfolios,
        form_class=PortfoliosCreateForm,
        template_name='portfolios/create.html',
        success_url='/portfolios'
    ), name='portfolio_update'),
)

答案 2 :(得分:0)

views.py

class MyUpdateView(UpdateView):
    model = ModelName  # required
    template_name = 'x/h1.html'
    form_class = ModelNameForm
    success_url = reverse_lazy('app:page1')

    def get_queryset(self):
        """
        Optional condition to restrict what users can see
        """
        queryset = super().get_queryset()
        return queryset.filter(id__lt=20)

    def get_success_url(self):
        return reverse_lazy(
            'app1:abc',
            kwargs={'pk': self.object.id}
        )

urls.py

urlpatterns=[]

path('xyz/<pk>/', MyUpdateView.as_view(),name='xyz')

my_model_view.html

{{form}}

根据我们在ModelName中的条件,您将可以在URL /xyz/<pk>/上编辑<pk>,其中get_queryset()可以是1到20之间的任何值。排除该条件以允许用户编辑任何对象。

self.object仅在发布请求到UpdateView后可用。