传递参数以查看以填充表单

时间:2018-04-09 15:26:07

标签: python django

当我通过执行此操作

准确指定数据时,它可以正常工作
form = forms.MakeSale(instance=Laptop.objects.get(Name="NameOfTheLaptop"))

但是一旦我尝试传递值来查看和查询模型,我就会收到以下错误:

Reverse for 'sale' with no arguments not found. 1 pattern(s) tried: ['sale\\/(?P<laptopname>[^/]+)$'] 

views.py

def laptop_sale(request, laptopname):
    form = forms.MakeSale(instance=Laptop.objects.get(Name=laptopname))
    if request.method == 'POST':
        form = forms.MakeSale(request.POST, request.FILES)
        if form.is_valid():
            readyinstance = form.save(commit=False)
            readyinstance.added_by = request.user
            readyinstance.save()
        else:
            return render(request, 'laptops/laptop_sale.html', {'form': form})
    return render(request, 'laptops/laptop_sale.html', {'form': form})

urls.py

path('sale/<str:laptopname>', views.laptop_sale, name = "sale")

details.html

    {%for detail in details%}
<div class="container">
    <div class="row">
        <div class="span12">
            <table class="table table-condensed table-hover">
                <thead>
                    <tr>
                        <th>Laptop #{{detail.id}}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Name:</td>
                        <td>{{detail.Name}}</td>
                    </tr>
                    <tr>
                        <td>Specification:</td>
                        <td>{{detail.specification}}</td>
                    </tr>
                    <tr>
                        <td>Warranty:</td>
                        <td>{{detail.warranty}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
<a class="btn btn-success" href="{%url 'laptops:sale' laptopname=detail.Name%}" > This laptop has been sold »</a>
{%endfor%}

1 个答案:

答案 0 :(得分:1)

感谢您的帮助。经过几天的搜索,我发现了一个类似的问题,有人说我应该包括另一条道路 path('sale/', views.laptop_sale, name = "sale")除了我现有的path('sale/<str:laptopname>', views.laptop_sale, name = "sale")之外,它似乎已经解决了这个问题。再次感谢您的帮助。