Later in this hour, we will discuss how to use the URLconf file to control how Django displays information. You need to understand the basics of Django's HttpRequest and HttpResponse classes. These two classes are simple to use. They allow you to quickly create dynamic code that helps you manage data that gets passed from the web browser through your view code and back out to the web browser.
The HttpRequest object is actually passed into your view function by Django. You use this view to gather and process information about the request in the view function. When you are finished handling the request, the view function is required to return an HttpResponse object.
The HttpRequest object is a Python class that contains metadata about an HTTP request. The HttpRequest object is passed as the first argument to the view function that is called when the view is activated by a web browser. When you define a view in a views.py file, you must specify a name for the HttpRequest object, just as you did when you edited the people/views.py file in Hour 2, "Creating Your First Website":
def index(request):
When the index function is initiated, you can use the request object to acquire the metadata about the request. The following are some of the most common HttpRequest object attributes you will likely use:
path contains a string representation of the path of the HTTP request.
method contains a string representation of the HTTP method, typically GET or POST.
GET contains a Python dictionary-like object that contains the HTTP GET parameters.
POST contains a Python dictionary-like object that contains the HTTP POST parameters.
By the Way
The POST attribute does not contain the file information if the POST request contains a file upload. See the description of the FILES attribute.
REQUEST contains a Python dictionary-like object that searches POST first and then GET to find all parameters.
Watch Out!
Although this feature is provided in Django, it is much better to use the method attribute to determine if the request is a GET or POST and then use the GET and POST attributes accordingly:
if request.method == "GET": name = request.GET["name"] elif request.method == "POST": name = request.POST["name"]
FILES contains a Python dictionary-like object that includes any files that are uploaded using an HTTP POST request.
By the Way
Each value in the FILES attribute is a dictionary object that contains three keys named filename, content-type, and content.
META contains a Python dictionary that includes all available headers in the HTTP request, such as CONTENT_TYPE, REMOTE_ADDRESS, and HTTP_HOST.
user contains a Django User object for the currently logged-in user.
Did you Know?
You can tell if the request comes from an authenticated user by using the is_authenticated() method of the User object:
if request.user.is_authenticated(): #Handle authenticated users else: #Handle anonymous users
Did you Know?
You can tell if the request comes from a secured connection by using the is_secure() method of the HttpRequest object:
if request.is_secure(): #Handle secure users else: #Handle unsecured users
The HttpResponse class in Django's http package allows you to generate a web page as a response to an HTTP request directly from your Python code. Unlike the HttpRequest object, which is created automatically by Django and passed into the view function, you must create your own HttpResponse object. The simplest way to create an HttpResponse object is to import the class from the django.http package using the following code snippet:
from django.http import HttpResponse
There are several ways to build an HTTP response using the HttpResponse object. The simplest method is to create an HTML string and pass it as an argument to the HttpResponse object, as shown in the following code snippet, to generate a web page similar to the one shown in Figure 4.1.
def view_index(request): colors = ("BLUE","RED","GREEN") html = "<HTML><BODY>\n" html += "<H1>Colors Index</H1><HR>\n" for c in colors: html += "<FONT COLOR=%s><LI>%s</LI></FONT>\n" % (c, c) html += "</HTML></BODY>" return HttpResponse(html)
You can also treat an HttpResponse object like a file. First, create an HttpResponse object, and then use the write() function to write the HTML code to the object. When you are through writing to the HttpResponse object, use it as a return value for the view function. The following code snippet shows how to use an HttpResponse object as a file to generate the web page shown in Figure 4.2:
def view_calendar(request): week week_days = ('Sunday','Monday','Tuesday',\ 'Wednesday','Thursday','Friday',\ 'Saturday') weeks = 5 response = HttpResponse() response.write("<HTML><BODY>\n") response.write("Calendar<HR>\n") response.write("<TABLE BORDER=1><TR>\n") for d in week_days: response.write("<TD>%s</TD>\n" % d) response.write("</TR>\n") for w in range(1,weeks): response.write("<TR>\n") for d in week_days: response.write("<TD> </TD>\n") response.write("</TR>\n") response.write("</BODY></HTML>") return response
You can also add and change the HTTP response headers by treating the HttpResponse object like a Python dictionary. The following code snippet sets the mimetype of the HTTP response:
def view index(request): response = HttpResponse("<HTML><BODY>Index</BODY></HTML>") response['mimetype'] = "text/plain" return response
Did you Know?
You do not need to check for the key before deleting the header. Using the Python del function to delete a header from the HttpResponse object, as shown here, does not raise an exception if the key you specify doesn't exist:
del response['mimetype']