I have made a ChoiceField
into a select and submit button and wondered if this is the correct approach.
forms.py
class PortfolioForm(forms.Form):
def __init__(self, *args, **kwargs):
super(PortfolioForm, self).__init__(*args, **kwargs)
portfolios = [('pf 1', 'pf 1'), ('pf 2', 'pf 2'), ('pf 3', 'pf 3')]
self.fields['portfolios'] = forms.ChoiceField(
widget=forms.Select(),
choices=portfolios,
required=False,
)
views.py
class PortfolioView(View):
form_class = PortfolioForm
template_name = 'portfolio.html'
def get(self, request):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(self.request.POST)
if form.is_valid():
selected_portfolio = form.cleaned_data.get('portfolios')
print(selected_portfolio)
form = self.form_class(initial={'portfolios': selected_portfolio})
else:
form = self.form_class(initial={'portfolio_name': ''})
return render(self.request, self.template_name, {'form': form})
and most of the trickery in the template. I use elements of form.portfolios
to make the buttons, but it seems I have to include form.portfolios
in the template to make it all work. In order not to show I put this in a hidden tag.
{% block content %}
<form id="id_portfolio" method="post">
{% csrf_token %}
<a style="visibility: hidden">{{ form.portfolios }}</a>
{% for portfolio in form.portfolios %}
<p>
{% if portfolio.data.selected %}
<button type="button">{{ portfolio.choice_label }}</button>
{% else %}
<button type="submit" value="{{ portfolio.data.value }}"
name="{{ portfolio.data.name }}">{{ portfolio.choice_label }}</button>
{% endif %}
</p>
{% endfor %}
{% endblock content %}
{{ form }}
? \$\endgroup\${{ form.portfolios }}
gives me a dropdown list. I want the buttons to be visible at all time. \$\endgroup\$Select
widget and replace theselect.html
template with a template that renders buttons instead of a dropdown select \$\endgroup\$