如何使用 UpdateView 更新 Django 模型? [英] How do I use an UpdateView to update a Django Model?
问题描述
我正在尝试使用基于类的通用视图 UpdateView 更新 Django 中的模型.
I'm trying to update a model in Django using the class-based generic view UpdateView.
我阅读了页面 在 Django 中使用类更新用户模型基于 UpdateView 尝试让我开始,但我收到一个错误 '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
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,但这似乎没有出现在请求变量中.我是不是用错了方法?
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屋!