Skip to content

Latest commit

 

History

History
85 lines (54 loc) · 2.19 KB

read401-28.md

File metadata and controls

85 lines (54 loc) · 2.19 KB

Django CRUD and Forms

Working with forms

HTML forms

In HTML, a form is a collection of elements inside <form>...</form> that allow a visitor to do things like enter text, select options, manipulate objects or controls, and so on, and then send that information back to the server.

GET and POST

GET and POST are the only HTTP methods to use when dealing with forms.

Django handles three distinct parts of the work involved in forms:

  • preparing and restructuring data to make it ready for rendering
  • creating HTML forms for the data
  • receiving and processing submitted forms and data from the client

Building a form in your template(HTML)

<form action="/your-name/" method="post">
    <label for="your_name">Your name: </label>
    <input id="your_name" type="text" name="your_name" value="{{ current_name }}">
    <input type="submit" value="OK">
</form>

Building a form class in form model in Django

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

handle the form in view model:

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import NameForm

def get_name(request):
    # if this is a POST request we need to process the form data

    if request.method == 'POST':

        # create a form instance and populate it with data from the request:
        
        form = NameForm(request.POST)
        
        # check whether it's valid:
        
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
           
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    
    else:
        form = NameForm()

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

now we will go to our template and modify it to be like:

<form action="/your-name/" method="post">
    
         {{ form }} 
    <input type="submit" value="Submit">
</form>

Now our form is created successfuly

More information visit Django Documentation web site