DjangoQuickstart
Works for    That’s mehttps://www.facebook.com/groups/
What is Django?
Demo: http://
Setting-up development      environment ‣ virtualenv + virtualenvwrapper
Installing virtualenv and      virtualenvwrapper   $ pip install virtualenv        then edit your .profile on osx or .bashr...
Creating your virtual            environment             $ mkvirtualenv pyconph              activating a virtual environm...
Installing Django  $ pip install Django testing your Django installation:$ python>>> import django>>> django.VERSION(1, 4,...
Creating a Django project$ django-admin.py startproject quickstart       Starting Django’s development server:$ cd quickst...
http://localhost:8000
Configuring your Django projectDjango project directory structure: quickstart ├── manage.py └── quickstart     ├── __init__...
Setting-up databasequickstart/settings.py DATABASES = {     default: {         ENGINE: django.db.backends.sqlite3,        ...
Setting-up directoriesquickstart/settings.py import os PROJECT_ROOT = os.path.split(os.path.abspath(     os.path.dirname(_...
Creating directories$ mkdir assets static templates    quickstart    ├── assets    ├── manage.py    ├── quickstart    │   ...
Creating local settings$ vim quickstart/localsettings.py DATABASES = {     default: {         ENGINE: django.db.backends.s...
Creating local settingsquickstart/settings.py DATABASES = {      default: {           ENGINE: django.db.backends.,        ...
Syncing the database$ python manage.py syncdbCreating tables ......Would you like to create one now? (yes/no): yesUsername...
Enabling the Django Adminquickstart/settings.py INSTALLED_APPS = (     ...     django.contrib.admin, )
Enabling the Django Adminquickstart/urls.py from django.conf.urls import patterns, include, url from django.contrib import...
Enabling the Django Admin    $ python manage.py syncdb    visit http://127.0.0.1/
Creating a Django App$ django-admin.py startapp todo     default app structure:      todo      ├── __init__.py      ├── mo...
Installing your appquickstart/settings.py INSTALLED_APPS = (     ...     todo, )
Creating modelstodo/models.py 1 from django.db import models 2 3 class Todo(models.Model): 4 name = models.CharField(max_l...
Exposing models to Django$ vim todo/admin.py from django.contrib import admin from todo.models import Todo class TodoAdmin...
Exposing models to Django
Creating forms$ vim todo/forms.py 1    from django import forms 2    from todo.models import Todo 3 4    class TodoForm(fo...
Creating viewstodo/views.py 1   from django.shortcuts import render_to_response, redirect 2   from django.template import ...
todo/views.py 9 def home(request): 10    todos = Todo.objects.order_by(-created) 11    if request.method == POST: 12      ...
Creating viewstodo/views.py 34 def new_todo(request): 35     if not request.method == POST: 36         return redirect(hom...
Creating templates$ mkdir templates/todo$ touch templates/base.html$ touch templates/todo/home.html
templates/base.html 1    <html> 2    <head> 3       <title>TODO</title> 4       <style type="text/css"> 5            field...
templates/todo/1     {% extends "base.html" %}23     {% block content %}4     <form method="POST" action="{% url new_todo ...
templates/todo/...19 <form method="POST">20     {% csrf_token %}21     <fieldset>22         <legend>Items todo</legend>23 ...
Adding urls:quickstart/urls.py urlpatterns = patterns(,     ...     url(r^$, todo.views.home, name=home),     url(r^todo/,...
Our TODO site:
Thank you :)
Django quickstart
Upcoming SlideShare
Loading in...5
×

Django quickstart

1,361

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,361
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
45
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Django quickstart

    1. 1. DjangoQuickstart
    2. 2. Works for That’s mehttps://www.facebook.com/groups/
    3. 3. What is Django?
    4. 4. Demo: http://
    5. 5. Setting-up development environment ‣ virtualenv + virtualenvwrapper
    6. 6. Installing virtualenv and virtualenvwrapper $ pip install virtualenv then edit your .profile on osx or .bashrc on linux and add the following lines:export WORKON_HOME=~/Envssource /usr/local/bin/virtualenvwrapper.sh reload your .profile or .bashrc files: $ . ~/.profile
    7. 7. Creating your virtual environment $ mkvirtualenv pyconph activating a virtual environment: $ workon pyconph for windows users:‣ https://github.com/davidmarble/virtualenvwrapper-win‣ https://bitbucket.org/guillermooo/virtualenvwrapper-
    8. 8. Installing Django $ pip install Django testing your Django installation:$ python>>> import django>>> django.VERSION(1, 4, 0, final, 0)
    9. 9. Creating a Django project$ django-admin.py startproject quickstart Starting Django’s development server:$ cd quickstart$ python manage.py runserver...Development server is running at http://127.0.0.1:8000/Quit the server with CONTROL-C.
    10. 10. http://localhost:8000
    11. 11. Configuring your Django projectDjango project directory structure: quickstart ├── manage.py └── quickstart ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py
    12. 12. Setting-up databasequickstart/settings.py DATABASES = { default: { ENGINE: django.db.backends.sqlite3, NAME: quickstart.sqlite, USER: , PASSWORD: , HOST: , PORT: , } }
    13. 13. Setting-up directoriesquickstart/settings.py import os PROJECT_ROOT = os.path.split(os.path.abspath( os.path.dirname(__file__)))[0] STATIC_ROOT = os.path.join(PROJECT_ROOT, static) STATIC_URL = /static/ STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, assets), ) ... TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, templates), )
    14. 14. Creating directories$ mkdir assets static templates quickstart ├── assets ├── manage.py ├── quickstart │   ├── __init__.py │   ├── settings.py │   ├── urls.py │   ├── wsgi.py ├── static └── templates
    15. 15. Creating local settings$ vim quickstart/localsettings.py DATABASES = { default: { ENGINE: django.db.backends.sqlite3, NAME: quickstart.sqlite, USER: , PASSWORD: , HOST: , PORT: , } }
    16. 16. Creating local settingsquickstart/settings.py DATABASES = { default: { ENGINE: django.db.backends., NAME: , USER: , PASSWORD: , HOST: , PORT: , } } ... try: from localsettings import * except ImportError: pass
    17. 17. Syncing the database$ python manage.py syncdbCreating tables ......Would you like to create one now? (yes/no): yesUsername (leave blank to use marconi):E-mail address: wombat@gmail.comPassword:Password (again):Superuser created successfully.Installing custom SQL ...Installing indexes ...Installed 0 object(s) from 0 fixture(s)
    18. 18. Enabling the Django Adminquickstart/settings.py INSTALLED_APPS = ( ... django.contrib.admin, )
    19. 19. Enabling the Django Adminquickstart/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns(, url(r^admin/, include(admin.site.urls)), )
    20. 20. Enabling the Django Admin $ python manage.py syncdb visit http://127.0.0.1/
    21. 21. Creating a Django App$ django-admin.py startapp todo default app structure: todo ├── __init__.py ├── models.py ├── tests.py └── views.py
    22. 22. Installing your appquickstart/settings.py INSTALLED_APPS = ( ... todo, )
    23. 23. Creating modelstodo/models.py 1 from django.db import models 2 3 class Todo(models.Model): 4 name = models.CharField(max_length=100) 5 is_done = models.BooleanField(default=False) 6 created = models.DateTimeField(auto_now_add=True) 8 Syncing $ python manage.py syncdb
    24. 24. Exposing models to Django$ vim todo/admin.py from django.contrib import admin from todo.models import Todo class TodoAdmin(admin.ModelAdmin): pass admin.site.register(Todo, TodoAdmin)
    25. 25. Exposing models to Django
    26. 26. Creating forms$ vim todo/forms.py 1 from django import forms 2 from todo.models import Todo 3 4 class TodoForm(forms.ModelForm): 5 class Meta: 6 model = Todo 7 fields = (name,) 8 9 class TodoListForm(forms.Form): 10 def __init__(self, *args, **kwargs): 11 todos = kwargs.pop(todos, []) 12 super(TodoListForm, self).__init__(*args, **kwargs) 13 for todo in todos: 14 field = str(todo.id) 15 self.fields[field] = forms.BooleanField( 16 required=False, label=todo.name) 17 self.fields[field].is_done = todo.is_done 18 19 def clean(self): 20 selected = [tid for tid, val in self.cleaned_data.items() if val] 21 if not selected: 22 raise forms.ValidationError("You need to select one or more items.") 23 return selected
    27. 27. Creating viewstodo/views.py 1 from django.shortcuts import render_to_response, redirect 2 from django.template import RequestContext 3 from django.contrib import messages 4 5 from todo.forms import TodoListForm, TodoForm 6 from todo.models import Todo ...
    28. 28. todo/views.py 9 def home(request): 10 todos = Todo.objects.order_by(-created) 11 if request.method == POST: 12 action = request.POST[action].lower() 13 todo_list_form = TodoListForm(data=request.POST, todos=todos) 14 if todo_list_form.is_valid(): 15 selected = Todo.objects.filter( 16 id__in=todo_list_form.cleaned_data) 17 actions = {done: lambda items: items.update(is_done=True), 18 delete: lambda items: items.delete()} 19 actions.get(action)(selected) 20 messages.add_message(request, messages.SUCCESS, 21 Items has been updated.) 22 else: 23 messages.add_message(request, messages.ERROR, 24 .join(todo_list_form.non_field_errors())) 25 return redirect(home) 26 else: 27 todo_form = TodoForm() 28 todo_list_form = TodoListForm(todos=todos) 29 context = {todo_list_form: todo_list_form, todo_form: todo_form} 30 return render_to_response(todo/home.html, context, 31 RequestContext(request))
    29. 29. Creating viewstodo/views.py 34 def new_todo(request): 35 if not request.method == POST: 36 return redirect(home) 37 todo_form = TodoForm(request.POST) 38 if todo_form.is_valid(): 39 todo_form.save() 40 messages.add_message(request, messages.SUCCESS, 41 Item has been added.) 42 else: 43 messages.add_message(request, messages.ERROR, 44 You need to enter a name.) 45 return redirect(home)
    30. 30. Creating templates$ mkdir templates/todo$ touch templates/base.html$ touch templates/todo/home.html
    31. 31. templates/base.html 1 <html> 2 <head> 3 <title>TODO</title> 4 <style type="text/css"> 5 fieldset { 6 width: 300px; 7 } 8 </style> 9 </head> 10 <body> 11 {% if messages %} 12 <section id="messages"> 13 <ul> 14 {% for message in messages %} 15 <li> 16 {{ message }} 17 </li> 18 {% endfor %} 19 </ul> 20 </section> 21 {% endif %} 22 {% block content %} 23 {% endblock content %} 24 </body> 25 </html>
    32. 32. templates/todo/1 {% extends "base.html" %}23 {% block content %}4 <form method="POST" action="{% url new_todo %}">5 {% csrf_token %}6 <fieldset>7 <legend>Add new todo</legend>8 <div class="field">9 {{ todo_form.name.label_tag }}10 {{ todo_form.name }}11 {% if todo_form.name.errors %}12 {{ todo_form.name.errors }}13 {% endif %}14 </div>15 <input type="submit" name="action" value="Add">16 </fieldset>17 </form>...
    33. 33. templates/todo/...19 <form method="POST">20 {% csrf_token %}21 <fieldset>22 <legend>Items todo</legend>23 {% for field in todo_list_form %}24 <div class="field">25 {{ field }}26 <label for="{{ field.auto_id }}"27 {% if field.field.is_done %}28 style="text-decoration:line-through;"29 {% endif %}>30 {{ field.label }}31 </label>32 </div>33 {% empty %}34 <p>You dont have anymore items todo.</p>35 {% endfor %}36 </fieldset>37 <br />38 <input type="submit" name="action" value="Done">39 <input type="submit" name="action" value="Delete">40 </form>41 {% endblock content %}
    34. 34. Adding urls:quickstart/urls.py urlpatterns = patterns(, ... url(r^$, todo.views.home, name=home), url(r^todo/, include(todo.urls)), )$ vim todo/urls.py from django.conf.urls import patterns, url urlpatterns = patterns(todo.views, url(r^new/$, new_todo, name=new_todo), )
    35. 35. Our TODO site:
    36. 36. Thank you :)
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×