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

Intro To Django

Intro To Django

Slides to a talk given by Sean O'Connor at the NYLUG.

Sean O'Connor

November 14, 2013
Tweet

More Decks by Sean O'Connor

Other Decks in Programming

Transcript

  1. ORM

  2. from myapp.models import Person ! chauncey = Person.objects.create(first_name="Chauncey", last_name="McPufferson") print

    chauncey.first_name chauncey.last_name = "McPufferson" chauncey.save() chauncey.delete()
  3. from myapp.models import Person ! person = Person.objects.get(id=1) bobs =

    Person.objects.filter(first_name="Bob") obs = Person.objects.raw( "SELECT * FROM myapp_person WHERE first_name LIKE '%ob%'")
  4. from django.conf.urls import patterns, include, url ! from polls import

    views ! urlpatterns = patterns('', # ex: /polls/ url(r'^$', views.index, name=‘index'), ! ! ! ! ! ! ! ! ) # ex: /polls/5/ url(r'^(?P<poll_id>\d+)/$', views.detail, name=‘detail'), # ex: /polls/5/results/ url(r'^(?P<poll_id>\d+)/results/$', views.results, name=‘results'), # ex: /polls/special/* url(r'^special/', include('polls.special.urls')),
  5. from django.shortcuts import render from polls.models import Poll ! !

    ! def index(request): ! ! latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] ! ! context = {'latest_poll_list': latest_poll_list} ! ! return render(request, 'polls/index.html', context)
  6. from django.shortcuts import render, get_object_or_404 from polls.models import Poll !

    ! ! ! def detail(request, poll_id): ! ! poll = get_object_or_404(Poll, pk=poll_id) ! ! return render(request, 'polls/detail.html', {'poll': poll})
  7. <h1>{{ poll.question }}</h1> ! <ul> {% for choice in poll.choice_set.all

    %} ! <li>{{ choice.choice_text }}</li> ! {% endfor %} </ul>
  8. from django import forms ! ! class ContactForm(forms.Form): ! subject

    = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() cc_myself = forms.BooleanField(required=False)
  9. <form action="/contact/" method=“post"> ! <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject"

    maxlength="100" /></p> ! <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p> ! <p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></p> ! <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p> ! <input type="submit" value="Submit" /> ! </form>
  10. from django.shortcuts import render from django.http import HttpResponseRedirect ! def

    contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/thanks/') else: form = ContactForm() ! return render(request, 'contact.html', { 'form': form, })
  11. RSS