如何解决在 Django UpdateView 中覆盖 get() 方法给出“str”没有属性获取错误
我有一个 Stats 模型,它与带有 OneToOne 字段的 Django 用户模型相关。 我有一个更新视图:
/ Assign handlers immediately after making the request,// and remember the jqxhr object for this request
var jqxhr = $.post( "example.php",function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});
它工作正常,但任何用户都可以修改与任何用户相关的统计数据,我希望用户只更新与他相关的统计数据。 所以我像这样覆盖了 StatsUpdateView 中的 get() 方法:
class StatsUpdateView(UpdateView):
model = Stats
fields = ('stat1','stat2','stat3')
代码运行良好,直到 else 语句,“用户匹配”被打印到控制台中,但在运行服务器时出现此错误: 'str' 对象没有属性 'get'
这是路径:
def get(self,*args,**kwargs):
if self.request.user != Stats.objects.get(pk=kwargs['pk']).user: #checks if the user logged in is the same user related to the Stats with the onetoone field. Works fine.
return redirect('homepage:home')
else: # if the user match,he can access the update view for his own stats
print('user match')
return reverse('user:updatestats',kwargs={'pk': kwargs['pk']})
编辑完整的回溯:
path('updatestats/<int:pk>/',StatisticheUpdateView.as_view(),name='updatestats')
解决方法
试试这个
使用HttpResponseRedirect
from django.http import HttpResponseRedirect
return HttpResponseRedirect(reverse('user:updatestats',kwargs={'pk': kwargs['pk']}))
https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpResponseRedirect
,为什么不使用这样的函数视图:
def update_stats(request,pk):
stats= get_object_or_404(Stats,pk=pk)
if request.user == stats.user:
form = StatsForm(request.POST or None) # just make a form as you need
if form.is_valid():
stats.stat1= form.cleaned_data.get('stat1')
# etc
stats.save()
return redirect('/yoururl')
context = {'form': form}
return render(request,'update.html',context) # render your template
else:
return redirect('homepage:home')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。