Reez0
Reez0

Reputation: 2689

Passing parameter to view to populate form

It works fine when I specify exactly what the data has to be by doing this

form = forms.MakeSale(instance=Laptop.objects.get(Name="NameOfTheLaptop"))

But as soon as I try and pass the value to view and query the model, I get the following error:

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%}

Upvotes: 1

Views: 44

Answers (1)

Reez0
Reez0

Reputation: 2689

Thanks for trying to help. After looking around on SO for days, I found a similar question where someone said I should include another path
path('sale/', views.laptop_sale, name = "sale")
in addition to my existing
path('sale/<str:laptopname>', views.laptop_sale, name = "sale") which seems to have solved the problem. Again, thanks for trying to help.

Upvotes: 1

Related Questions