django从视图中设置模板URL

时间:2018-04-24 12:29:35

标签: django

是否可以从Django中的视图设置模板URL?

即。我有一个带有取消按钮的表单,我想在多个视图上使用该表单,但取消URL将根据表单的使用情况而有所不同。

视图:

<intent-filter android:label="filter_react_native">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
         <data android:scheme="myschemeapp" android:host="addHost" />

    </intent-filter>

模板:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['app'] = 'sites'
    context['view'] = 'site_list'
    context['cancel_id'] = 'this may or may not be set'
    return context

1 个答案:

答案 0 :(得分:2)

您只需使用reverse在视图侧评估网址并将其传递给模板:

在视图中:

from django.urls import reverse

context['cancel_url'] = reverse('app:view', args=[cancel_id])
return context
模板中的

<a href="{{ cancel_url }}" class="btn btn-primary">Cancel</a>
相关问题