[英]How to add parameters to urls in Django?
I have a view that filters the field called "defaultfieldname" in a certain object_list. 我有一个视图,过滤在某个object_list中名为“defaultfieldname”的字段。 What I want to do is to adapt it to pass the name of the field as as parameter in urls.py, so I could use different urls for different fields. 我想要做的是调整它以传递字段的名称作为urls.py中的参数,所以我可以为不同的字段使用不同的URL。
I am not sure which way would be easier: 我不确定哪种方式会更容易:
url(r'^calendar/birthday/$', login_required(MonthCalends.as_view(model=Person)), name='bday_list', filter_field="birthdate"),
url(r'^calendar/deathday/$', login_required(MonthCalends.as_view(model=Person)), name='dday_list', filter_field="deathdate"),
or 要么
url(r'^calendar/birthday/$', login_required(MonthCalends.as_view(model=Person, filter_field="birthdate")), name='bday_list'),
url(r'^calendar/deathday/$', login_required(MonthCalends.as_view(model=Person, filter_field="deathdate")), name='dday_list'),
Then I have a view: 然后我有一个观点:
class MonthCalends(ListView):
template_name='month_list.html'
## Sets default fieldname value
filter_field = "defaultfieldname"
...rest of code
The param in urls.py should overwrite the "defaultfieldname" on the view, but I don't know how to get the filter_field from the urls.py in the view. urls.py中的param应覆盖视图中的“defaultfieldname”,但我不知道如何从视图中的urls.py获取filter_field。 Any help? 有帮助吗?
Thanks! 谢谢!
The arguments you send with as_view
are set on the MonthCalends object. 使用as_view
发送的参数在MonthCalends对象上设置。 That means filter_field
is available as self.filter_field
. 这意味着filter_field
可用作self.filter_field
。 Assuming you have defined the get
method you could do as follows: 假设您已经定义了get
方法,您可以执行以下操作:
class MonthCalends(ListView):
template_name='month_list.html'
## Sets default fieldname value
filter_field = "defaultfieldname"
def get(self, request, *args, **kwargs):
try:
# if the filter field was sent as an argument
filter_field = self.filter_field
except:
# else revert to default
filter_field = MonthCalends.filter_field
# ...rest of code
For a more full explanation check the Django class based views documentation . 有关更完整的说明,请查看基于Django类的视图文档 。
You may just use one url, that triggers the second part of your url: 您可以只使用一个网址,触发网址的第二部分:
url(r'^calendar/(\w+)$', login_required(MonthCalends.as_view(model=Person)), name='bday_list'),
Then you may access it using self.args[0]
然后你可以使用self.args[0]
访问它
And in case you just permit two different types for filter_field
, you may just raise an exception later in the class that you have read self.args[0]
. 如果你只为filter_field
允许两种不同的类型,你可能只是在你读过self.args[0]
的类中稍后引发异常。
Of course, you may use more readable syntax in the regex like: 当然,您可以在正则表达式中使用更易读的语法,如:
r'^calendar/(?P<type>\w+)$'
In this case you can access it using self.kwargs['type']
. 在这种情况下,您可以使用self.kwargs['type']
访问它。
Anyway, using regex groups seems much neater. 无论如何,使用正则表达式组似乎更整洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.