简体   繁体   English

URL 在 Django 中使用参数和不使用参数

[英]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:编辑:

  • Is it any way to use regex in url so it will work for both ways?有没有办法在 url 中使用正则表达式,所以它适用于两种方式?
  • Or can we make parameters as optional?或者我们可以将参数设为可选?

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.

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