[英]URL to work with parameter and without parameter in Django
I am using Django for my project, and I want to render thank-you
page.我正在为我的项目使用 Django,我想呈现
thank-you
页面。 But it should be with or without parameters.但它应该有或没有参数。
urls.py网址.py
urlpatterns = [
....
path(r'thank-you?t=<type>?n=<name>', thank_you_view, name='thank-you'),
....
]
it is working fine for urls like: http://127.0.0.1:8080/thank-you%3Ft=teacher%3Fn=Ajay,%20Gaikwad
Template make use of parameters.它适用于以下网址:
http://127.0.0.1:8080/thank-you%3Ft=teacher%3Fn=Ajay,%20Gaikwad
模板使用参数。
but not working for url without parameters like: http://127.0.0.1:8080/thank-you
Default template will be rendered here.但不适用于没有以下参数的
http://127.0.0.1:8080/thank-you
默认模板将在此处呈现。
also I tried some regex我也尝试了一些正则表达式
path(r'thank-you(?t=<type>?n=<name>|'')', thank_you_view, name='thank-you'),
But it not working. path(r'thank-you(?t=<type>?n=<name>|'')', thank_you_view, name='thank-you'),
但它不起作用。
If you use below view and render context with template then it will work.如果您使用下面的视图并使用模板渲染上下文,那么它将起作用。
views.py视图.py
def thank_you_view(request, *args, **kwargs):
context = {kwargs['type']: kwargs['name']}
return render(request, "light/thank-you.html", context=context)
Edit:编辑:
Once you define path parameters, Django is expecting it in the URL.一旦定义了路径参数,Django 就会在 URL 中得到它。 Else you can get it as query parameters.
否则,您可以将其作为查询参数获取。 You're mixing up query and path parameters.
您正在混淆查询和路径参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.