python - 在基于类的 View 中获得 kwargs 的最佳方法?

标签 python django

我有一个基于类的 Django View :

class LocationView(TemplateView):

我在我的 url 调度程序中定义了一个命名参数:

url(r'^locations/(?P<id>\d+)/$', LocationView.as_view(), name="location")

我知道我可以在 get_context_data 这样的类方法中访问我的 id 参数,我可以在其中将 **kwargs 传递给方法本身。但是,我希望能够仅访问类本身内的参数,因为我从 API 中获取了一些数据,这些数据将在整个类的不同方法中以不同的方式使用。有什么办法可以做到这一点吗?

最佳答案

您可以在为基于类的 View 调用dispatch()之后运行的任何方法中执行self.kwargs

如果您正在为模型创建详细 View ,就像您正在做的那样,您可能应该使用基于通用类的 View 之一来为您执行此操作。

为什么不尝试以下方法:

from django.views.generic import DetailView

class LocationView(DetailView):
  queryset = LocationModel.objects.all()
  template_name = 'location_of_detail_template.html'

然后更新您的 urls.py 文件并将正则表达式组的名称从 id 更改为 pk 以使其自动工作。

关于python - 在基于类的 View 中获得 kwargs 的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20180752/

相关文章:

python - 仅从 CSV 文件中读取选定的列,但保证所有其他列都相同

java - Perl 兼容正则表达式引擎 : how implemented?

python - 我如何知道我使用的是哪个 Python 解释器?

python - CELERY 4.0.2 没有登录文件

python - Django 开发服务器未检测到我的 html 文件中的更改

django - 如何让 Django url dispatcher 使用子域?

python - pidbox 收到方法 enable_events() [reply_to :None ticket:None] in Django-Celery

Python 索引错误 : list index out of range while finding SNPs in vcf

javascript - 尝试在 Django 中构建一个使用 chessboard.js 显示棋盘的网页

python - 在 Python 中存储和检索古吉拉特语字符