何时使用Django get_absolute_url()方法? [英] When to use Django get_absolute_url() method?

查看:54
本文介绍了何时使用Django get_absolute_url()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django文档说:

Django documentation says:


get_absolute_url()方法告诉Django如何

get_absolute_url() method to tell Django how to calculate the canonical URL for an object.

在这种情况下,规范URL是什么意思?

What is canonical URL mean in this is context?

从SEO角度来看,规范的URL意味着从外观相似的URL( example.com example.com/index.html )。

I know from an SEO perspective that canonical URL means picking the best URL from the similar looking URLs (example.com , example.com/index.html). But this meaning doesn't fit in this context.

我知道此方法在Django admin,重定向等中提供了一些附加功能。而且我完全知道如何使用这种方法。

I know this method provides some additional functionality in Django admin, redirection etc. And I am fully aware of how to use this method.

但是背后的原理是什么?我从未在项目中实际使用过它。

But what is the philosophy behind it? I have never actually used it in my projects. Does it serve any special purpose?

推荐答案

首先,在进行Web开发时,您真的想避免使用硬编码路径在您的模板中。这样做的原因是路径可能会更改,浏览所有HTML和模板来查找每个URL或路径并手动进行更新将很麻烦。

First of all, when it comes to web development you really want to avoid hard coding paths in your templates. The reason for this is that paths might change, and it will be a hassle to go through all your HTML and templates to find every single URL or path and update it manually. It makes your code much harder to maintain.

对此的解决方案是定义返回URL的函数。这是 get_absolute_url()进入图片的地方。

The solution to this is to define functions that return the URL instead. This is where get_absolute_url() comes into the picture.

示例:

<!-- Bad -->
<a href="/language/category/product/{{product.pk}}">Link</a>

<!-- Good -->
<a href="{{product.get_absolute_url}}">Link</a>



规范网址



第二个问题是什么是规范网址。规范URL是指向特定页面的官方 URL。有时,资产可以显示在多个不同的URL中,例如:

Canonical URL

Your second question is what a canonical URL is. A canonical URL is "the official" url to a certain page. Sometimes an asset can be displayed in multiple different URL's, for example:

/en/shoes/1-nike-shoes/
/en/shoes/1-nike-shoes?sort=price&order=asc
/en/shoes/1-nike-shoes?sort=price&order=desc

此处,我们在3个不同的URL中显示了相同的资产。 规范URL将是我们定义为主要的URL。例如。 / zh-CN / shoes / 1-nike-shoes /

Here we have the same asset displayed in 3 different URL's. The "Canonical URL" would be the one we defined as the main one. E.g. /en/shoes/1-nike-shoes/.

定义官员或某个资产的主要 URL。

Its very useful to define what a official or "main" URL to a certain asset is. It will allow you to prevent duplicate content when search engines index your website.

在Django文档中使用的引用语境中,它将使您防止重复的内容。在这种情况下,规范是指显示此模型的官方URL。

In the context of the quote you are using from the Django Documentation. "Canonical" in this case means "the official URL where this model is displayed".

这篇关于何时使用Django get_absolute_url()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆