I am creating a web app and the home page is where the user selects their location. The view for the home page template queries my database for a list of locations and populates a drop down list. After the user hits submit, I validate the form data, and if they picked a valid city (ie. it exists in my database), I want to redirect them to another page that displays deals of the day for that city. My question is based on basic view/form design in Django. How can I pass the city onto the next page? Basically I want to do the following:
Home Page -> submit form -> call method to validate form -> form redirects user to another page
Do I have to create a separate validate view/page for validation? Forms take an action parameter, so I'm guessing I would have to set the action to /validate/, which would call my validate_form() method (through the urls.py file), which would then redirect them to the appropriate page.
I just wanted to run my thoughts by someone before I went ahead and implemented it. Thanks for your time.
Why do you want to validate the city? Just redirect to the city and if the city does not exist then the 404 page will be shown.
your template
<form action="{% url 'choose_city' %}" method="POST">
<select name="city">
{% for city in cities %}
<option value="{{ city.id }}">{{ city.name }}</option>
{% endfor %}
</select>
<button>Show deals</button>
</form>
urls.py
url(r'^choose/$', views.choose_city, name='choose_city'),
url(r'^deals/(?P<city_id>\d+)/$', views.deals_by_city, name='deals_by_city'),
views.py
from django.shortcuts import get_object_or_404, redirect, render
def choose_city(request):
return redirect('deals_by_city', city_id=request.POST['city'])
def deals_by_city(request, city_id):
city = get_object_or_404(City, pk=city_id)
deals = Deal.objects.filter(city=city)
return render(request, 'deals_by_city.html', {'city': city,
'deals': deals})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With