[英]Get url kwargs in class based views
I need to retrieve the value of the pk written in the url in my class based view:我需要在基于类的视图中检索写在 url 中的 pk 的值:
path('<int:pk>/data/', views.DataView.as_view(), name='data'),
However, what I saw everywhere was the pk retrieved in the definition of methods like get
or post
.但是,我到处看到的是在
get
或post
等方法的定义中检索到的 pk。
What I want is to be able to use it to define my class variables, because I need to do get the same value from this pk in every method inside my class, like below:我想要的是能够使用它来定义我的类变量,因为我需要在我的类中的每个方法中从这个 pk 中获取相同的值,如下所示:
class DataView(ContextMixin, UpdateView):
pk = get_pk_from_url
...
value = ...
def get(self, request, *args, **kwargs):
value = self.value
# Do something with value
def post(self, request, *args, **kwargs):
value = self.value
# Do something with value
I got an idea while writing this question, which is to define a method that will do what I need, then calling this method in my other methods.我在写这个问题的时候有个想法,就是定义一个方法来做我需要的,然后在我的其他方法中调用这个方法。
class DataView(ContextMixin, UpdateView):
def get_value(self):
self.pk = self.kwargs['script_id']
...
self.value = ...
def get(self, request, *args, **kwargs):
self.get_value()
value = self.value
# Do something with value
def post(self, request, *args, **kwargs):
self.get_value()
value = self.value
# Do something with value
However, I don't know if there's another way, which is why I still wanna ask my question.但是,我不知道是否还有其他方法,这就是为什么我仍然想问我的问题。
Thanks to @WillemVanOnsem's comment, I was able to use the setup
method (doc here ) in order to define everything I needed to define.感谢@WillemVanOnsem 的评论,我能够使用
setup
方法( 此处的文档)来定义我需要定义的所有内容。 So in the end I get something like that :所以最后我得到了类似的东西:
class DataView(View):
def setup(self, request, *args, **kwargs):
self.pk = kwargs['pk']
...
self.value = ...
return super().setup(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
value = self.value
def post(self, request, *args, **kwargs):
value = self.value
The setup
method being called before the get
and post
ones, the class attributes declared in it can then be used in the other methods. setup
方法在get
和post
之前被调用,在其中声明的类属性可以在其他方法中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.