我正在尝试添加一项功能,限制用户在一个minuate中发布多个。然后我遇到了这个错误,不知道为什么这不起作用。能否请你看看我的错是什么?
class PostCreateView(CreateView):
model = Post
form_class = PostForm
template_name = 'main/add_post.html'
def form_valid(self,form):
if not hasattr(self.request.session['last_submitted']):
last_submitted = pickle.dumps(datetime.datetime.now())
self.request.session['last_submitted'] = last_submitted
save_it = True
else:
last_submitted = pickle.loads(self.request.session['last_submitted'])
delta = datetime.datetime.now() - last_submitted
save_it = (delta.seconds > 60) # assume allow re-submit after 60 seconds
if save_it:
self.object = form.save(commit=False)
# any manual settings go here
#self.object.category = Category.objects.filter(category__in=categories).all()
self.object.moderator = self.request.user
self.object.image = extract(self.object.url)
self.object.thumbnail = extractt(self.object.content)
self.object.save()
return HttpResponseRedirect(reverse('post', args=[self.object.slug]))
else:
# consider redirect as usual, if the user just clicked twice by mistake
return self.form_invalid(form) # or Http error code
Traceback:
File "env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "env/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
249. return super(BaseCreateView, self).post(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
215. return self.form_valid(form)
File "ebagu/main/views.py" in form_valid
160. if not hasattr(self.request.session['last_submitted']):
File "env/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in __getitem__
48. return self._session[key]
Exception Type: KeyError at /add_post/
Exception Value: 'last_submitted'
答案 0 :(得分:1)
这看起来:
if not hasattr(self.request.session['last_submitted']):
hasattr
接受两个参数,并告诉您对象是否具有特定的属性名称:
hasattr(...)
hasattr(object, name) -> bool
Return whether the object has an attribute with the given name.
(This is done by calling getattr(object, name) and catching exceptions.)
您的意思是使用以下内容吗?
if 'last_submitted' not in self.request.session:
答案 1 :(得分:0)
我从您发布的信息中可以告诉您,views.py
中的第160行正在触发错误:
if not hasattr(self.request.session['last_submitted']):
您的追踪会抱怨KeyError。它基本上告诉你self.request.session
中不存在索引'last_submitted'。
此错误的触发基本上是因为您的代码正在尝试从session
内不存在的对象中检索值。