I am struggling with something that should be routine for me by now but I have a mental block. I have a model that stores Country names and a slug version of the name.
Eg. "United States", "united-states"
I want to display the country names in a template for selection, then return the selected country's slug value to the Class based View which will then obtain the data. The list of countries can be links or dropdown - whatever. But I need to obtain the selected value in the View. Here is a simplified version:
Template
{% extends 'base.html' %}
{% block content %}
<form method="POST">
{% for country in object_list %}
<a href="{{country.slug_name}}">{{ country.pretty_name }}</a></br>
{% endfor %}
</form>
{% endblock content %}
View
class CountryView(TemplateView):
country_name = THE SLUG
country_obj = Country(country_name)
country_obj.build_country_dictionary()
country_obj.display()
So I think I need one of the get methods to access this but I cannot work it out. Thanks for any help.
CodePudding user response:
The "structured way"
Have a look at FormView
, where you define your form class (which you also need to create, depends on your situation can be a model form as well). The rest is pretty much handled by the view.
https://ccbv.co.uk/projects/Django/4.0/django.views.generic.edit/FormView/
PSEUDO code
class MyForm(ModelForm):
model = YourModel
class MyFormView(FormView):
form_class = MyForm
# depends on what you want to do, you can overwrite form_valid to do your logic
The quickest way
PSEUDO code
{% extends 'base.html' %}
{% block content %}
<form method="POST">
{% csrf_token %}
<select name="selection">
{% for country in object_list %}
<option value="{{ country.slug_name }}">{{ country.pretty_name }}</option>
{% endfor %}
</select>
<input type="submit">Submit</input>
</form>
{% endblock content %}
class CountryView(TemplateView):
def post(self, request, *args, **kwargs):
selection = request.POST.get('selection')