Djangobook note

寵の児 提交于 2020-02-16 07:56:59

Ref
example:

MTV frameworkIn the MTV development pattern,
“M” stands for model, the data-access layer. This layer contains anything and everything about the data: how to access it,how to validate it, which behaviors it has and the relationships between the data.
“T” stands for template, the presentation layer. This layer contains presentation-related decisions: how something should be displayed on a Web page or other type of document.
“V” stands for view, the business-logic layer. This layer contains the logic that access the model and defers to the appropriate template(s). You can think of it as the bridge between models and templates.

Installation
------------
$ python setup.py install

error: cann't find /usr/lib/python2.5/site-package/config
solution: unzip Django1.0 into /usr/lib/python2.5/site-package/, then ln django-admin.py to /usr/local/bin

Start Project
-------------
$ project:django-admin.py startproject demo

$ python manage.py runserver or python manage.py runserver 8080

$ e settings.py
DATABASE_ENGINE = 'mysql'
DATABASE_NAME = 'dbname'
DATABASE_USER = 'user'
DATABASE_PASSWORD = 'password'
DATABASE_HOST = ''
DATABASE_PORT = ''

$ python manage.py syncdb


Start App
----------

Projects vs. apps
What's the difference between a project and an app? An app is a Web application that does something -- e.g., a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.

$ python manage.py startapp polls

$ python manage.py shell

Admin Page
------------
Activate the admin site, do these three things:

  • Add "django.contrib.admin" to your INSTALLED_APPS setting.
  • Run python manage.py syncdb. Since you have added a new application to INSTALLED_APPS, the database tables need to be updated.
  • Edit your mysite/urls.py file and uncomment below:
    from django.contrib import admin

    admin.autodiscover()

    (r'^admin/(.*)', admin.site.root),

$ python manage.py runserver

xxd@xxd-desktop:~/web/django_projects/mysite/polls$ more models.py
from django.db import models
import datetime

class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()

class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice

xxd@xxd-desktop:~/web/django_projects/mysite/polls$ more views.py
from django.template import Context, loader
from mysite.polls.models import Poll
from django.http import HttpResponse

# the basic idea of MVC
"""
def index(request):
return HttpResponse(" You're at the poll index.")
"""
# Which displays the latest 5 poll questions in the system,
# separated by commas, according to publication date:
# But the page's design is still a hard-coded view
"""def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
output = ', '.join([p.question for p in latest_poll_list])
return HttpResponse(output)
"""
# better one, but there is a shortcut:
"""
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
t = loader.get_template('polls/index.html')
c = Context({
'latest_poll_list': latest_poll_list,
})
return HttpResponse(t.render(c))
"""

#A shortcut: render_to_response()
from django.shortcuts import render_to_response
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

def detail(request, poll_id):
return HttpResponse("You're looking at poll %s." % poll_id)

#Raising 404
"""
from django.http import Http404
def detail(request, poll_id):
try:
p = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
return render_to_response('polls/detail.html', {'poll': p})
"""

#Raising 404 shortcut
from django.shortcuts import render_to_response, get_object_or_404
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p})
# There's also a get_list_or_404() function,
# which works just as get_object_or_404()
# -- except using filter() instead of get().
# It raises Http404 if the list is empty.

from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from mysite.polls.models import Choice, Poll
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render_to_response('polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('mysite.polls.views.results', args=(p.id,)))

def results(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/results.html', {'poll': p})

xxd@xxd-desktop:~/web/django_projects/mysite$ more urls.py
from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('mysite.polls.views',
# Example:
# (r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
(r'^$', 'index'),
(r'^(?P\d+)/$', 'detail'),
(r'^(?P\d+)/results/$', 'results'),
# just for fun
#(r'^polls/latest\.php$', 'mysite.polls.views.index'),
(r'^(?P\d+)/vote/$', '.vote'),
(r'^admin/(.*)', admin.site.root),
)

#generic views:

"""
from django.conf.urls.defaults import *
from mysite.polls.models import Poll

info_dict = {
'queryset': Poll.objects.all(),
}

urlpatterns = patterns('',
(r'^$', 'django.views.generic.list_detail.object_list', info_dict),
(r'^(?P\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
url(r'^(?P\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results
'),
(r'^(?P\d+)/vote/$', 'mysite.polls.views.vote'),
)
"""


*. Add Admin Page for 0.96:


1.add below into setting.py

INSTALLED_APPS = (
‘django.contrib.admin’,
)

2.add below into urls.py:

(r’^admin/’, include(’django.contrib.admin.urls’))

3.manage.py shell

>>> from django.contrib.auth.create_superuser import createsuperuser
>>> createsuperuser()

4.

$ manage.py syncdb


* Django ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined

solution1
>>> from django.template import Template, Context
>>> from django.conf import settings
>>> settings.configure()>
>>> t = Template('My name is {{ my_name }}.')
>>> c = Context({'my_name': 'Daryl Spitzer'})
>>> t.render(c)

solution2
$ which python2.5
/usr/bin/python2.5
$ export PYTHONPATH=/usr/bin/python2.5:~/share
$ export DJANGO_SETTINGS_MODULE=test.settings
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!