Friday, December 14, 2012

Chapter 7 Forms



Getting Data From the Request Object

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")


Attribute/methodDescriptionExample
request.pathThe full path, not including the domain but including the leading slash."/hello/"
request.get_host()The host (i.e., the “domain,” in common parlance)."127.0.0.1:8000" or"www.example.com"
request.get_full_path()The path, plus a query string (if available)."/hello/?print=true"
request.is_secure()True if the request was made via HTTPS. Otherwise,False.True or False

request.META 




  • HTTP_REFERER
     – The referring URL, if any. (Note the misspelling of REFERER.) <Referer os a common misspelling of the word referrer. so common, in fact. that it made it into the official specification of HTTP>
  • HTTP_USER_AGENT – The user’s browser’s user-agent string, if any. This looks something like:"Mozilla/5.0 (X11; U; Linux i686; fr-FR; rv:1.8.1.17) Gecko/20080829 Firefox/2.0.0.17".
  • REMOTE_ADDR – The IP address of the client, e.g., "12.345.67.89". (If the request has passed through any proxies, then this might be a comma-separated list of IP addresses, e.g., "12.345.67.89,23.456.78.90".)


  • def ua_display_good1(request):
        try:
            ua = request.META['HTTP_USER_AGENT']
        except KeyError:
            ua = 'unknown'
        return HttpResponse("Your browser is %s" % ua)

    request.GET and request.POST [diction-like object]

    Simple web search

    from django.http import HttpResponse
    from django.shortcuts import render_to_response
    from mysite.books.models import Book
    
    def search(request):
        if 'q' in request.GET and request.GET['q']:
            q = request.GET['q']
            books = Book.objects.filter(title__icontains=q)
            return render_to_response('search_results.html',
                {'books': books, 'query': q})
        else:
            return HttpResponse('Please submit a search term.')

    More Elegant Solution: One Layer less
    (no more def search_from(request):
                         return render_to_response('search_form.html')
    no more ('r^search_form/$', views.search_form)

    (r'^search/$', views.search)

    def search(request):
        errors = []
        if 'q' in request.GET:
            q = request.GET['q']
            if not q:
                errors.append('Enter a search term.')
            elif len(q) > 20:
                errors.append('Please enter at most 20 characters.')
            else:
                books = Book.objects.filter(title__icontains=q)
                return render_to_response('search_results.html',
                    {'books': books, 'query': q})
        return render_to_response('search_form.html',
            {'errors': errors})


    <form action="" method="get">


    <html>
    <head>
        <title>Search</title>
    </head>
    <body>
        {% if errors %}
            <ul>
                {% for error in errors %}
                <li>{{ error }}</li>
                {% endfor %}
            </ul>
        {% endif %}
        <form action="/search/" method="get">
            <input type="text" name="q">
            <input type="submit" value="Search">
        </form>
    </body>
    </html>

    CONTACT FORM

    from django.core.mail import send_mail
    from django.http import HttpResponseRedirect
    from django.shortcuts import render_to_response
    
    def contact(request):
        errors = []
        if request.method == 'POST':
            if not request.POST.get('subject', ''):
                errors.append('Enter a subject.')
            if not request.POST.get('message', ''):
                errors.append('Enter a message.')
            if request.POST.get('email') and '@' not in request.POST['email']:
                errors.append('Enter a valid e-mail address.')
            if not errors:
                send_mail(
                    request.POST['subject'],
                    request.POST['message'],
                    request.POST.get('email', 'noreply@example.com'),
                    ['siteowner@example.com'],
                )
                return HttpResponseRedirect('/contact/thanks/')
        return render_to_response('contact_form.html',
            {'errors': errors})

    HttpResponseRedirect  
    If the user is redirected to another page after the POST, then there’s no chance of repeating the request.


    FROM CLASS

    from django import forms
    
    class ContactForm(forms.Form):
        subject = forms.CharField()
        email = forms.EmailField(required=False)
        message = forms.CharField()


    >>> from contact.forms import ContactForm
    >>> f = ContactForm()
    >>> print f
    <tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" id="id_subject" /></td></tr>
    <tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr>
    <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="


    >>> print f.as_ul()
    <li><label for="id_subject">Subject:</label> <input type="text" name="subject" id="id_subject" /></li>
    <li><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></li>
    <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
    >>> print f.as_p()
    <p><label for="id_subject">Subject:</label> <input type="text" name="subject" id="id_subject" /></p>
    <p><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></p>
    <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
    
    Most elegant solution

    # views.py
    
    from django.shortcuts import render_to_response
    from mysite.contact.forms import ContactForm
    
    def contact(request):
        if request.method == 'POST':
            form = ContactForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                send_mail(
                    cd['subject'],
                    cd['message'],
                    cd.get('email', 'noreply@example.com'),
                    ['siteowner@example.com'],
                )
                return HttpResponseRedirect('/contact/thanks/')
        else:
            form = ContactForm()
        return render_to_response('contact_form.html', {'form': form})
    
    # contact_form.html
    
    <html>
    <head>
        <title>Contact us</title>
    </head>
    <body>
        <h1>Contact us</h1>
    
        {% if form.errors %}
            <p style="color: red;">
                Please correct the error{{ form.errors|pluralize }} below. #cannot have space around | 
            </p>
        {% endif %}
    
        <form action="" method="post">
            <table>
                {{ form.as_table }}
            </table>
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>

    --------------------------------------------------------------------------s
    403 Forbidden
    CSRF verification failed. Request aborted.
    More information is available with DEBUG=True.
    -------------------------------------------------------------------------
    in the views.py
    from django.template import RequestContext
    return render_to_response('contact_form.html', {'form': form}, context_instance=RequestContext(request))

    in the template html: <form action="" method="post">{% csrf_token %}


    CSS and Django <<< access the attribute in form one by one instead of form.as_table
    <html>
    <head>
        <title>Contact us</title>
    </head>
    <body>
        <h1>Contact us</h1>
    
        {% if form.errors %}
            <p style="color: red;">
                Please correct the error{{ form.errors|pluralize }} below.
            </p>
        {% endif %}
    
        <form action="" method="post">
            <div class="field">
                {{ form.subject.errors }}
                <label for="id_subject">Subject:</label>
                {{ form.subject }}
            </div>
            <div class="field">
                {{ form.email.errors }}
                <label for="id_email">Your e-mail address:</label>
                {{ form.email }}
            </div>
            <div class="field">
                {{ form.message.errors }}
                <label for="id_message">Message:</label>
                {{ form.message }}
            </div>
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>
    {{ form.message.errors }} displays a <ul class="errorlist"> if errors are present and a blank string if the field is valid (or the form is unbound). We can also treat form.message.errors as a Boolean or even iterate over it as a list. For example:
    <div class="field{% if form.message.errors %} errors{% endif %}">
        {% if form.message.errors %}
            <ul>
            {% for error in form.message.errors %}
                <li><strong>{{ error }}</strong></li>
            {% endfor %}
            </ul>
        {% endif %}
        <label for="id_message">Message:</label>
        {{ form.message }}
    </div>
    In the case of validation errors, this will add an “errors” class to the containing <div> and display the list of errors in an unordered list.





    done

    No comments:

    Post a Comment