N
N
normandeccc2017-04-06 01:34:51
Django
normandeccc, 2017-04-06 01:34:51

What is the most correct way to handle the simplest form data in Django?

Hello.
For educational purposes, I set myself the following task:
Create a page where the user enters his name in a form field, after which he goes to a page where he is greeted by name. That is, the user enters the name "Vasya" and sees the greeting "Hello, Vasya" on another page. In the draft,
the problem is solved in the following way:
There is a Put_your_name view that accepts the user's name.

def Put_your_name(request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/Hello_user/')
    else:
        form = NameForm()

    return render(request, 'Put_your_name.html', {'form': form})

This view is almost a complete copy of the example from the Django documentation
The Django Form class:
class NameForm(forms.Form):
    your_name = forms.CharField(label='Введите свое имя:', max_length=20)

There is another Hello_user view that displays the entered data.
def Hello_user(request):
    name_of_user = request.POST['your_name']
    return render(request, 'Hello_user.html', {'form_name': name_of_user})

The code for the form itself on the Put_your_name.html page is as follows:
<form action="/Hello_user/" method="POST">
{% csrf_token %}
{{form}}
 <p><input type="submit" value="Привет" /></p>
 </form>

The hello code on the Hello_user.html page is as follows: Urls:
<h1>Привет, {{form_name}}</h1>
urlpatterns = [
    url ('^name/$', Put_your_name),
    url ('^Hello_user/$', Hello_user),
]

The question is:
Is everything done right? It seems to me that I missed something, or did not fully understand the purpose and capabilities of the forms.
In the Put_your_name view, I just check that the form is filled in correctly and that's it. The data is not sent anywhere. Is it possible to pass data from the Put_your_name view to Hello_user and not take it from request.POST['your_name']?
I would like to know the shortest and most correct solution.
Thanks in advance for your replies and your attention.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Mindlin, 2017-04-06
@kgbplus

In this case, you should not use POST, but GET

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question