gpt4 book ai didi

django - 使用DJango DetailView的发布请求给出错误 'MyView'对象没有属性 'object'

转载 作者:行者123 更新时间:2023-12-04 22:04:06 25 4
gpt4 key购买 nike

我正在尝试使用Django DetailView创建一个对象。我的代码就是这样。

class Detail(DetailView):
model = MyModel
template_name = 'mymodel_detail.html'

def get_context_data(self, **kwargs):
context = super(Detail, self).get_context_data(**kwargs)
context['form'] = DetailForm
return context

def post(self, request, *args, **kwargs):
form = DetailForm(request.POST, request.FILES)
if form.is_valid():
context['reply_form'] = DetailForm
self.object = super(Detail, self).get_object()
context['object'] = super(Detail, self).get_object()

return self.render_to_response(request=request, template=self.get_template_names(), context=context)
else:
context = context = super(Detail, self).get_context_data(**kwargs)
context['reply_form'] = form
self.object = super(Detail, self).get_object()
context['object'] = super(Detail, self).get_object()

return self.render_to_response(request=request, template=self.get_template_names(), context=context)

但是在这里我得到了错误
'Detail' object has no attribute 'object'

我尝试在上下文实例中以及与self一起分配对象。但是什么都行不通。

最佳答案

这里缺少的是,您必须在调用get_context_data()之前将对象分配给类或self。

class Detail(DetailView):
model = MyModel
template_name = 'mymodel_detail.html'

def get_context_data(self, **kwargs):
context = super(Detail, self).get_context_data(**kwargs)
context['form'] = DetailForm
return context

def post(self, request, *args, **kwargs):
form = DetailForm(request.POST, request.FILES)
if form.is_valid():
# Write Your Logic here

self.object = self.get_object()
context = super(Detail, self).get_context_data(**kwargs)
context['form'] = DetailForm
return self.render_to_response(context=context)

else:
self.object = self.get_object()
context = super(Detail, self).get_context_data(**kwargs)
context['form'] = form
return self.render_to_response( context=context)
并在 render_to_response()中传递上下文。没有其他参数。
希望它能为您服务。

关于django - 使用DJango DetailView的发布请求给出错误 'MyView'对象没有属性 'object',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32497740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com