...

/

New Listing View and Template

New Listing View and Template

Learn how to add the code for the view of the Listing page.

Add code for New Listing view

Add the following code in views.py.

Press + to interact
def new_listing(request):
if request.method != 'POST':
form = ListingForm()
else:
form = ListingForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('listings:all_listings')
context = {'form': form}
return render(request, 'listings/new_listing.html', context)

As we are submitting data to be processed, we use a POST request. However, lines 2–3, say that if request.method is not equal to POST, then render an empty form. We write the code this way because, in order to access the form in the first place, users will always request data from the server first. When we access the page where the form is located, we are actually requesting the server to show us that page. That is known as a GET request.

Once the user fills out and submits the empty form, the code in lines 4–8 will run. Let’s break this down even further.

In line 5, we created a variable form that will hold the data being submitted by the user. We used request.POST ...