将(?P <topic_id> \ d +)中捕获的参数封装为请求对象的属性

时间:2018-05-16 00:45:14

标签: python django design-patterns

urlpatterns Django中向views.py发送get请求和topic_id参数

url(r'^edit_topic/(?P<topic_id>\d+)$', views.edit_topic, name='edit_topic'),

在views.py中传入两个参数

def topic(request, topic_id):
    """Show a single topic and all its entries."""
    topic = Topic.objects.get(id=topic_id)

我想知道topic_id是否可以包含request并将一个参数发送到views.py

def topic(request):
    topic = Topic.objects.get(id=request.topic_id)

代码现在会遇到错误,
但是在Django的工具细节中添加&#39; topic_id&#39;并不困难。请求对象的属性 如果将topic_id打包到请求,会有什么不利之处?

1 个答案:

答案 0 :(得分:1)

可以做到但是urlpatterns需要稍微更改一下。

url(r'^edit_topic/$', views.edit_topic, name='edit_topic'),

创建请求时
<domain_name>/edit_topic?topic_id=<your_id>

例如,请求看起来像

http://127.0.0.1:8000/edit_topic?topic_id=1000

在views.py中,当请求到达时,您可以执行GET操作以获取值

def topic(request):
    topic = Topic.objects.get(id=request.GET('topic_id'))