【问题标题】:django: redirecting back to a multimodel view after passing required variablesdjango:传递所需变量后重定向回多模型视图
【发布时间】:2023-03-07 02:30:01
【问题描述】:

我收到错误消息:

没有找到带有参数“({'flotation_id':'21','sample_id':'28780488'},)'的'botanyoverview'的反向。尝试了 1 种模式:['botany/botanyoverview/flotation/(?P[0-9]+)/sample/(?P[0-9]+)$']

两个 id 都存在,通常这是 urls.py 中的一个问题,但我似乎无法发现它。

我有几个表格/模型,它们显示在一个 html 视图中,您单击一个并转到编辑页面,我正在尝试修复重定向,因此它会将您返回到开始的概述页面,这个需要浮选和样品 ID。该 url 最初有效,但在编辑后尝试重定向回原始页面时抛出此错误。我看不到错误,有什么想法吗?

views.py

def editplantpart(request, pk, fk='', sp='', fl=''):
        post = get_object_or_404(PlantPart, pk=pk)
        if request.method == "POST":
            form = PlantPartForm(request.POST, instance=post)
            if form.is_valid():
                post = form.save(commit=False)
                sample_id=sp
                flotation_id=fl
                post.save()
                return redirect('botanyoverview', {  'flotation_id': flotation_id, 'sample_id':sample_id,})

        else:
            form = PlantPartForm(instance=post)
        return render(request, 'plantpart/create_plantpart.html', {'form': form})

urls.py

re_path('flotation/(?P<fl>\d+)/sample/(?P<sp>\d+)/fraction/(?P<fk>\d+)/plantpart/edit/(?P<pk>\d+)/edit/', views.editplantpart, name='editplantpart'),

html

<tr class='clickable-row' data-href="{% url 'editplantpart' fk=plantpart.fraction_id pk=plantpart.plantpart_id fl=flotation.flotation_id sp=flotation.sample_id  %}">

@@@ 编辑

植物学概览网址

path('botanyoverview/flotation/<int:flotation_id>/sample/<int:sample_id>', views.botanyoverview, name='botanyoverview'),

【问题讨论】:

  • 显示botanyoverview的网址。
  • 上面添加的url

标签: django redirect


【解决方案1】:

您应该调用redirect,方法是传递视图名称和可选的一些位置或关键字(在您的情况下)参数; URL 将使用reverse() 方法进行反向解析:

redirect('botanyoverview', flotation_id=flotation_id, sample_id=sample_id)

以下是一些重定向示例:

https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/#examples

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 2015-05-23
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多