使用django创建项目最终代码

目录树

  1. djproject/  
  2. |-- db  
  3. |   `-- tdata.sqlite3  
  4. |-- djproject  
  5. |   |-- __init__.py  
  6. |   |-- __init__.pyc  
  7. |   |-- settings.py  
  8. |   |-- settings.pyc  
  9. |   |-- urls.py  
  10. |   |-- urls.pyc  
  11. |   |-- wsgi.py  
  12. |   `-- wsgi.pyc  
  13. |-- jobs  
  14. |   |-- admin.py  
  15. |   |-- admin.pyc  
  16. |   |-- __init__.py  
  17. |   |-- __init__.pyc  
  18. |   |-- models.py  
  19. |   |-- models.pyc  
  20. |   |-- tests.py  
  21. |   |-- views.py  
  22. |   `-- views.pyc  
  23. |-- manage.py  
  24. `-- templates  
  25.     |-- base.html  
  26.     `-- jobs  
  27.         |-- base.html  
  28.         |-- job_detail.html  
  29.         `-- job_list.html  
djproject/
|-- db
|   `-- tdata.sqlite3
|-- djproject
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- settings.py
|   |-- settings.pyc
|   |-- urls.py
|   |-- urls.pyc
|   |-- wsgi.py
|   `-- wsgi.pyc
|-- jobs
|   |-- admin.py
|   |-- admin.pyc
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- models.py
|   |-- models.pyc
|   |-- tests.py
|   |-- views.py
|   `-- views.pyc
|-- manage.py
`-- templates
    |-- base.html
    `-- jobs
        |-- base.html
        |-- job_detail.html
        `-- job_list.html
手动修改或添加的文件

djproject/
|-- db
|   `-- tdata.sqlite3
|-- djproject
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- settings.py

  1. # Django settings for djproject project.   
  2.   
  3. DEBUG = True  
  4. TEMPLATE_DEBUG = DEBUG  
  5.   
  6. ADMINS = (  
  7.     # ('Your Name', 'your_email@example.com'),   
  8. )  
  9.   
  10. MANAGERS = ADMINS  
  11.   
  12. DATABASES = {  
  13.     'default': {  
  14.         'ENGINE''django.db.backends.sqlite3'# Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.   
  15.         'NAME''db/tdata.sqlite3',                      # Or path to database file if using sqlite3.   
  16.         'USER''',                      # Not used with sqlite3.   
  17.         'PASSWORD''',                  # Not used with sqlite3.   
  18.         'HOST''',                      # Set to empty string for localhost. Not used with sqlite3.   
  19.         'PORT''',                      # Set to empty string for default. Not used with sqlite3.   
  20.     }  
  21. }  
  22.   
  23. # Local time zone for this installation. Choices can be found here:   
  24. # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name   
  25. # although not all choices may be available on all operating systems.   
  26. # On Unix systems, a value of None will cause Django to use the same   
  27. # timezone as the operating system.   
  28. # If running in a Windows environment this must be set to the same as your   
  29. # system time zone.   
  30. TIME_ZONE = 'America/Chicago'  
  31.   
  32. # Language code for this installation. All choices can be found here:   
  33. # http://www.i18nguy.com/unicode/language-identifiers.html   
  34. LANGUAGE_CODE = 'en-us'  
  35.   
  36. SITE_ID = 1  
  37.   
  38. # If you set this to False, Django will make some optimizations so as not   
  39. # to load the internationalization machinery.   
  40. USE_I18N = True  
  41.   
  42. # If you set this to False, Django will not format dates, numbers and   
  43. # calendars according to the current locale.   
  44. USE_L10N = True  
  45. # If you set this to False, Django will not use timezone-aware datetimes.   
  46. USE_TZ = True  
  47.   
  48. # Absolute filesystem path to the directory that will hold user-uploaded files.   
  49. # Example: "/home/media/media.lawrence.com/media/"   
  50. MEDIA_ROOT = ''  
  51.   
  52. # URL that handles the media served from MEDIA_ROOT. Make sure to use a   
  53. # trailing slash.   
  54. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/"   
  55. MEDIA_URL = ''  
  56.   
  57. # Absolute path to the directory static files should be collected to.   
  58. # Don't put anything in this directory yourself; store your static files   
  59. # in apps' "static/" subdirectories and in STATICFILES_DIRS.   
  60. # Example: "/home/media/media.lawrence.com/static/"   
  61. STATIC_ROOT = ''  
  62.   
  63. # URL prefix for static files.   
  64. # Example: "http://media.lawrence.com/static/"   
  65. STATIC_URL = '/static/'  
  66.   
  67. # Additional locations of static files   
  68. STATICFILES_DIRS = (  
  69.     # Put strings here, like "/home/html/static" or "C:/www/django/static".   
  70.     # Always use forward slashes, even on Windows.   
  71.     # Don't forget to use absolute paths, not relative paths.   
  72. )  
  73.   
  74. # List of finder classes that know how to find static files in   
  75. # various locations.   
  76. STATICFILES_FINDERS = (  
  77.     'django.contrib.staticfiles.finders.FileSystemFinder',  
  78.     'django.contrib.staticfiles.finders.AppDirectoriesFinder',  
  79. #    'django.contrib.staticfiles.finders.DefaultStorageFinder',   
  80. )  
  81.   
  82. # Make this unique, and don't share it with anybody.   
  83. SECRET_KEY = 'u)jwane53vf=^d62(c!3@#a9mv=xug-rbto2j#72+$ogvhsg!y'  
  84.   
  85. # List of callables that know how to import templates from various sources.   
  86. TEMPLATE_LOADERS = (  
  87.     'django.template.loaders.filesystem.Loader',  
  88.     'django.template.loaders.app_directories.Loader',  
  89. #     'django.template.loaders.eggs.Loader',   
  90. )  
  91.   
  92. MIDDLEWARE_CLASSES = (  
  93.     'django.middleware.common.CommonMiddleware',  
  94.     'django.contrib.sessions.middleware.SessionMiddleware',  
  95.     'django.middleware.csrf.CsrfViewMiddleware',  
  96.     'django.contrib.auth.middleware.AuthenticationMiddleware',  
  97.     'django.contrib.messages.middleware.MessageMiddleware',  
  98.     # Uncomment the next line for simple clickjacking protection:   
  99.     # 'django.middleware.clickjacking.XFrameOptionsMiddleware',   
  100. )  
  101.   
  102. ROOT_URLCONF = 'djproject.urls'  
  103.   
  104. # Python dotted path to the WSGI application used by Django's runserver.   
  105. WSGI_APPLICATION = 'djproject.wsgi.application'  
  106.   
  107. TEMPLATE_DIRS = (  
  108.     # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".   
  109.     # Always use forward slashes, even on Windows.   
  110.   
  111.     # Don't forget to use absolute paths, not relative paths.   
  112.     'templates',  
  113. )  
  114.   
  115. INSTALLED_APPS = (  
  116.     'django.contrib.auth',  
  117.     'django.contrib.contenttypes',  
  118.     'django.contrib.sessions',  
  119.     'django.contrib.sites',  
  120.     'django.contrib.messages',  
  121.     'django.contrib.staticfiles',  
  122.     'jobs',  
  123.     # Uncomment the next line to enable the admin:   
  124.     'django.contrib.admin',  
  125.     # Uncomment the next line to enable admin documentation:   
  126.     # 'django.contrib.admindocs',   
  127. )  
  128.   
  129. # A sample logging configuration. The only tangible logging   
  130. # performed by this configuration is to send an email to   
  131. # the site admins on every HTTP 500 error when DEBUG=False.   
  132. # See http://docs.djangoproject.com/en/dev/topics/logging for   
  133. # more details on how to customize your logging configuration.   
  134. LOGGING = {  
  135.     'version'1,  
  136.     'disable_existing_loggers'False,  
  137.     'filters': {  
  138.         'require_debug_false': {  
  139.             '()''django.utils.log.RequireDebugFalse'  
  140.         }  
  141.     },  
  142.     'handlers': {  
  143.         'mail_admins': {  
  144.             'level''ERROR',  
  145.             'filters': ['require_debug_false'],  
  146.             'class''django.utils.log.AdminEmailHandler'  
  147.         }  
  148.     },  
  149.     'loggers': {  
  150.         'django.request': {  
  151.             'handlers': ['mail_admins'],  
  152.             'level''ERROR',  
  153.             'propagate'True,  
  154.         },  
  155.     }  
  156. }   
# Django settings for djproject project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'db/tdata.sqlite3',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # 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.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
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 = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
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.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'u)jwane53vf=^d62(c!3@#a9mv=xug-rbto2j#72+$ogvhsg!y'

# 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',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'djproject.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'djproject.wsgi.application'

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.
    'templates',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'jobs',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
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,
        },
    }
} 
|   |-- settings.pyc
|   |-- urls.py

  1. from django.conf.urls import patterns, include, url  
  2. #from django.conf.urls.defaults import *   
  3.   
  4.   
  5. # Uncomment the next two lines to enable the admin:   
  6. # from django.contrib import admin   
  7. # admin.autodiscover()   
  8. from django.contrib import admin  
  9. admin.autodiscover()  
  10.   
  11.   
  12. urlpatterns = patterns('',  
  13.     # Examples:   
  14.     # url(r'^$', 'djproject.views.home', name='home'),   
  15.     # url(r'^djproject/', include('djproject.foo.urls')),   
  16.   
  17.     # Uncomment the admin/doc line below to enable admin documentation:   
  18.     # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),   
  19.     url(r'^jobs/$''jobs.views.index'),  
  20.     url(r'^jobs/(?P<job_id>\d+)/$''jobs.views.detail'),  
  21.     # Uncomment the next line to enable the admin:   
  22. #    url(r'^admin/', admin.site.urls),   
  23.     url(r'^admin/', admin.site.urls),  
  24.   
  25. )  
from django.conf.urls import patterns, include, url
#from django.conf.urls.defaults import *


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


urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'djproject.views.home', name='home'),
    # url(r'^djproject/', include('djproject.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^jobs/$', 'jobs.views.index'),
    url(r'^jobs/(?P<job_id>\d+)/$', 'jobs.views.detail'),
    # Uncomment the next line to enable the admin:
#    url(r'^admin/', admin.site.urls),
    url(r'^admin/', admin.site.urls),

)
|   |-- urls.pyc
|   |-- wsgi.py
|   `-- wsgi.pyc
|-- jobs
|   |-- admin.py

  1. #admin.py   
  2. from django.contrib import admin  
  3. from jobs.models import Location  
  4. from jobs.models import Job  
  5.   
  6. class JobAdmin(admin.ModelAdmin):  
  7.     fieldsets = [  
  8.         (None,          {'fields': ['pub_date','job_title','job_description']}),  
  9.         ('More info',   {'fields': ['location'], 'classes': ['collapse']}),  
  10.     ]  
  11.     list_display = ('job_title''job_description''pub_date')  
  12.   
  13. class LocationAdmin(admin.ModelAdmin):  
  14.     list_display = ('city''state''country')  
  15.   
  16. admin.site.register(Job,JobAdmin)  
  17. admin.site.register(Location, LocationAdmin)  
#admin.py
from django.contrib import admin
from jobs.models import Location
from jobs.models import Job

class JobAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,          {'fields': ['pub_date','job_title','job_description']}),
        ('More info',   {'fields': ['location'], 'classes': ['collapse']}),
    ]
    list_display = ('job_title', 'job_description', 'pub_date')

class LocationAdmin(admin.ModelAdmin):
    list_display = ('city', 'state', 'country')

admin.site.register(Job,JobAdmin)
admin.site.register(Location, LocationAdmin)
|   |-- admin.pyc
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- models.py

  1. from django.db import models  
  2.   
  3. class Location(models.Model):  
  4.     city = models.CharField(max_length=50)  
  5.     state = models.CharField(max_length=50, null=True, blank=True)  
  6.     country = models.CharField(max_length=50)  
  7.   
  8.     def __str__(self):  
  9.         if self.state:  
  10.             return "%s, %s, %s" % (self.city, self.state, self.country)  
  11.         else:  
  12.             return "%s, %s" % (self.city, self.country)  
  13.   
  14. class Job(models.Model):  
  15.     pub_date = models.DateField()  
  16.     job_title = models.CharField(max_length=50)  
  17.     job_description = models.TextField()  
  18.     location = models.ForeignKey(Location)  
  19.   
  20.     def __str__(self):  
  21.         return "%s (%s)" % (self.job_title, self.location)  
from django.db import models

class Location(models.Model):
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=50, null=True, blank=True)
    country = models.CharField(max_length=50)

    def __str__(self):
        if self.state:
            return "%s, %s, %s" % (self.city, self.state, self.country)
        else:
            return "%s, %s" % (self.city, self.country)

class Job(models.Model):
    pub_date = models.DateField()
    job_title = models.CharField(max_length=50)
    job_description = models.TextField()
    location = models.ForeignKey(Location)

    def __str__(self):
        return "%s (%s)" % (self.job_title, self.location)
|   |-- models.pyc
|   |-- tests.py
|   |-- views.py

  1. # Create your views here.   
  2. from django.shortcuts import get_object_or_404, render_to_response  
  3. from jobs.models import Job  
  4.   
  5.   
  6. def index(request):  
  7.     object_list = Job.objects.order_by('-pub_date')[:3]  
  8.     return render_to_response('jobs/job_list.html', {'object_list': object_list})  
  9.   
  10. def detail(request, job_id):  
  11.     j = get_object_or_404(Job, pk=job_id)  
  12.     return render_to_response('jobs/job_detail.html', {'job': j})  
# Create your views here.
from django.shortcuts import get_object_or_404, render_to_response
from jobs.models import Job


def index(request):
    object_list = Job.objects.order_by('-pub_date')[:3]
    return render_to_response('jobs/job_list.html', {'object_list': object_list})

def detail(request, job_id):
    j = get_object_or_404(Job, pk=job_id)
    return render_to_response('jobs/job_detail.html', {'job': j})
|   `-- views.pyc
|-- manage.py

`-- templates
    |-- base.html

  1. <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >  
  3.   <head>  
  4.     <title>Company Site: {% block title %}Page{% endblock %}</title>  
  5.     {% block extrahead %}{% endblock %}  
  6.   </head>  
  7.   <body>  
  8.     {% block content %}{% endblock %}  
  9.   </body>  
  10. </html>  
<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
  <head>
    <title>Company Site: {% block title %}Page{% endblock %}</title>
    {% block extrahead %}{% endblock %}
  </head>
  <body>
    {% block content %}{% endblock %}
  </body>
</html>
    `-- jobs
        |-- base.html

  1. {% extends "base.html" %}  
  2.   
  3. {% block extrahead %}  
  4.     <style>  
  5.         body {  
  6.             font-style: arial;  
  7.         }  
  8.         h1 {  
  9.             text-align: center;  
  10.         }  
  11.         .job .title {  
  12.             font-size: 120%;  
  13.             font-weight: bold;  
  14.         }  
  15.         .job .posted {  
  16.             font-style: italic;  
  17.         }  
  18.     </style>  
  19. {% endblock %}  
{% extends "base.html" %}

{% block extrahead %}
    <style>
        body {
            font-style: arial;
        }
        h1 {
            text-align: center;
        }
        .job .title {
            font-size: 120%;
            font-weight: bold;
        }
        .job .posted {
            font-style: italic;
        }
    </style>
{% endblock %}
        |-- job_detail.html

  1. {% extends "jobs/base.html" %}  
  2.   
  3. {% block title %}Job Detail{% endblock %}  
  4.   
  5. {% block content %}  
  6.     <h1>Job Detail</h1>  
  7.   
  8.     <div class="job">  
  9.         <div class="title">  
  10.             {{ job.job_title }}  
  11.             -  
  12.             {{ job.location }}  
  13.         </div>  
  14.         <div class="posted">  
  15.             Posted: {{ job.pub_date|date:"d-M-Y" }}  
  16.         </div>  
  17.         <div class="description">  
  18.             {{ job.job_description }}  
  19.         </div>  
  20.     </div>  
  21. {% endblock %}  
{% extends "jobs/base.html" %}

{% block title %}Job Detail{% endblock %}

{% block content %}
    <h1>Job Detail</h1>

    <div class="job">
        <div class="title">
            {{ job.job_title }}
            -
            {{ job.location }}
        </div>
        <div class="posted">
            Posted: {{ job.pub_date|date:"d-M-Y" }}
        </div>
        <div class="description">
            {{ job.job_description }}
        </div>
    </div>
{% endblock %}
        `-- job_list.html

  1. {% extends "jobs/base.html"  %}  
  2. {% block title %}Job List{% endblock %}  
  3.   
  4. {% block content %}  
  5.         <h1>Job List</h1>  
  6.         <ul>  
  7.         {% for job in object_list %}  
  8.                 <li><a href="{{ job.id }}">{{ job.job_title }}</a></li>  
  9.         {% endfor %}  
  10.         </ul>  
  11. {% endblock %}  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值