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

Introduction to Django

Introduction to Django

Django and Heroku

Kien Nguyen

October 05, 2013
Tweet

More Decks by Kien Nguyen

Other Decks in Technology

Transcript

  1. Model - View - Template Model - what things are

    View - how things are processed Template - How things are presented
  2. Models import datetime from django.db import models from django.utils import

    timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
  3. Represents the DB objects BEGIN; CREATE TABLE "codecamp_question" ( "id"

    integer NOT NULL PRIMARY KEY, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL ) ; CREATE TABLE "codecamp_choice" ( "id" integer NOT NULL PRIMARY KEY, "question_id" integer NOT NULL REFERENCES "codecamp_question" ("id"), "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL ) ; COMMIT;
  4. Views Where all magic happens Normally Keep your logic in

    the model Process model instances Render HTML
  5. Views def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice

    = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('results', args=(p.id,)))
  6. index.html {% if latest_question_list %} <ul> {% for question in

    latest_question_list %} <li> <a href="{% url 'detail' question.id %}"> {{ question.question_text }} </a> </li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
  7. views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect,

    HttpResponse from django.core.urlresolvers import reverse from codecamp.models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context)
  8. detail.html <h1>{{ question.question_text }}</h1> {% if error_message %} <p><strong>{{ error_message

    }}</strong></p> {% endif %} <form action="{% url 'vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}"> {{ choice.choice_text }} </label><br /> {% endfor %} <input type="submit" value="Vote" /> </form>
  9. views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect,

    HttpResponse from django.core.urlresolvers import reverse from codecamp.models import Question def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', { 'question': question })
  10. Security advantages No raw SQL from users - we deal

    with models and queries Automatic HTML parsing - no XSS attacks CSRF protection - no replay of forms by other code
  11. URLs from django.conf.urls import patterns, include, url from codecamp import

    views # for admin page from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^polls/(?P<question_id>\d+)/$', views.detail, name='detail'), url(r'^polls/(?P<question_id>\d+)/results/$', views.results, name='results'), url(r'^polls/(?P<question_id>\d+)/vote/$', views.vote, name='vote'), url(r'^admin/', include(admin.site.urls)), ) URLs map to views (view Regular expressions)
  12. Views are python function from django.shortcuts import render, get_object_or_404 from

    django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from codecamp.models import Question def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', { 'question': question })
  13. Admin interface class ChoiceInline(admin.StackedInline): model = models.Choice extra = 4

    class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date']}), ] search_fields = ['question_text'] list_display = ('question_text', 'pub_date', 'was_published_recently') inlines = [ChoiceInline] admin.site.register(models.Question, QuestionAdmin)
  14. Admin interface class MemberAdmin(UserAdmin): list_filter = ('is_admin', ) filter_horizontal =

    () fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('email', )}), ) search_fields = ('email', 'username') list_display = ('username', 'email', 'is_admin', 'date_joined') list_per_page = 50 admin.site.register(models.Member, MemberAdmin) admin.site.register(models.Question, QuestionAdmin)
  15. manage.py shell: start up a python shell with your django

    project loaded in test: run you unit test runserver: run built in server for python app syncdb: create SQL for your models
  16. Features Support various programming language: Python, Ruby, Node.js, Java, Scala,

    ... Support a lot of plugins to work with other cloud services (AWS, RDS, MongoDB, ...) Painless deploy/rollback over git tool Easily to scale horizontally???
  17. QA