out_url = "http://www.google.com" return render_to_response('short/redirect.html', {'out_url':out_url})in short/redirect.html
<meta http-equiv="refresh" content="0; URL={{ out_url }}">
out_url = "http://www.google.com" return render_to_response('short/redirect.html', {'out_url':out_url})in short/redirect.html
<meta http-equiv="refresh" content="0; URL={{ out_url }}">
cd //var/www/mutarock/mutarock vim settings.py
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), '..', 'multimedia').replace('\\','/') MEDIA_URL = '/multimedia/'設定完之後移到上一層去
cd .. mkdir multimedia接下來是apps裡面models.py的設定
class Picture(models.Model): image = models.ImageField(upload_to='pic')
vim form.py輸入下面的code
from django import forms from PIL import Image class PictureUploadForm(forms.Form): image = forms.ImageField() def clean_image(self): ' reject large images.' max_size = 10**7 if len(self.cleaned_data['image'].read()) > max_size: raise forms.ValidationError('Image must be less then %d bytes.' % max_size) else: return self.cleaned_data['image']
import uuid #use for data name from apps.picture.form import PictureUploadForm #import your form def picture_upload(request): picture = Picture() if request.method != 'POST': form = PictureUploadForm() else: form = PictureUploadForm(request.POST, request.FILES) if form.is_valid(): # an UploadedFile object uploadedImage = form.cleaned_data['image'] file_name = uuid.uuid4().hex file_extension = os.path.splitext(uploadedImage.name)[-1] full_file_name = file_name + file_extension # save picture object picture.image.save( full_file_name, request.FILES['image'], save = False ) picture.save() return render_to_response( 'example/result.html' {'result': "Upload success",}, context_instance = RequestContext(request)) return render_to_response( 'example/picture_upload.html', {'form':form}, context_instance = RequestContext(request))
<form enctype="multipart/form-data" method="post" action="example/picture_upload"> {% csrf_token %} <table> {{form.as_p}} </table> <input type="submit" value="Submit" id="Save"/> </form>
<p> {{ result }} </p>
urlpatterns += patterns('', url(r'^multimedia/(?P所以我輸入.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
cd //var/www/mutarock/apps/polls vim views.py首先先來新增一個index,這個可以印出資料庫最近新增的幾個投票
from django.template import Context, loader from apps.polls.models import Poll from django.http import HttpResponse 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))上面的code會抓出最近的5個投票,並且讀取polls/index.html這個templates
python manage.py runserver開啟瀏覽器 http://127.0.0.1:8000/polls 應該會跑出錯誤訊息
TemplateDoesNotExist at /polls/ polls/index.html這是因為我們還沒有把templates建立起來,我們前面只是設定
cd //var/www/mutarock mkdir templates cd templates mkdir polls目前這個系統的資料夾應該會像
mutarock/ manage.py mutarock/ apps/ polls/ templates/ polls/移到 templates/polls 資料夾去建立我們的index.html
{% if latest_poll_list %} {% if latest_poll_list %} <ul> {% for poll in latest_poll_list %} <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}這樣就可以順利顯示我們的polls資訊了
cd //var/www/mutarock/mutarock/ vim settings.py
TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/'), )這個設定主要是告訴django你的模板放在哪裡,我這邊用的是相對路徑
cd .. mkdir templates cd templates/ mkdir polls我希望每個apps的模板放的地方不一樣,所以多新增一個子資料夾polls
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^polls/$', 'polls.views.index'), url(r'^polls/(?P\d+)/$', 'polls.views.detail'), url(r'^polls/(?P \d+)/results/$', 'polls.views.results'), url(r'^polls/(?P \d+)/vote/$', 'polls.views.vote'), url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^polls/', include('apps.polls.urls')), url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url urlpatterns = patterns('apps.polls.views', url(r'^$', 'index'), url(r'^(?P之後再browser上面輸入 http://127.0.0.1/polls 系統就會知道要導向到polls的urls.py\d+)/$', 'detail'), url(r'^(?P \d+)/results/$', 'results'), url(r'^(?P \d+)/vote/$', 'vote'), )
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'apps.polls', )
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin import settings admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'mutarock.views.home', name='home'), # url(r'^mutarock/', include('mutarock.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), )這邊的urlpattern是利用regular expression去表示
python manage.py runsever打開瀏覽器進入你在domain下面的admin page
cd //var/www/mutarock/apps/polls/ vim admin.py輸入
from polls.models import Poll from django.contrib import admin admin.site.register(Poll)
cd //var/www/mutarock python manage.py startapp apps以後的app都把它放在這麼資料夾下面
cd /apps python ./manage.py startapp polls目前整個project的資料夾應該像下面這樣
mutarock/ manage.py mutarock/ apps/ polls/polls則是長這個樣子
polls/ __init__.py models.py tests.py views.pymodels.py主要是這個app的資料型態,例如這個例子裡面有Poll和Choice
from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField()其他細節就不多說了,可以去看教學
cd //var/www/mutarock/mutarock vim settings.py其中一個欄位是INSTALLED_APPS,在這邊把自己的app加進去
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'apps.polls', #這個範例的app )OK之後可以利用強大的managa.py去顯示這個app會建立的哪些table有哪些欄位(based on your model)
python manage.py sql polls確定應該沒有問題之後就輸入
python manage.py syncdb系統就會實際把table建好
python manage.py shell這個語法去實際和系統互動 以下是教學提供的幾個例子,我就貼過來自己看
>>> from polls.models import Poll, Choice # Import the model classes we just wrote. # No polls are in the system yet. >>> Poll.objects.all() [] # Create a new Poll. # Support for time zones is enabled in the default settings file, so # Django expects a datetime with tzinfo for pub_date. Use timezone.now() # instead of datetime.datetime.now() and it will do the right thing. >>> from django.utils import timezone >>> p = Poll(question="What's new?", pub_date=timezone.now()) # Save the object into the database. You have to call save() explicitly. >>> p.save() # Now it has an ID. Note that this might say "1L" instead of "1", depending # on which database you're using. That's no biggie; it just means your # database backend prefers to return integers as Python long integer # objects. >>> p.id 1 # Access database columns via Python attributes. >>> p.question "What's new?" >>> p.pub_date datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<utc>) # Change values by changing the attributes, then calling save(). >>> p.question = "What's up?" >>> p.save() # objects.all() displays all the polls in the database. >>> Poll.objects.all() [<Poll: Poll object>]可以看到最後一個例子回傳的東西相當不人性化
class Poll(models.Model): # ... def __unicode__(self): return self.question class Choice(models.Model): # ... def __unicode__(self): return self.choice教學上面提到,熟悉python的人一般會使用 __str__ 而不是 __unicode__ 這邊會建議使用 __unicode__ 是因為django預設是用unicode
sudo apt-get update sudo apt-get upgrade sudo apt-get install mysql-server mysql-client python-mysqldb python-django
mysql -u root -p create database djangodb; exit;
cd //var/www/mutarock/mutarock/ vim settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'djangodb', # Or path to database file if using sqlite3. 'USER': 'USERNAME', # Not used with sqlite3. 'PASSWORD': 'PASSEORD', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } }ENGINE: 是database的種類,我是用mysql
python manage.py syncdb就會在所選擇的database裡面新增幾個基本的table
sudo apt-get update sudo apt-get upgrade sudo apt-get install python-setuptools sudo apt-get install python-pip sudo pip install django
cd //var/www/ sudo django-admin.py startproject mutarock
mutarock/ manage.py mutarock/ __init__.py settings.py urls.py wsgi.py
python manage.py runserver如果沒有問題的話,應該就可以看到