About me

Friday, May 18, 2018

python django chap 8

Friends this is the continuation from its previous post so i kindly recommend you to read that post i have made this very simple even a complete beginner can learn it and if you are beginner in python then you need to learn python i have made that blog also for that click this link


CREATING FORMS

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.


Some of these form interface elements - text input or checkboxes - are fairly simple and are built into HTML itself. Others are much more complex; an interface that pops up a date picker or allows you to move a slider or manipulate controls will typically use JavaScript and CSS as well as HTML form <input /> elements to achieve these effects.you can learn more on forms in the link here
Django handles three distinct parts of works involves in the form
  • 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
The main benefit of django is that Django can take care of it all for you.if you want you can code it all manually
the django has a form class .It is much as the same way that a Django model describes the logical structure of an object, its behavior, and the way its parts are represented to us, a Form class describes a form and determines how it works and appears.
In a similar way that a model class’s fields map to database fields, a form class’s fields map to HTML form  <input /> elements. (A ModelForm maps a model class’s fields to HTML form  <input/>elements via a Form; this is what the Django admin is based upon.) A form’s fields are themselves classes; they manage form data and perform validation when a form is submitted. A DateField and a FileField handle very different kinds of data and have to do different things with it. A form field is represented to a user in the browser as an HTML “widget” - a piece of user interface machinery. Each field type has an appropriate default Widget class, but these can be overridden as required.

<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>


This tells the browser to return the form data to the URL /your-name/, using the POST method. It will display a text field, labeled “Your name:”, and a button marked “OK”. If the template context contains a current_name variable, that will be used to pre-fill the your_name field.
now we need to build a view which renders the template containing the HTML form, and that can supply the current_name field as appropriate and when the form is submitted the post request contains the form data to be submitted now we will create our form in the myproj/form.py it is as

from django import forms

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

this defines a form class with single field your_name.with label is also given if  which will appear in the <label> when its rendered .The fields maximum allowable length is is defined in the max_length and the The whole form, when rendered for the first time, will look like:

<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" maxlength="100" required />

Form data sent back to a Django website is processed by a view, generally the same view which published the form. This allows us to reuse some of the same logic.to handle it we need to instantiate it in the view for the URL where we want it to be published .

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})
if we arrive at this view with a get request it will create an empty form instance and place it in the template context to be rendered. This is what we can expect to happen the first time we visit the URL

If the form is submitted using a POST request, the view will once again create a form instance and populate it with data from the request: form = NameForm(request.POST) This is called “binding data to the form” (it is now a bound form). .
A Form instance has an is_valid() method, which runs validation routines for all its fields. When this method is called, if all fields contain valid data, it will return true and place in its cleaned_data attribute we can use this data to update the database or do other processing before sending an HTTP redirect to the browser telling it where to go next. if its not true we will go back to the template with the form This time the form is no longer empty (unbound) so the HTML form will be populated with the data previously submitted, where it can be edited and corrected as required.
now we can create our html template which is as :

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

As we learned earlier all the form fields will be unpacked in the html template in the{{form}} with the feature of Django Template Language 
thats all for creating forms in django 


to be continued in the next post.....................

THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF YOU WANT TO GET LATEST POSTS ON THIS PLEASE FOLLOW BY EMAIL ID AND FEEL FREE TO ASK YOUR DOUBTS AND DON'T FORGET TO SHARE,COMMENT AND FOLLOW 

No comments:

Post a Comment