0

There is a Django form. When I send a GET-request, I output a new empty form, when I click "Submit", I display on the page what the user entered in the questionnaire. The problem is that I want some data to be output not as an internal representation, but as an full one (idk how it called correctly). I'm a beginner in Django and may not understand many nuances.

I tried to add data to the dictionary individually, but it didn't lead to anything.

pool.html:

<p><b>Ваше имя:</b> {{ form_data.name }}</p>
<p><b>Ваш пол:</b> {{ form_data.get_sex_display }}</p>

forms.py:

class FeedbackForm(forms.Form):
    SEX_OPTIONS = (
        ('m', 'Мужской'),
        ('f', 'Женский'),
        ('none', 'Паркетный')
    ...
    sex = forms.ChoiceField(
        widget=forms.RadioSelect,
        choices=SEX_OPTIONS,
        label='Ваш пол:'
    )

views.py:

def pool(request):
    assert isinstance(request, HttpRequest)
    context['title'] = 'Обратная связь'

    if request.method == 'GET':
        form = FeedbackForm()
    else:
        form = FeedbackForm(request.POST)
        if form.is_valid():
            form_data = request.POST.dict()
            context['form_data'] = form_data

    context['form'] = form
    return render(request, 'app/pool.html', context=context)

1 Answers1

0

Please correct me if I am wrong:

  1. The user posts a feedback via FeedbackForm
  2. You want to display the feedback.

Right now you are not saving anyting. You just want to show on the "next" site what was entered on the last site?

Your mistake is that you assign request.POST.dict() to context['form_data']. Therefore you are assigning the raw post data, which is a dicitonary, to the context 'form_data'. Surely this dictionary does not have the method get_sex_display.

You want to deal with your form! Your form deals with the form fields already populated with the POST-data. I really recommend you to read about form.cleaned_data. This is a dictionary that is created after form validation; so you can access it after form.is_valid().

First option:

# views.py
        if form.is_valid():
            form_data = form.cleaned_data
            context['form_data'] = form_data

# template
{{ form_data.get_sex_display }}

Second option:

# views.py
        if form.is_valid():
            form_data = form.cleaned_data
            context['sex'] = form.cleaned_data["sex"]

# template
{{ sex }}

Let me know if this works out for you.

Tarquinius
  • 1,468
  • 1
  • 3
  • 18