First form

Django has a form system to replace traditional HTML's form
Before making a form for a application, you need to create a forms.py first.

~$ cd Opensource/opensource_XX
~/Opensource/opensource_XX$ vim forms.py

And put following code into it.

# forms.py
from django import forms

That's all!


Example for a Login form.

This is a bunch of HTML code for a basic login form.

<form>
    <label>Account</label>
    <input type="text" id="account" name="account" class="form-control" placeholder="Account" required/>
    <label>Password</label>
    <input type="password" id="password" name="password" class="form-control" placeholder="Password" required/>
</form>

The form has two field which is TextField and PasswordField.
every time when you design a form, you have to analysis it field structure, and go to django's official form field document and seek a proper field.

This is the website: https://docs.djangoproject.com/en/1.11/ref/forms/fields/

In this case. We only need CharField.
Which is for reflect HTML's <input> label.

Also, by using <input> label's type element, we can control it's display form like normal text, or a password character (*).

When editing forms.py, you do like this:

from django import forms

class login(forms.Form):
# form's name to class's name, and extends forms.Form object

    account = forms.CharField(
        # This is one of your field name
        label='Account',
        # <label>'s content with field.
        required=True,
        # one of the element we must assign to make it required.
        widget=forms.TextInput(attrs=
        {
            # this dictionary can let you assign any other element that might not be support by django.
            'id': 'account', # in case you have any other name way.
            'class': 'form-control', # Im more prefer a Bootstrap rendering
            'placeholder': 'Account', # Add more hint is always good.
            'type': 'text' # This is the most important part.
        })
    )
    password = forms.CharField(
        label='Password',
        required=True,
        widget=forms.TextInput(attrs=
        {
            'id': 'password',
            'class': 'form-control',
            'placeholder': 'Password',
            'type': 'password' # DO NOT FORGET !!!!!!
        })
    )

and this is all about creating your first form.

But still, not using it!.


Usage in views.py

Every form is a variable in forms.py
Before use it in views.py, make sure you have already import it.

from opensource_XX import forms

After this, you can call any form variable in views.py to render in tempalte.

For example:

views.py

from opensource_XX import forms

def login(request):
    login_form = forms.login()
    return render(request, 'opensource_XX/templates/login.html', locals())

login.html

<html>
<body>
<form method="POST">
  {{ login_form.as_p }}
  <input type="submit" value="Submit"/>
</form>
</body>
</html>

After put variable into template html file.
Remember put submit button inside form like:

<input type="submit" value="Submit"/>
<input type="clear" value="Clear"/>

Also, the method you submit a form effect the way how django view function process the form result.

<form method="POST">
or
<form method="GET">

Verify a form's data

You can get a request method by calling:

request.method

It will return a string like 'GET' or 'POST'

Put it into a if statement for a further process, like:

if request.method == 'GET':
    return render(...)
elif request.method == 'POST':
    # process form data.
    return render(...)

While you want to process a form, you might get some value from a form.
Once you make sure this request contains a form and it's definition in forms.py.

if request.method == 'POST':
    form = forms.login(request.POST)

By using the following method, you can easily get value in specific field in a form.

form.cleaned_data['filed_name']

For example:

Getting account field value:
login_form.cleaned_data['account']

Getting password field value:
login_form.cleaned_data['password']

Finally, you can verify datas

def login(request):
    try:
        if request.method == "POST":
            login_form = forms.login(request.POST)
            if login_form.is_valid():
                account = login_form.cleaned_data['account']
                password = login_form.cleaned_data['password']
                if account == 'B10517031' and password == 'password':
                    return HttpResponse('login success')
                else:
                    return HttpResponse('login failed.')
        else:
            login_form = forms.login()
        return render(...)
    except:
        error_report = traceback.format_exc()
        return redner(...)

Other stuff you might interesting.

If you are using some specil filed like GerneralIPAddressField in django.
You can simplly use:

form.is_valid()

It can help you to check some element like "required=True" or IP format ... so on.

results matching ""

    No results matching ""