如何确保每次调用-Django视图时代码都运行
关于Django泛型视图,如何让函数在每次调用视图时运行? 例如,当我这样做时:如何确保每次调用-Django视图时代码都运行,django,Django,关于Django泛型视图,如何让函数在每次调用视图时运行? 例如,当我这样做时: class infoRequestPage(CreateView): model = InfoRequest form_class = moreInfoForm template_name = 'info_request.html' success_url = reverse_lazy('HomePageView') pageVisit = InfoRequest(
class infoRequestPage(CreateView):
model = InfoRequest
form_class = moreInfoForm
template_name = 'info_request.html'
success_url = reverse_lazy('HomePageView')
pageVisit = InfoRequest(
infoName = autoName,
infoRegion= autoRegion,)
pageVisit.save()
print("test")
它将按预期返回test
,但仅在我第一次加载页面时返回。但是,如果我更新源代码并将print命令更改为其他命令,如“testing”
,它将再次运行。但和上次一样,只有在第一次加载页面时。
我试图清除缓存,并重新启动浏览器,但都没有做任何事情。在代码更改之前,它似乎只运行一次 在“开始”时执行此操作
def get(self, *args, **kwargs):
print("test")
return super().get(*args, **kwargs)
邮递
def post(self, *args, **kwargs):
print("test")
return super().post(*args, **kwargs)
您可以覆盖以下选项:
你想达到什么目的?有多种方法,但它们都围绕django请求生命周期展开。当用户访问我的页面时,我想在我的数据库中存储一些值,如他们来自的地区、访问的时间等。所以我想我会在视图中这样做。在测试期间,它似乎只运行一次,即使我刷新了页面,所以我想我只是想了解它是如何工作的,以及为什么它只运行一次。它只运行一次,因为它是类实例化的一部分,与调用它的人或内容无关。你需要研究一下中间件或者视图中调用了什么函数,对GDPR的研究也会有用的。谢谢@willem Van Onsem,这也行得通。与
def dispatch
相比,使用上面提供的@HenryM的def get
是否发现任何问题?@mattGdispatch
在每次调用视图时都会被调用get
仅对HTTP get调用,post
仅对HTTP post调用。def post
中存在复制粘贴错误-应为super()。post(*args,**kwargs)
class infoRequestPage(CreateView):
model = InfoRequest
form_class = moreInfoForm
template_name = 'info_request.html'
success_url = reverse_lazy('HomePageView')
pageVisit = InfoRequest(
infoName = autoName,
infoRegion= autoRegion,)
pageVisit.save()
def dispatch(self, request, *args, **kwargs):
print('test')
super().dispatch(request, *args, **kwargs)
class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
"""
Log out the user and display the 'You are logged out' message.
"""
next_page = None
redirect_field_name = REDIRECT_FIELD_NAME
template_name = 'registration/logged_out.html'
extra_context = None
@method_decorator(never_cache)
def dispatch(self, request, *args, **kwargs):
auth_logout(request)
next_page = self.get_next_page()
if next_page:
# Redirect to this page until the session has been cleared.
return HttpResponseRedirect(next_page)
return super().dispatch(request, *args, **kwargs)
# ...