Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to Django

Introduction to Django

Bruno Renié

April 03, 2012
Tweet

More Decks by Bruno Renié

Other Decks in Programming

Transcript

  1. $ django-admin.py startproject webmardi webmardi/ ├── manage.py └── webmardi ├──

    __init__.py ├── settings.py ├── urls.py └── wsgi.py
  2. from django.db import models from ..users.models import User class Cheese(models.Model):

    name = models.CharField(max_length=255) image = models.ImageField(upload_to='cheese') description = models.TextField() class Taste(models.Model): cheese = models.ForeignKey(Cheese, related_name='tastes') user = models.ForeignKey(User) like = models.BooleanField(default=True) class Meta: unique_together = ('cheese', 'user')
  3. from django.contrib import admin from .models import Cheese, Taste class

    CheeseAdmin(admin.ModelAdmin): list_display = ('name', 'image') class TasteAdmin(admin.ModelAdmin): list_display = ('cheese', 'user', 'like') admin.site.register(Cheese, CheeseAdmin) admin.site.register(Taste, TasteAdmin)
  4. from django.template.response import TemplateResponse from .models import Cheese, Taste def

    cheese_list(request): context = { 'cheeses': Cheese.objects.all(), } return TemplateResponse(request, 'cheese_list.html', context)
  5. from django.conf.urls import patterns, url from . import views urlpatterns

    = patterns('', url(r'^$', views.cheese_list, name='cheese_list'), url(r'^cheese/(?P<pk>\d+)/$', views.cheese_detail, name='cheese_detail'), url(r'^cheese/(?P<pk>\d+)/like/$', views.like_cheese, name='like_cheese'), url(r'^cheese/(?P<pk>\d+)/dislike/$', views.dislike_cheese, name='dislike_cheese'), url(r'^cheese/add/$', views.add_cheese, name='add_cheese'), )
  6. <!-- base.html --> <html> <head> <title>{% block title %}{% endblock

    %}</title> </head> <body> {% block content %}{% endblock %} </body> </html>
  7. <!-- cheese_list.html --> {% extends "base.html" %} {% load thumbnail

    markup %} {% block title %}Cheese types{% endblock %} {% block content %} {% for cheese in cheeses %} <h2>{{ cheese.name }}</h2> <img src="{% thumbnail cheese.image 300x300 crop %}"> {{ cheese.description|markdown }} {% endfor %} {% endblock %}
  8. from django.core.urlresolvers import reverse from django.test import TestCase class CheeseTest(TestCase):

    def test_home(self): url = reverse('cheese_list') response = self.client.get(url) self.assertContains(response, 'Cheese')
  9. Search Error reporting HTML5 forms Database migrations CMS REST API

    Background tasks Debugging There's an app for that