Django中的动态重定向

2024-06-28 19:18:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从一个动态页面动态重定向到另一个页面。想象一下,在一个IMDB电影页面(动态)上,然后点击到编剧/导演/演员页面(动态)的链接

以下是URL:

   urlpatterns = [
    path('', views.index, name="index"),
    path('writer/<int:id>', views.writer, name="writer"),
    path('title/<int:id>', views.title, name="title"),
    path('creator/', views.creator, name="creator"),
]

这是index.html:

{% for pilots in pilot %}
    <div>
        <p>Title: <a href="title/{{ pilots.id }}">{{ pilots.title }}</a></p>
        {% for writers in pilots.creators.all %}
            <p>Writer: <a href="writer/{{ writers.id }}">{{ writers.writer }}</a></p>
        {% endfor %}
        
    </div>
{% endfor %}

这是title.html(动态ahref不工作):

{% for title in titles %}
        <p>{{title.title}}</p>
        <p>{{title.count}}</p>
        <p>{{title.year}}</p>
        <p>{{title.description}}</p>
        {% for creators in title.creators.all %}
            <a href="creator/">{{creators.writer}}</a>
        {% endfor %}
{% endfor %}

这是views.py:

def title(request, id):
    titles = Pilot.objects.filter(id=id)
    context = {
        'titles': titles,
    }
    return render(request, 'title.html', context)

def creator(request):
    return redirect(f'writer/{id}')

Tags: pathnameinidfortitle动态页面
1条回答
网友
1楼 · 发布于 2024-06-28 19:18:53

我想这就是你需要的:remove hardcode in django

您的代码可能会更改为

{% for title in titles %}
        <p>{{title.title}}</p>
        <p>{{title.count}}</p>
        <p>{{title.year}}</p>
        <p>{{title.description}}</p>
        {% for creators in title.creators.all %}
            <a href="{% url 'writer' creators.writer.id %}">{{creators.writer}}</a>
        {% endfor %}
{% endfor %}

此外,您还可以创建一个namespace(当使用多个应用程序时)。请参阅文档中的更多信息。:)

相关问题 更多 >