通过URL传递对象数据

kja*_*nal 2 django django-urls

我知道我可以通过URL模式传递对象值,并在视图函数中使用它们.例如:

(r'^edit/(?P<id>\w+)/', edit_entry),
Run Code Online (Sandbox Code Playgroud)

可以像:

def edit_entry(request, id):
        if request.method == 'POST':
                a=Entry.objects.get(pk=id)
                form = EntryForm(request.POST, instance=a)
                if form.is_valid():
                        form.save()
                        return HttpResponseRedirect('/contact/display/%s/' % id)
        else:
                a=Entry.objects.get(pk=id)
                form = EntryForm(instance=a)
        return render_to_response('edit_contact.html', {'form': form})
Run Code Online (Sandbox Code Playgroud)

但是如何从URL中的模型字段("id"除外)传递值?例如,我有一个抽象的基本模型,其字段为"job_number",由子模型"OrderForm"和"SpecReport"共享.我想点击订单上的"job_number",并为同一个工作号码调用规格报告.我可以创建一个

href="/../specifications/{{ record.job_number }}
Run Code Online (Sandbox Code Playgroud)

将信息传递给url,但我已经知道这个正则表达式语法不正确:

(r'^specifications/(?P<**job_number**>\w+)/', display_specs),
Run Code Online (Sandbox Code Playgroud)

我也不能像在id中那样捕获视图中的job_number:

def display_specs(request, job_number):
    records = SpecReport.objects.filter(pk=job_number)
    tpl = 'display.html'
    return render_to_response(tpl, {'records': records })
Run Code Online (Sandbox Code Playgroud)

有一个简单的方法,还是比我认为的更复杂?

修改后的代码如下:

(r'^specdisplay/?agencyID=12/', display_specs),
Run Code Online (Sandbox Code Playgroud)

和:

def display_specs(request, agencyID):
    agencyID= request.GET.get('agencyID')
    records = ProductionSpecs.objects.filter(pk=id)
    tpl = 'display_specs.html'
    return render_to_response(tpl, {'records': records })
Run Code Online (Sandbox Code Playgroud)

不知道如何过滤.pk不再适用.

Van*_*ale 6

是的,你让它变得有点复杂.

在您的urls.py您有:

(r'^edit/(?P<id>\w+)/', edit_entry),
Run Code Online (Sandbox Code Playgroud)

现在您只需要为display_specs添加几乎相同的表达式:

(r'^specifications/(?P<job_number>\w+)/', display_specs),
Run Code Online (Sandbox Code Playgroud)

正则表达式中的括号标识一个组,并(?P<name>...)定义一个将被命名的命名组name.此名称是视图的参数.

因此,您的视图现在看起来像:

def display_specs(request, job_number):
   ...
Run Code Online (Sandbox Code Playgroud)

最后,即使这会起作用,当您重定向到视图时,而不是使用:

HttpResponseRedirect('/path/to/view/%s/' % job_number)
Run Code Online (Sandbox Code Playgroud)

使用更多:

HttpResponseRedirect(
    reverse('display_specs', kwargs={'job_number': a.job_number}))
Run Code Online (Sandbox Code Playgroud)

现在,如果您决定更改资源路径,则重定向不会中断.

为此,您需要在urlconf中开始使用命名url,如下所示:

url(r'^specifications/(?P<job_number>\w+)/', display_specs, name='display_specs'),
Run Code Online (Sandbox Code Playgroud)