Url:
path('set_color/', SetColorView.as_view(), name='colors'),
Form:
COLORS = (
('black', 'black'),
('white', 'white'),
('red', 'red'),
('yellow', 'yellow'),
('blue', 'blue'), )
class SetColorForm(forms.Form):
background_color = forms.ChoiceField(choices=COLORS, widget=forms.widgets.RadioSelect)
Template:
{% extends 'base.html' %}
{% block content %}
<form action="" method="post" style="background-color:{{
form.field.value|default:'powderblue'}}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Set"/>
</form>
{% endblock %}
View:
class SetColorView(View):
form_class = SetColorForm
template_name = 'exercises/colors.html'
def get(self, request):
form = self.form_class
context = {
'form': form,
}
return render(request, self.template_name, context)
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
success_url = 'exercises:colors'
if form.is_valid():
back_color = form.cleaned_data['background_color']
return redirect(reverse(success_url, kwargs={'form': back_color}))