简体   繁体   English

如何在 Django 模板中生成绝对网址?

[英]How do I generate absolute urls in Django template?

I'm having trouble generating the absolute url for a Django model.我在为 Django 模型生成绝对 url 时遇到问题。 In "courses.html" template I iterate through two models, category and course , but am only able to generate the relative url <slug> rather than the full url /courses/<slug> from each object.在“courses.html”模板中,我遍历了两个模型, categorycourse ,但我只能从每个对象生成相对 url <slug>而不是完整的 url /courses/<slug>

Is there any way to generate an absolute url for each object?有没有办法为每个对象生成一个绝对 url?

main views.py主视图.py

def courses(request):
    return render(request=request,
                  template_name="main/courses.html",
                  context={'courses': Course.objects.all,
                           'categories': Category.objects.all},
                  )

courses.html课程.html


{% extends "main/header.html" %}
{% block content %}

{% for category in categories %}
    <a href="{{ category.slug }}"/>
      <p>{{ category }}</p>
    </a>
{% endfor %}

{% for course in courses %}
    <a href="{{ course.slug }}"/>
      <p>{{ course }}</p>
    </a>
{% endfor %}

Problem问题

Get absolute url for a model object that correlates with a url.获取与 url 相关的模型对象的绝对 url。

Solution解决方案

A common idiosyncrasy in django is to define get_absolute_url on the model and use reverse to build the url with context from the model. django 中的一个常见特性是在模型上定义get_absolute_url并使用 reverse 使用来自模型的上下文构建 url。 Keeping business logic contextual to the model in the model simplifies maintenance and automated testing.将业务逻辑与模型中的模型保持关联可简化维护和自动化测试。 This pattern is used throughout the Django framework (ie: https://github.com/django/django/blob/555e3a848e7ac13580371c7eafbc89195fee6ea9/tests/contenttypes_tests/models.py#L16-L20 ).此模式在整个 Django 框架中使用(即: https : //github.com/django/django/blob/555e3a848e7ac13580371c7eafbc89195fee6ea9/tests/contenttypes_tests/models.py#L16-L20 )。

Example例子

urls.py网址.py

...
    path('<int:course_id>/', views.CourseDetail.as_view(), name='course_detail'),
    path('<int:category_id>/', views.CategoryDetail.as_view(), name='category_detail'),
...

models.py模型.py

class Course(models.Model):
    def get_absolute_url(self):
        return reverse('course_detail', kwargs={ "id": str(self.id] })

class Category(models.Model):
    def get_absolute_url(self):
        return reverse('category_detail', kwargs={ "id": str(self.id] })

courses.html课程.html

{% extends "main/header.html" %}
{% block content %}

{% for category in categories %}
    <a href="{{ category.get_absolute_url }}"/>
      <p>{{ category }}</p>
    </a>
{% endfor %}

{% for course in courses %}
    <a href="{{ course.get_absolute_url }}"/>
      <p>{{ course }}</p>
    </a>
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM