David J Nevin+= Code

Published: Sep 15, 2022

Django Edit Items

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

100
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.

100
101
102
103
104
105
106
107
108
109
110
111
112
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:

100
101
102
103
104
105
106
<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.


Next: Django Delete Items
Previous: Django Individual Item Page