Editing items in the PostgreSQL DB#

The pattern now is as before.

Add the URL#

Adding the url to the page into the app urls.py

path('edit_listing/<edit_id>/', views.edit_listing, name='edit_listing')

Create the view#

Create the edit view in views.py. Here the contents of a form are being altered.

def edit_listing(request, edit_id):
    listing = Listings.objects.get(id=edit_id)

    if request.method != 'POST':
        form = ListingForm(instance=listing)
    else:
        form = ListingForm(request.POST, request.FILES, instance=listing)
        if form.is_valid():
            form.save()
            return redirect('listings:all_listings')

    context = {'listing': listing, 'form': form}
    return render(request, 'listings/edit_listing.html', context)

Create Template .html file#

The key aspects here are:

<form action="{% url 'listings:edit_listing' listing.id %}" method='post' enctype="multipart/form-data">
    <div class="form-group">
        {% csrf_token %}
        {{ form.as_p }}
    </div>
    <button type="submit" class="btn">Edit listing</button>
</form>

Wire up the Edit Button#

There is now a functioning Edit listing page. It just needs to be wired up to the edit button on the my_listings page.