You can create new listings, see the details of the listings, but you can’t edit or delete a listing. Let’s take care of the editing part in this chapter.
Edit Listing URL
Open urls.py and add the following code.
In a similar way to the detail view, we need to include the ID of the listing in the URL, so that we can edit the correct listing.
Edit Listing View
Since we are dealing with changing a form, the edit listing view will be different from the detail view. Open views.py and add the following code.
The main difference between the new listing view and the edit view is that we are not creating but rather editing an existing listing.
listing = Listings.objects.get(id=detail_id)
First, we get the specific listing we are trying to edit. After we do this, then the process is very similar to the new listing view. Refer to chapter 5 for an explanation of how forms work.
form = ListingForm(instance=listing)
If the request is not a POST request, we generate a form, but this time the fields will be already filled with the existing information for that particular listing. This is achieved by setting instance=listing which gets a particular instance from the database.
form = ListingForm(request.POST, request.FILES, instance=listing)
We want to edit an existence model instance in the database, we use instance=listing, so that we overwrite that particular instance in the database when submitting the form again.
Edit Listing Template
Create a template called edit_listing.html in the templates folder. Open this template and add the following code.
form action="% url 'listings:edit_listing' listing.id %" method='post' enctype="multipart/form-data"
The action method changed since we are in a different template now and we also included listing.id which is needed to edit the correct listing when submitting the form.
My Listings Template Revisited
Open my_listings.html and activate the edit button.
a class="btn" href="% url 'listings:edit_listing' my_listing.id %"">Edit/a
We activated the edit button by adding the path to the edit page and passed the ID of the particular listing we want to edit.
Run the server, go to my listings page, and edit some listings to test the form. After you submit the form, the listings should reflect the changes being made.
If you're enjoying the series and want to support, you can find the entire book below.
Top comments (0)