Python-Django의 명령

9721 단어 mvcdjangostaticfile
# 1.      helloworld
#
#      django     django   
# https://pypi.python.org/pypi/Django/1.6.4
python3 setup.py install
#
#   django  
django-admin.py startproject mysite
#
#   django  
python3 manage.py runserver [port]
#
#     app
python3 manage.py startapp appname

# 2. model  
#           (    Field   )
# AutoFiled  SlugField SmallIntegerField #Date,DateTime,Decimal,Char,File,Float,FilePath,Text#,Time,Binary,Boolean,BigInterger,NullBoolean,Image,#Interger,OneToOne
#PositiveSmallIntegerField, #PositiveIntergerField,Url,Email
#
#     model  
from django.db import models
class Publisher(models.Model):
    name = models.CharField(max_length=30) //     
    website = models.URLField()   // url    
    email = models.EmailField()   // email    
    publication_date = models.DateField()   //       
    publisher = models.ForeignKey(Publisher)   //     (  )
#
#         (        @2BiTT)
class Person(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)
#
#       (        @2BiTT)
class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)
    def get_absolute_url(self):
        return "/people/%i/" % self.id

# 3.          
#      (   settings.py    app)
python3 manage.py validate
#
#     sql    
python3 manage.py sqlall modelname (app   )
#
#      db              
python3 manage.py syncdb

# 4. django       
#        
python manage.py createsuperuser
#
#  model   admin       admin 
from django.contrib import admin
from books.models import Publisher, Author, Book
admin.site.register(Author,AuthorAdmin)
#
#       ,        
from django.contrib import admin
class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'publisher', 'publication_date')   #   
    list_filter = ('publication_date',)    #      
    date_hierarchy = 'publication_date'   #       
    ordering = ('-publication_date',)   #         
    fields = ('title', 'authors', 'publisher')  #                     null=True
    raw_id_fields = ('publisher',)  #        id  
#

# 5.         
#       
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'template').replace('\\','/'),
    # /Users/King/Documents/Ops/Python/HelloDjango/HelloDjango
    # /Users/King/Documents/Ops/Python/HelloDjango/HelloDjango/template
)
#
#          
python manage.py shell
    from django.contrib.auth.models import Publisher
    p = Publisher.objects.create(name='Apress',website='www.apress.com')
    Publisher.name = 'tuling'
       model     objects   
      filter      obj    Publisher.objects.filter(name='usa')
                Publisher.objects.filter(name__contains='usa')
#   
      get            ,               Publisher.DoesNotExist
      order_by         -   
    p = Publisher.objects.filter(id=52).update(name='Apress Publishing')
    p.delete()       
    p.save()
#
#       
 setting.py 
    #       
    #                     
    STATIC_ROOT = 'static/'
    #   url        urls  
    STATIC_URL = 'static/'
      
    <link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.css">
    <script type="text/javascript" src="{{ STATIC_URL }}js/bootstrap.js"></script>
 urls.py    
    from django.conf.urls.static import static
         
    admin.autodiscover()
    urlpatterns = patterns('',
        # Examples:
        # url(r'^$', 'HelloDjango.views.home', name='home'),
        # url(r'^blog/', include('blog.urls')),
        url(r'^admin/', include(admin.site.urls)),
        (r'^$', latest_books),
    ) + (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT))
 views.py        
    return render_to_response('index.html', {
        'book_list': book_list,
        'STATIC_URL': STATIC_URL,
    })

# 6.       
     
STATICFILES_DIRS = (
    '/Users/King/Documents/Ops/Python/HelloDjango/static',
)
#
#
#   app     
#
#
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
ROOT_URLCONF = 'HelloDjango.urls'
SECRET_KEY = '&%s+d(0$motnksr+0o+oo8z9k=2h*7gd%gnnylrnc^w5#nut)h'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
WSGI_APPLICATION = 'HelloDjango.wsgi.application'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# # Absolute filesystem path to the directory that will hold user-uploaded files.
# # Example: "/home/media/media.lawrence.com/media/"
# MEDIA_ROOT = ''
#
# # URL that handles the media served from MEDIA_ROOT. Make sure to use a
# # trailing slash.
# # Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
# MEDIA_URL = ''
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# TEMPLATE_DIRS = ('templates',)
#       
#                     
STATIC_ROOT = 'static/'
#   url        urls  
STATIC_URL = 'static/'
# STATICFILES_DIRS = (
# # Put strings here, like "/home/html/static" or "C:/www/django/static".
# # Always use forward slashes, even on Windows.
# # Don't forget to use absolute paths, not relative paths.
# )
# STATICFILES_FINDERS = (
#     'django.contrib.staticfiles.finders.FileSystemFinder',
#     'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#     #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
# )
#       
# List of callables that know how to import templates from various sources.
# TEMPLATE_LOADERS = (
#     'django.template.loaders.filesystem.Loader',
#     'django.template.loaders.app_directories.Loader',
#     #     'django.template.loaders.eggs.Loader',
# )
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates').replace('\\','/'),
)
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app',
)
# LOGGING = {
#     'version': 1,
#     'disable_existing_loggers': False,
#     'filters': {
#         'require_debug_false': {
#             '()': 'django.utils.log.RequireDebugFalse'
#         }
#     },
#     'handlers': {
#         'mail_admins': {
#             'level': 'ERROR',
#             'filters': ['require_debug_false'],
#             'class': 'django.utils.log.AdminEmailHandler'
#         }
#     },
#     'loggers': {
#         'django.request': {
#             'handlers': ['mail_admins'],
#             'level': 'ERROR',
#             'propagate': True,
#             },
#         }
# }

Django 프레임워크의 기본 상호작용
#         
from django.shortcuts import render_to_response
def search(request):
    return render_to_response('search.html', {'books':books,})
#
# search.html      ,     
{% if books %}
    <ul>
       {{ books | length }}   
    {% for book in books %}
        <li>{{ book.title }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>           </p>
{% endif %}
#         search_form.html
<html><head>
<title>Search</title></head>
<body>
{% if error %}
<p style="color:red;">       </p>
{% endif %}
<form action="/search_form/" method="get">    
<input type="text" name="q">    
<input type="submit" value="Search">
</form>
</body>
</html>
#
#        
# from django.http import HttpResponse
# request.path()   get_host()   get_full_path()   get_isecure()
# request.META[]     http   
def search_form(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        books = Book.objects.filter(title__icontains=q)
        return render_to_response('search_result.html', {'books':books,'query':q})
    else:
        return render_to_response('search.html', {'error': True})

마지막 부록에서 기본 실현 코드 1부
다음 계획 Django의 고급 응용 프로그램

좋은 웹페이지 즐겨찾기