我可以在 Django 模板标签中引发 Http404 吗?

发布于 2024-09-07 19:07:15 字数 157 浏览 2 评论 0原文

我有一个 Django 应用程序,它提供模板标签 profile。该标签接受用户名作为其参数。当不存在具有给定用户名的 User 实例时,我应该如何处理这种情况?在模板标签内引发 HTTP 404 有意义吗?或者我应该简单地将一个空字典传递给模板?

I have a Django application that provides template tag profile. The tag accepts a username as its argument. How should I treat the situation when there exists no User instance with the given username? Does it make sense to raise HTTP 404 inside a template tag? Or should I simply pass an empty dictionary to the template?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我们只是彼此的过ke 2024-09-14 19:07:15

我认为不可能从模板中引发 404,如果可以的话,您也不应该这样做。您应该将逻辑和表示分开。

你有两种声音的可能性。

  • 不要使用模板标记渲染任何内容(静默失败)
  • 引发模板错误。

您没有确切说明您的模板标记在做什么,所以我不能推荐这两者中的任何一个,但使用模板标记最正常的事情就是默默地失败。

I don't think it's possible to raise a 404 from the template, and you shouldn't do it if you could. You should keep the logic and presentation separate.

You have two sound possibilities.

  • Don't render anything with your template tag (fail silently)
  • Raise a template error.

You don't say exactly what your template tag is doing, so I can't recommend any of the two, but the most normal thing to do with a template tag, is to fail silently.

如梦 2024-09-14 19:07:15

如果页面是特定于用户的,您应该在呈现该页面之前让用户访问 @login_required,以便您知道该用户存在。

否则,按照惯例,您应该在模板标记中默默地失败。

If the page is User specific, you should get the user to @login_required before rendering that page, so that you know that the user exists.

Otherwise, by convention, you should just fail silently in the template tags.

旧话新听 2024-09-14 19:07:15

您应该做的是在显示 profile 标记之前检查模板中是否存在 user 变量。

What you should do is check within your template if the user variable exists before displaying the profile tag.

机场等船 2024-09-14 19:07:15

我可以看到两种方法:

使用 if 语句和 javascript 代码进行重定向,例如

{% if profile_not_exist %}
   Javascript with redirect
{% else %}
   Generic code
{% endif %}

或者在视图中定义逻辑(更好的方法),例如

def index(request):
   if(profile_not_exist):
      indexTemplate = loader.get_template('404.html')
   else:
      indexTemplate = loader.get_template('index.html')

I can see two ways:

Use if statement with javascript code to redirect, like

{% if profile_not_exist %}
   Javascript with redirect
{% else %}
   Generic code
{% endif %}

Or define logic in view( better way ), like

def index(request):
   if(profile_not_exist):
      indexTemplate = loader.get_template('404.html')
   else:
      indexTemplate = loader.get_template('index.html')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文