accelerating information technology...

25
Accelerating Information Technology Innovation http://aiti.mit.edu Rwanda Summer 2011 Lecture DJ03 – Components and Views

Upload: dangtuyen

Post on 26-Mar-2018

218 views

Category:

Documents


2 download

TRANSCRIPT

Accelerating Information Technology

Innovation

http://aiti.mit.edu

Rwanda Summer 2011 Lecture DJ03 – Components and Views

Plans •  Today’s Lecture:

– Forms –  Interacting with the Database – Static files

•  This Evening – Work periods for Technical Demo

•  5-7 PM •  8:15-10:00 PM

•  Tomorrow – Work periods for Technical Demo (8 AM – 5 PM) – Business Pitch Practice with Christina (5 – 8 PM)

2

Forms

•  How do we add data to the database – admin interface – command line –  forms (user-submitted)

•  Forms are typically submitted using HTTP POST or GET protocols – Security issues that you must watch out for to

ensure data is not stolen as it is submitted

3

Forms

•  Each request has a POST and GET “dictionary” of parameters that were submitted using POST or GET

4

<form action=“/sms_interface/” method=“POST”>{% csrf_token %} <input type=“text” name=“text_message”> <input type=“text” name=“phone_number”> </form>

key value text_message ‘hello’ phone_number 0784751342

These are values I might type into the form

A new URL: we need a view function to handle the input

blank_text.html

Rendering a Form

•  Django wants to protect you from Cross-Site Request Forgery (CSRF) attacks – Use django.template.RequestContext

objects when rendering templates – Use {% csrf_token %} after your <form>

template tags

5

def blank_text(request): my_requestcontext = RequestContext(request,{}) render_to_response(‘blank_text.html’)

POST data

•  Using the request.POST dictionary, we can access the attributes we want to use…

6

def mirror_response(request): if request.method == “POST”: text_string =request.POST[‘text_mesage’] phone_number = request.POST[‘phone_number’] return HttpResponse(‘%s sent the text message %s’) else: return HttpResponse(“This is not a helpful way to handle non-POST requests”)

Think carefully…POST dictionary values are strings!

Django Form class

•  The Form class can help us out…

7

class TextForm(forms.Form): text_message = forms.CharField() phone_number = forms.CharField()

def sms_handler(request): if request.method == “POST”: text_info = TextForm(request.POST) text_body = str(text_info[‘text_message’].data) phone_number = str(text_info[‘phone_number’].data) return HttpResponse(“%s sent %s” % (phone_number,text_body)) else: my_rc = RequestContext(request,{‘form’:TextForm()} render_to_response(‘blank_window.html’,my_rc)

Django Form Class

8

<html> <form action=“” method=“POST”> {{ form.as_p }} <input type=“submit” value=“Submit!”> </form> </html>

• We can render the form context variable a few different ways • Try looking at the page source to see what HTML django is using behind the scenes in each case…

<li><label for="id_text_message">Text message:</label> <input type="text" name="text_message" id="id_text_message" /></li> <li><label for="id_phone_number">Phone number:</label> <input type="text" name="phone_number" id="id_phone_number" /></li>

Using {{ form.as_ul }}

ModelForm Class

•  A form using django.forms.Form to fill in the information about the Movie class

9

class MovieForm(forms.Form): title = forms.CharField() genre = forms.CharField() rating = forms.IntegerField() # what should we do for lead actor and supporting actors?

We could use models.CharField to specify the actor names

How do we create a Movie instance now and put it in our database?

lead_name = forms.CharField() support_names = forms.CharField()

ModelForm class

•  After the data is posted…

10

def get_movie_data(request): if request.method == “POST”: movie_form = MovieForm(request.POST) my_movie = Movie(title=movie_form.title, rating=movie_form.rating, genre = movie_form.genre) lead_actor = Actor.objects.get(name=movie_form.name) all_support_names = movie.support_names.split(“,”) my_movie.save() for some_name in all_support_names: my_movie.supporting_actors.add(Actor.objects.get(name=some_name)) my_movie.save()

ModelForm Class

•  Advantages of previous approach – Exercise our QuerySet API Skills

•  Disadvantages of previous approach – That was miserable

11

Django almost always has something to make your life a lot easier…

You’ve got to look it up!

ModelForm Class

•  Let’s create a form based on our Movie model.

12

from django.forms import ModelForm from models import Movie

class MovieForm(ModelForm): class Meta: model = Movie

Wow, that was easy.

ModelForm Class

•  One view function for two cases: –  the user has submitted the form –  the user wants to fill out the form

13

def get_movie_data(request): if request.method == “POST”: movie_form = MovieForm(request.POST) my_movie = movie_form.save() return HttpResponse(“The movie %s was successfully entered in the database”) else: my_form = MovieForm() my_rc = RequestContext(request,{‘form’:my_form}) return render_to_response(‘movie_app/movie_form.html’,my_rc)

ModelForm Class

•  Django does a ridiculous amount of HTML work on our behalf

14

ForeignKey and ManyToMany fields: Dropdown and mutiple select menus

Basic CSS in Django

•  A CSS Stylesheet is a static file; it doesn’t change as our database evolves

•  Other kinds of static files: –  Images!

•  Use django.contrib.staticfiles – Each app should have a subdirectory, static/ – Specify other subdirectories for static files in

STATICFILE_DIRS = (“/some/path/to/static”, “/some/other/path/to/static”,)

15

Basic CSS in Django •  Make your stylesheet •  Put it in an accessible static directory

–  some_app/static/some/path –  any/path/in/staticfile_dirs

•  Link to the file using HTML and the static URL tag – <link rel=“stylesheet” href=“{{ STATIC_URL }}/

your_stylesheet_here> •  Always render templates using stylesheets

with RequestContext objects 16

Basic CSS in Django

•  I’m not a CSS Expert…a basic stylesheet for my movie example

17

h1 {background-color: b0c4de; font-family:"Times New Roman", Times, serif; }

body {color: #000000; font-family: verdana;}

a:link {color: #00FF00;}

a:hover {color: #00FFFF;}

a:visited {color: #FF00FF;}

Basic CSS in Django

•  Now, I insert it into the head section of the template…

18

<html> <head> <link rel=“stylesheet” href=“{{ STATIC_URL }}/stylesheets/movie_basic.css”> </head> …more here later

movie_link.html

movie_app/

static/

stylesheets/

images/

Images and Files in Django

•  Two types: –  images/files from the developers- STATIC files

(today…) –  images/files from the users (and in the db!)

•  ImageField: PIL: can manipulate images •  FileField: Allow users to upload any type of

file

19

Images and Files

•  YOUR images…put in the static files directory

•  Use HTML <img> tag to insert an image

20

<img src="{{ STATIC_URL }}/images/movie_reel.jpeg">

Images and Files

•  Put it all together:

21

Please make your website look nicer than this!

Modular Appearances in Django

•  CSS is a framework for styling many HTML pages and elements at once

•  Many times, we want to reuse pieces of templates

•  Template tags –  {% extend “some_template.html” %} –  {% block some_block %} {% endblock %}

22

Modular Appearances in Django

•  Suppose we want at the top of all pages: –  “Zach’s Movie Hub” – A link to the homepage – A link for users to enter new movies

23

<html> <h1> Zach's Movie Hub! </h1> <ul> <li> <a href="{% url movie_app.views.enter_movie_data %}">Enter a new movie</a> <li> <a href="{% url movie_app.views.movie_link %}"> Return to the movie links </a> </ul> {% block content %} {% endblock %} </html>

fill in the blank when we {% extend %} the template

Look at those {% url … % } tags Makes our lives easier!

Modular Appearances in Django •  Rewriting the display_movie.html

template:

24

{% extends "my_base.html" %} {% block content %} <h2> Movie Page </h2> <ul> <li> Title: {{ curr_movie.title }} <li> Lead Actor: {{ curr_movie.lead_actor.name }} <li> Genre: {{ curr_movie.genre }} <li> Rating: {{ curr_movie.rating }} </ul> {% endblock %}

extend the my_base.html template

Modular Appearances in Django

25