A
A
Andross782020-05-17 00:40:19
Django
Andross78, 2020-05-17 00:40:19

How to change background-color via POST to server?

Job to change background-color via POST to server

spoiler
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}))

The exception I get is: Reverse for 'colors' with keyword arguments '{'form': 'red'}' not found. 1 pattern(s) tried: ['exercises\\/set_color\\/$']

What did I do wrong in this line "return redirect(reverse(success_url, kwargs={'form': back_color}))" ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Sobolev, 2020-05-17
@Sobolev5

Please show the root file urls.py
Well, in general, I note that your code is meaningless, since the color is not saved anywhere.
If the task was to change the background color by reference, then this can be done without using your design.

<a href="?background_color=red">Поставить красный цвет</a>
<body {% if request.GET.background_color %}style="background-color:{{ request.GET.background_color }}{% endif %}">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question