MDS Lesson 5

Forms

What are they for?

Pass user input to server

  • search queries
  • login
  • add/update records

Processing a form

  1. Enter Data
  2. Submit Data
  3. Validate Data
  4. Act on Data

A Form in HTML


<form method="GET" action="/search/">
    <fieldset>
        <caption> Search </caption>
        <input type="text" name="q">
        <button type="submit">Search</button>
    </fieldset>
</form>

A Login Form


<form method="POST" action="/login/">
    <formset>
        <caption> Log In </caption>
        <input type="text" name="username">
        <input type="password" name="password">
        <button type="submit">Log In</button>
    </formset>
</form>

GET versus POST ?

GET

POST

  • Data show in URL
  • Idempotent
  • Cachable
  • Data sent in body
  • Changes state of server
  • Not cahable

Django Forms

  • Declarative - document fields
  • Validation
  • HTML generation

The Login Form


from django import forms

class LoginForm(forms.Form):
    username = forms.TextField()
    password = forms.PasswordField()

The Form View


from .forms import SearchForm

def login(request):
    if request.method == 'POST':

        form = SearchForm(request.POST)
        if form.valid():
            ...
            return redirect(request.user)
    else:
        form = SearchForm()

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

What about Validation?

  • Field
  • Custom per field
  • Custom per form

MDS: Forms

By Curtis Maloney

MDS: Forms

  • 737