设为首页 收藏本站
查看: 986|回复: 0

[经验分享] Python-Django中的那些命令

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2014-5-3 17:42:18 | 显示全部楼层 |阅读模式
# 在下载好的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
#
# 模型定义特殊字段定义(后面一些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)   // 引用信息(外键)
#
# 模型检测 (需要在settings.py中注册此app)
python3 manage.py validate
#
# 模型生成sql语句查看
python3 manage.py sqlall modelname (app的名字)
#
# 模型生成到db 要生成用户之前必须做这一步
python3 manage.py syncdb
#
# 建立管理超级员
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序号
#
# 定义模板路径
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,
    })
#
# 其他解决方案
配置文件中
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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-18548-1-1.html 上篇帖子: Python中set集合的整理 下篇帖子: python的分布式任务并行处理框架Jug简单使用
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表