最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【记录】基于通过pip安装官网Django后,折腾第二个Django的app

Django crifan 4585浏览 0评论

已经折腾完第一个app了,现在接着参考:

Writing your first Django app, part 2

去折腾第二个app:


1.打开

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp\firstApp\settings.py

添加admin:

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

去cmd中运行:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py syncdb
Creating tables ...
Creating table django_admin_log
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

修改E:\Dev_Root\WebServer\Django\fisrtApp\firstApp\firstApp\urls.py为:

from django.conf.urls import patterns, include, url

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

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'firstApp.views.home', name='home'),
    # url(r'^firstApp/', include('firstApp.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)),
)

2.另外开个cmd去运行服务器:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py runserver
Validating models...

0 errors found
Django version 1.4.1, using settings 'firstApp.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[14/Oct/2012 22:09:42] "GET /admin/ HTTP/1.1" 200 1896

然后再去打开对应的admin页面,就可以看到登录界面了:

django admin ui

登录后:

site admin UI

3.新建:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp\polls\admin.py

内容为:

from polls.models import Poll
from django.contrib import admin

admin.site.register(Poll)

关闭旧的server,重开cmd,重新运行server:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py runserver
Validating models...

0 errors found
Django version 1.4.1, using settings 'firstApp.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

刷新http://127.0.0.1:8000/admin/即可看到新的polls的UI了:

added polls admin ui

点击Polls,进入change的ui:

click polls to see change ui

点击后可以编辑:

change poll

修改后,点击history,可以看到历史记录:

see history

4.把

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp\polls\admin.py

相关部分改为:

#admin.site.register(Poll)
class PollAdmin(admin.ModelAdmin):
    fields = ['pub_date', 'question']

admin.site.register(Poll, PollAdmin)

然后刷新页面可以看到变化:

first date then question

再变为:

# #admin.site.register(Poll)

# class PollAdmin(admin.ModelAdmin):
    # fields = ['pub_date', 'question']

# admin.site.register(Poll, PollAdmin)

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date']}),
    ]

admin.site.register(Poll, PollAdmin)

效果为:

fields set UI

再改为:

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    ]

admin.site.register(Poll, PollAdmin)

效果为:

show hide

5.再给admin.py添加代码:

from polls.models import Choice

admin.site.register(Choice)

然后效果为:

can see choices

 

去添加choice:

add choice

然后把代码改为:

from polls.models import Poll
from django.contrib import admin

from polls.models import Choice

#-------------------------------------------------------------------------------
# admin.site.register(Choice)
class ChoiceInline(admin.StackedInline):
    model = Choice
    extra = 3

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    ]
    inlines = [ChoiceInline]

admin.site.register(Poll, PollAdmin)

#-------------------------------------------------------------------------------

# #admin.site.register(Poll)

# class PollAdmin(admin.ModelAdmin):
    # fields = ['pub_date', 'question']

# admin.site.register(Poll, PollAdmin)

# class PollAdmin(admin.ModelAdmin):
    # fieldsets = [
        # (None,               {'fields': ['question']}),
        # ('Date information', {'fields': ['pub_date']}),
    # ]

# admin.site.register(Poll, PollAdmin)

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    ]

admin.site.register(Poll, PollAdmin)

结果由于重复出现了两个

admin.site.register(Poll, PollAdmin)

所以报错了:

AlreadyRegistered at /admin/polls/
The model Poll is already registeredRequest Method: GET 
Request URL: http://127.0.0.1:8000/admin/polls/ 
Django Version: 1.4.1 
Exception Type: AlreadyRegistered 
Exception Value: The model Poll is already registered 
Exception Location: E:\dev_install_root\Python27\lib\site-packages\django\contrib\admin\sites.py in register, line 80 
Python Executable: E:\dev_install_root\Python27\python.exe 
Python Version: 2.7.2 
Python Path: ['E:\\Dev_Root\\WebServer\\Django\\fisrtApp\\firstApp',
 'E:\\dev_install_root\\Python27\\lib\\site-packages\\distribute-0.6.28-py2.7.egg',
 'C:\\Windows\\system32\\python27.zip',
 'E:\\dev_install_root\\Python27\\DLLs',
 'E:\\dev_install_root\\Python27\\lib',
 'E:\\dev_install_root\\Python27\\lib\\plat-win',
 'E:\\dev_install_root\\Python27\\lib\\lib-tk',
 'E:\\dev_install_root\\Python27',
 'E:\\dev_install_root\\Python27\\lib\\site-packages',
 'E:\\dev_install_root\\Python27\\lib\\site-packages\\setuptools-0.6c11-py2.7.egg-info'] 
Server time: Sun, 14 Oct 2012 22:38:41 +0800 

Traceback Switch to copy-and-paste view
E:\dev_install_root\Python27\lib\site-packages\django\core\handlers\base.py in get_response                     if hasattr(request, "urlconf"):                        # Reset url resolver with a custom urlconf.                        urlconf = request.urlconf                        urlresolvers.set_urlconf(urlconf)                        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)                    callback, callback_args, callback_kwargs = resolver.resolve(                            request.path_info) ...                    # Apply view middleware                    for middleware_method in self._view_middleware:                        response = middleware_method(request, callback, callback_args, callback_kwargs)                        if response:                            break
▶ Local vars 
Variable Value 
settings <django.conf.LazySettings object at 0x0000000002591DD8> 
middleware_method <bound method MessageMiddleware.process_request of <django.contrib.messages.middleware.MessageMiddleware object at 0x000000000331F9B0>> 
self <django.core.handlers.wsgi.WSGIHandler object at 0x00000000032ABDA0> 
request "<WSGIRequest\npath:/admin/polls/,\nGET:<QueryDict: {}>,\nPOST:<QueryDict: {}>,\nCOOKIES:{'csrftoken': 'pZqqwmY5XFbdHPz1el5MU5CyGgmQAFjA',\n 'sessionid': '568f8b2f1ee7fb3b7d443834f9acd15e'},\nMETA:{'ALLUSERSPROFILE': 'C:\\\\ProgramData',\n 'AMDAPPSDKROOT': 'C:\\\\Program Files (x86)\\\\AMD APP\\\\',\n 'ANT_HOME': 'E:\\\\Dev_Root\\\\docbook\\\\tools\\\\ant\\\\apache-ant-1.8.4',\n 'APPDATA': 'C:\\\\Users\\\\Administrator\\\\AppData\\\\Roaming',\n 'COMMONPROGRAMFILES': 'C:\\\\Program Files\\\\Common Files',\n 'COMMONPROGRAMFILES(X86)': 'C:\\\\Program Files (x86)\\\\Common Files',\n 'COMMONPROGRAMW6432': 'C:\\\\Program Files\\\\Common Files',\n 'COMPUTERNAME': 'NYBDHB7EB3XEHP6',\n 'COMSPEC': 'C:\\\\Windows\\\\system32\\\\cmd.exe',\n 'CONTENT_LENGTH': '',\n 'CONTENT_TYPE': 'text/plain',\n 'DJANGO_SETTINGS_MODULE': 'firstApp.settings',\n 'FOP_HOME': 'E:/Dev_Root/docbook/tools/fop-1.0',\n 'FP_NO_HOST_CHECK': 'NO',\n 'GATEWAY_INTERFACE': 'CGI/1.1',\n 'HOMEDRIVE': 'C:',\n 'HOMEPATH': '\\\\Users\\\\Administrator',\n 'HTTP_ACCEPT': 'application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*',\n 'HTTP_ACCEPT_ENCODING': 'gzip, deflate',\n 'HTTP_ACCEPT_LANGUAGE': 'zh-CN',\n 'HTTP_CONNECTION': 'Keep-Alive',\n 'HTTP_COOKIE': 'csrftoken=pZqqwmY5XFbdHPz1el5MU5CyGgmQAFjA; sessionid=568f8b2f1ee7fb3b7d443834f9acd15e',\n 'HTTP_HOST': '127.0.0.1:8000',\n 'HTTP_REFERER': 'http://127.0.0.1:8000/admin/polls/choice/add/',\n 'HTTP_USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)',\n 'JAVA_HOME': 'C:\\\\Program Files (x86)\\\\Java\\\\jre7',\n 'LOCALAPPDATA': 'C:\\\\Users\\\\Administrator\\\\AppData\\\\Local',\n 'LOGONSERVER': '\\\\\\\\NYBDHB7EB3XEHP6',\n 'NUMBER_OF_PROCESSORS': '4',\n 'OS': 'Windows_NT',\n 'PATH': 'C:\\\\Program Files\\\\Common Files\\\\Microsoft Shared\\\\Windows Live;C:\\\\Program Files (x86)\\\\Common Files\\\\Microsoft Shared\\\\Windows Live;C:\\\\Program Files (x86)\\\\AMD APP\\\\bin\\\\x86_64;C:\\\\Program Files (x86)\\\\AMD APP\\\\bin\\\\x86;C:\\\\Windows\\\\system32;C:\\\\Windows;C:\\\\Windows\\\\System32\\\\Wbem;C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\;C:\\\\Program Files (x86)\\\\ATI Technologies\\\\ATI.ACE\\\\Core-Static;C:\\\\Program Files (x86)\\\\Windows Live\\\\Shared;E:\\\\dev_install_root\\\\TortoiseSVN\\\\bin;c:\\\\Program Files (x86)\\\\Microsoft SQL Server\\\\100\\\\Tools\\\\Binn\\\\;c:\\\\Program Files\\\\Microsoft SQL Server\\\\100\\\\Tools\\\\Binn\\\\;c:\\\\Program Files\\\\Microsoft SQL Server\\\\100\\\\DTS\\\\Binn\\\\;E:\\\\Dev_Root\\\\docbook\\\\tools\\\\libxml\\\\bin;E:/Dev_Root/docbook/tools/fop-1.0;C:\\\\Program Files (x86)\\\\Java\\\\jre7\\\\bin;E:\\\\Dev_Root\\\\docbook\\\\tools\\\\ant\\\\apache-ant-1.8.4\\\\bin;E:\\\\dev_install_root\\\\HTML Help Workshop;D:\\\\Program Files\\\\7-Zip;E:\\\\dev_install_root\\\\Python27;E:\\\\dev_install_root\\\\Python27\\\\Scripts;',\n 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC',\n 'PATH_INFO': u'/admin/polls/',\n 'PROCESSOR_ARCHITECTURE': 'AMD64',\n 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 37 Stepping 5, GenuineIntel',\n 'PROCESSOR_LEVEL': '6',\n 'PROCESSOR_REVISION': '2505',\n 'PROGRAMDATA': 'C:\\\\ProgramData',\n 'PROGRAMFILES': 'C:\\\\Program Files',\n 'PROGRAMFILES(X86)': 'C:\\\\Program Files (x86)',\n 'PROGRAMW6432': 'C:\\\\Program Files',\n 'PROMPT': '$P$G',\n 'PSMODULEPATH': 'C:\\\\Windows\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\Modules\\\\',\n 'PUBLIC': 'C:\\\\Users\\\\Public',\n 'QUERY_STRING': '',\n 'REMOTE_ADDR': '127.0.0.1',\n 'REMOTE_HOST': '',\n 'REQUEST_METHOD': 'GET',\n 'RUN_MAIN': 'true',\n 'SCRIPT_NAME': u'',\n 'SERVER_NAME': 'NYBDHB7EB3XEHP6',\n 'SERVER_PORT': '8000',\n 'SERVER_PROTOCOL': 'HTTP/1.1',\n 'SERVER_SOFTWARE': 'WSGIServer/0.1 Python/2.7.2',\n 'SESSIONNAME': 'Console',\n 'SYSTEMDRIVE': 'C:',\n 'SYSTEMROOT': 'C:\\\\Windows',\n 'TEMP': 'C:\\\\Users\\\\ADMINI~1\\\\AppData\\\\Local\\\\Temp',\n 'TMP': 'C:\\\\Users\\\\ADMINI~1\\\\AppData\\\\Local\\\\Temp',\n 'USERDOMAIN': 'NYBDHB7EB3XEHP6',\n 'USERNAME': 'Administrator',\n 'USERPROFILE': 'C:\\\\Users\\\\Administrator',\n 'VBOX_INSTALL_PATH': 'E:\\\\dev_install_root\\\\Oracle\\\\VirtualBox\\\\',\n 'VS100COMNTOOLS': 'C:\\\\Program Files (x86)\\\\Microsoft Visual Studio 10.0\\\\Common7\\\\Tools\\\\',\n 'WINDIR': 'C:\\\\Windows',\n 'WINDOWS_TRACING_FLAGS': '3',\n 'WINDOWS_TRACING_LOGFILE': 'C:\\\\BVTBin\\\\Tests\\\\installpackage\\\\csilogfile.log',\n '_DFX_INSTALL_UNSIGNED_DRIVER': '1',\n 'wsgi.errors': <open file '<stderr>', mode 'w' at 0x0000000001E5E1E0>,\n 'wsgi.file_wrapper': <class wsgiref.util.FileWrapper at 0x0000000002CDFE28>,\n 'wsgi.input': <socket._fileobject object at 0x00000000032BD750>,\n 'wsgi.multiprocess': False,\n 'wsgi.multithread': True,\n 'wsgi.run_once': False,\n 'wsgi.url_scheme': 'http',\n 'wsgi.version': (1, 0)}>" 
exceptions <module 'django.core.exceptions' from 'E:\dev_install_root\Python27\lib\site-packages\django\core\exceptions.pyc'> 
resolver <RegexURLResolver firstApp.urls (None:None) ^/> 
urlresolvers <module 'django.core.urlresolvers' from 'E:\dev_install_root\Python27\lib\site-packages\django\core\urlresolvers.pyc'> 
response None 
urlconf 'firstApp.urls' 

E:\dev_install_root\Python27\lib\site-packages\django\core\urlresolvers.py in resolve         return self._app_dict[language_code]    def resolve(self, path):        tried = []        match = self.regex.search(path)        if match:            new_path = path[match.end():]            for pattern in self.url_patterns: ...                try:                    sub_match = pattern.resolve(new_path)                except Resolver404, e:                    sub_tried = e.args[0].get('tried')                    if sub_tried is not None:                        tried.extend([[pattern] + t for t in sub_tried])
▶ Local vars 
Variable Value 
path u'/admin/polls/' 
self <RegexURLResolver firstApp.urls (None:None) ^/> 
new_path u'admin/polls/' 
tried [] 
match <_sre.SRE_Match object at 0x000000000331E718> 

E:\dev_install_root\Python27\lib\site-packages\django\core\urlresolvers.py in url_patterns             return self._urlconf_module        except AttributeError:            self._urlconf_module = import_module(self.urlconf_name)            return self._urlconf_module    @property    def url_patterns(self):        patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ...        try:            iter(patterns)        except TypeError:            raise ImproperlyConfigured("The included urlconf %s doesn't have any patterns in it" % self.urlconf_name)        return patterns

所以,重新改为:

from polls.models import Poll
from django.contrib import admin

from polls.models import Choice

#-------------------------------------------------------------------------------
admin.site.register(Choice)


#-------------------------------------------------------------------------------

# #admin.site.register(Poll)

# class PollAdmin(admin.ModelAdmin):
    # fields = ['pub_date', 'question']

# admin.site.register(Poll, PollAdmin)

# class PollAdmin(admin.ModelAdmin):
    # fieldsets = [
        # (None,               {'fields': ['question']}),
        # ('Date information', {'fields': ['pub_date']}),
    # ]

# admin.site.register(Poll, PollAdmin)

# class PollAdmin(admin.ModelAdmin):
    # fieldsets = [
        # (None,               {'fields': ['question']}),
        # ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    # ]

# admin.site.register(Poll, PollAdmin)

class ChoiceInline(admin.StackedInline):
    model = Choice
    extra = 3

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    ]
    inlines = [ChoiceInline]

admin.site.register(Poll, PollAdmin)

结果就正常了:

added sub choice

然后改为:

#class ChoiceInline(admin.StackedInline):
class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3

就变成了:

TabularInline UI

6.再去添加出来list_display:

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    ]
    inlines = [ChoiceInline]
    list_display = ('question', 'pub_date')
    list_display = ('question', 'pub_date', 'was_published_recently')

然后效果为:

3 fields

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp\polls\models.py

改为:

import datetime;
from django.utils import timezone;
from django.db import models

# Create your models here.
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_recently(self):
        return self.pub_date >= (timezone.now() - datetime.timedelta(days=1));
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

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

然后E:\Dev_Root\WebServer\Django\fisrtApp\firstApp\polls\admin.py

改为:

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    ]
    inlines = [ChoiceInline]
    list_display = ('question', 'pub_date')
    list_display = ('question', 'pub_date', 'was_published_recently')
    list_filter = ['pub_date']

效果为:

filter by date

再添加search:

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    ]
    inlines = [ChoiceInline]
    list_display = ('question', 'pub_date')
    list_display = ('question', 'pub_date', 'was_published_recently')
    list_filter = ['pub_date']
    search_fields = ['question']

效果为:

added search

 

添加上date:

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    ]
    inlines = [ChoiceInline]
    list_display = ('question', 'pub_date')
    list_display = ('question', 'pub_date', 'was_published_recently')
    list_filter = ['pub_date']
    search_fields = ['question']
    date_hierarchy = 'pub_date'

效果为:

date hierarchy

7.把

E:\dev_install_root\Python27\Lib\site-packages\django\contrib\admin\templates\admin\base_site.html

拷贝到

E:\Dev_Root\WebServer\Django\crifan\mytemplates\admin

中。

然后修改E:\Dev_Root\WebServer\Django\fisrtApp\firstApp\firstApp\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.
    "E:/Dev_Root/WebServer/Django/crifan/mytemplates"
)

关于查找django安装路径,也去试了试:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>python
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path = sys.path[1:];
>>> import django
>>> print(django.__path__);
['E:\\dev_install_root\\Python27\\lib\\site-packages\\django']
>>>

另外,修改了logo:

crifan logo

至此,第二个app就结束了。

转载请注明:在路上 » 【记录】基于通过pip安装官网Django后,折腾第二个Django的app

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (2)

  1. 呵呵,兄弟,你这个站点好奇怪啊。
    evilbinary10年前 (2014-10-07)回复
87 queries in 0.195 seconds, using 22.22MB memory