Permalink
Browse files

Merge pull request #1129 from frog32/master

Add needed Imports to the Documentation
  • Loading branch information...
2 parents c70ca48 + a4a761a commit 33c361ef9d882522aeae549a3a8c8b52ca5cfc5a @mjtamlyn mjtamlyn committed May 19, 2013
View
@@ -197,6 +197,7 @@ answer newbie questions, and generally made Django that much better:
J. Clifford Dyer <jcd@sdf.lonestar.org>
Clint Ecker
Nick Efford <nick@efford.org>
+ Marc Egli <frog32@me.com>
eibaan@gmail.com
David Eklund
Julia Elman
@@ -221,6 +222,7 @@ answer newbie questions, and generally made Django that much better:
Stefane Fermgier <sf@fermigier.com>
J. Pablo Fernandez <pupeno@pupeno.com>
Maciej Fijalkowski
+ Leandra Finger <leandra.finger@gmail.com>
Juan Pedro Fisanotti <fisadev@gmail.com>
Ben Firshman <ben@firshman.co.uk>
Matthew Flanagan <http://wadofstuff.blogspot.com>
@@ -531,6 +533,7 @@ answer newbie questions, and generally made Django that much better:
Don Spaulding <donspauldingii@gmail.com>
Calvin Spealman <ironfroggy@gmail.com>
Dane Springmeyer
+ Silvan Spross <silvan.spross@gmail.com>
Bjørn Stabell <bjorn@exoweb.net>
Georgi Stanojevski <glisha@gmail.com>
starrynight <cmorgh@gmail.com>
@@ -24,6 +24,8 @@ representing your models -- so far, it's been solving two years' worth of
database-schema problems. Here's a quick example, which might be saved in
the file ``mysite/news/models.py``::
+ from django.db import models
+
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
@@ -214,6 +216,8 @@ Generally, a view retrieves data according to the parameters, loads a template
and renders the template with the retrieved data. Here's an example view for
``year_archive`` from above::
+ from django.shortcuts import render_to_response
+
def year_archive(request, year):
a_list = Article.objects.filter(pub_date__year=year)
return render_to_response('news/year_archive.html', {'year': year, 'article_list': a_list})
@@ -582,6 +582,8 @@ of this object. Let's fix that by editing the polls model (in the
``Choice``. On Python 3, simply replace ``__unicode__`` by ``__str__`` in the
following example::
+ from django.db import models
+
class Poll(models.Model):
# ...
def __unicode__(self): # Python 3: def __str__(self):
@@ -158,6 +158,9 @@ you want when you register the object.
Let's see how this works by re-ordering the fields on the edit form. Replace
the ``admin.site.register(Poll)`` line with::
+ from django.contrib import admin
+ from polls.models import Poll
+
class PollAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question']
@@ -179,6 +182,9 @@ of fields, choosing an intuitive order is an important usability detail.
And speaking of forms with dozens of fields, you might want to split the form
up into fieldsets::
+ from django.contrib import admin
+ from polls.models import Poll
+
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
@@ -198,6 +204,9 @@ You can assign arbitrary HTML classes to each fieldset. Django provides a
This is useful when you have a long form that contains a number of fields that
aren't commonly used::
+ from django.contrib import admin
+ from polls.models import Poll
+
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
@@ -218,6 +227,7 @@ Yet.
There are two ways to solve this problem. The first is to register ``Choice``
with the admin just as we did with ``Poll``. That's easy::
+ from django.contrib import admin
from polls.models import Choice
admin.site.register(Choice)
@@ -342,6 +352,12 @@ representation of the output.
You can improve that by giving that method (in :file:`polls/models.py`) a few
attributes, as follows::
+ import datetime
+ from django.utils import timezone
+ from django.db import models
+
+ from polls.models import Poll
+
class Poll(models.Model):
# ...
def was_published_recently(self):
@@ -393,6 +393,9 @@ Now, let's tackle the poll detail view -- the page that displays the question
for a given poll. Here's the view::
from django.http import Http404
+ from django.shortcuts import render
+
+ from polls.models import Poll
# ...
def detail(request, poll_id):
try:
@@ -420,6 +423,8 @@ and raise :exc:`~django.http.Http404` if the object doesn't exist. Django
provides a shortcut. Here's the ``detail()`` view, rewritten::
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)
@@ -136,6 +136,8 @@ object. For more on :class:`~django.http.HttpRequest` objects, see the
After somebody votes in a poll, the ``vote()`` view redirects to the results
page for the poll. Let's write that view::
+ from django.shortcuts import get_object_or_404, render
+
def results(request, poll_id):
poll = get_object_or_404(Poll, pk=poll_id)
return render(request, 'polls/results.html', {'poll': poll})
@@ -98,6 +98,8 @@ second element is the human-readable name. For example::
Generally, it's best to define choices inside a model class, and to
define a suitably-named constant for each value::
+ from django.db import models
+
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
@@ -997,12 +999,15 @@ relationship with itself -- use ``models.ForeignKey('self')``.
If you need to create a relationship on a model that has not yet been defined,
you can use the name of the model, rather than the model object itself::
+ from django.db import models
+
class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
# ...
class Manufacturer(models.Model):
# ...
+ pass
To refer to models defined in another application, you can explicitly specify
a model with the full application label. For example, if the ``Manufacturer``
@@ -1135,6 +1140,9 @@ The possible values for :attr:`~ForeignKey.on_delete` are found in
necessary to avoid executing queries at the time your models.py is
imported::
+ from django.db import models
+ from django.contrib.auth.models import User
+
def get_sentinel_user():
return User.objects.get_or_create(username='deleted')[0]
@@ -1207,6 +1215,8 @@ that control how the relationship functions.
Only used in the definition of ManyToManyFields on self. Consider the
following model::
+ from django.db import models
+
class Person(models.Model):
friends = models.ManyToManyField("self")
@@ -34,6 +34,8 @@ that, you need to :meth:`~Model.save()`.
1. Add a classmethod on the model class::
+ from django.db import models
+
class Book(models.Model):
title = models.CharField(max_length=100)
@@ -105,6 +107,7 @@ individually.
You'll need to call ``full_clean`` manually when you want to run one-step model
validation for your own manually created models. For example::
+ from django.core.exceptions import ValidationError
try:
article.full_clean()
except ValidationError as e:
@@ -132,6 +135,7 @@ automatically provide a value for a field, or to do validation that requires
access to more than a single field::
def clean(self):
+ import datetime
from django.core.exceptions import ValidationError
# Don't allow draft entries to have a pub_date.
if self.status == 'draft' and self.pub_date is not None:
@@ -434,6 +438,8 @@ representation of the model from the ``__unicode__()`` method.
For example::
+ from django.db import models
+
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
@@ -460,6 +466,9 @@ Thus, you should return a nice, human-readable string for the object's
The previous :meth:`~Model.__unicode__()` example could be similarly written
using ``__str__()`` like this::
+ from django.db import models
+ from django.utils.encoding import force_bytes
+
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
@@ -490,6 +499,7 @@ function is usually the best approach.)
For example::
def get_absolute_url(self):
+ from django.core.urlresolvers import reverse
return reverse('people.views.details', args=[str(self.id)])
One place Django uses ``get_absolute_url()`` is in the admin app. If an object
@@ -145,6 +145,12 @@ Django quotes column and table names behind the scenes.
and a question has more than one answer, and the order of answers matters, you'd
do this::
+ from django.db import models
+
+ class Question(models.Model):
+ text = models.TextField()
+ # ...
+
class Answer(models.Model):
question = models.ForeignKey(Question)
# ...
@@ -232,6 +232,7 @@ the model field that is being aggregated.
For example, if you were manipulating a list of blogs, you may want
to determine how many entries have been made in each blog::
+ >>> from django.db.models import Count
>>> q = Blog.objects.annotate(Count('entry'))
# The name of the first blog
>>> q[0].name
@@ -699,6 +700,8 @@ And here's ``select_related`` lookup::
``select_related()`` follows foreign keys as far as possible. If you have the
following models::
+ from django.db import models
+
class City(models.Model):
# ...
pass
@@ -814,6 +817,8 @@ that are supported by ``select_related``. It also supports prefetching of
For example, suppose you have these models::
+ from django.db import models
+
class Topping(models.Model):
name = models.CharField(max_length=30)
@@ -1565,6 +1570,7 @@ aggregated.
For example, when you are working with blog entries, you may want to know the
number of authors that have contributed blog entries::
+ >>> from django.db.models import Count
>>> q = Blog.objects.aggregate(Count('entry'))
{'entry__count': 16}
@@ -2042,6 +2048,7 @@ Range test (inclusive).
Example::
+ import datetime
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
Entry.objects.filter(pub_date__range=(start_date, end_date))
@@ -12,8 +12,11 @@ Related objects reference
* The "other side" of a :class:`~django.db.models.ForeignKey` relation.
That is::
+ from django.db import models
+
class Reporter(models.Model):
- ...
+ # ...
+ pass
class Article(models.Model):
reporter = models.ForeignKey(Reporter)
@@ -24,7 +27,8 @@ Related objects reference
* Both sides of a :class:`~django.db.models.ManyToManyField` relation::
class Topping(models.Model):
- ...
+ # ...
+ pass
class Pizza(models.Model):
toppings = models.ManyToManyField(Topping)
@@ -215,6 +215,7 @@ re-rendered, you can re-evaluate the rendered content, and assign
the content of the response manually::
# Set up a rendered TemplateResponse
+ >>> from django.template.response import TemplateResponse
>>> t = TemplateResponse(request, 'original.html', {})
>>> t.render()
>>> print(t.content)
@@ -256,6 +257,8 @@ To define a post-render callback, just define a function that takes
a single argument -- response -- and register that function with
the template response::
+ from django.template.response import TemplateResponse
+
def my_render_callback(response):
# Do content-sensitive processing
do_post_processing()
@@ -248,7 +248,7 @@ specify the objects that the view will operate upon -- you can also
specify the list of objects using the ``queryset`` argument::
from django.views.generic import DetailView
- from books.models import Publisher, Book
+ from books.models import Publisher
class PublisherDetail(DetailView):
@@ -326,6 +326,7 @@ various useful things are stored on ``self``; as well as the request
Here, we have a URLconf with a single captured group::
# urls.py
+ from django.conf.urls import patterns
from books.views import PublisherBookList
urlpatterns = patterns('',
@@ -375,6 +376,7 @@ Imagine we had a ``last_accessed`` field on our ``Author`` object that we were
using to keep track of the last time anybody looked at that author::
# models.py
+ from django.db import models
class Author(models.Model):
salutation = models.CharField(max_length=10)
@@ -390,6 +392,7 @@ updated.
First, we'd need to add an author detail bit in the URLconf to point to a
custom view::
+ from django.conf.urls import patterns, url
from books.views import AuthorDetailView
urlpatterns = patterns('',
@@ -401,7 +404,6 @@ Then we'd write our new view -- ``get_object`` is the method that retrieves the
object -- so we simply override it and wrap the call::
from django.views.generic import DetailView
- from django.shortcuts import get_object_or_404
from django.utils import timezone
from books.models import Author
@@ -222,6 +222,7 @@ works for AJAX requests as well as 'normal' form POSTs::
from django.http import HttpResponse
from django.views.generic.edit import CreateView
+ from myapp.models import Author
class AjaxableResponseMixin(object):
"""
Oops, something went wrong.

0 comments on commit 33c361e

Please sign in to comment.