如何使用UpdateView更新Django模型? [英] How do I use an UpdateView to update a Django Model?

查看:172
本文介绍了如何使用UpdateView更新Django模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to update a model in Django using the class-based generic view UpdateView.

我阅读了页面使用基于UpdateView的Django更新用户模型尝试让我开始,但是我'我得到一个错误'WSGIRequest'对象没有属性'id'

I read the page Updating User model in Django with class based UpdateView to try and get me started, but I'm getting an error 'WSGIRequest' object has no attribute 'id'

我是Django的一个新鲜的脸,所以如果我做一些愚蠢的事情请放心。

I'm a fresh face to Django, so please be forgiving if I'm doing something stupid.

// urls.py

//urls.py

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

// views.py

//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,但在请求变量中似乎没有出现。我这样做是错误的吗?

It's mostly just a modified version of the code originally posted, but I thought it'd work. I know that I'm trying to retrieve the id passed as a GET parameter, but that doesn't seem to come through in the request variable. Am I going about this the wrong way?

谢谢

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

I think I fixed it, but this may be wrong: I changed the lines

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

我可能是错的。

推荐答案

应该是:

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

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

Look at class based generic view dispatch explains that keyword arguments are assigned to 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)

这篇关于如何使用UpdateView更新Django模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆