个人知识管理站

分享个人生活、工作、学习过程中各种所学、所见、所闻,有趣的、好玩的、技术积累等各方面的内容。

您尚未登录。

公告

不积跬步无以至千里,不积小流无以成江海,网址:www.itecfun.com

#2 2016-05-30 19:18:03

xuyg
管理员
注册时间: 2015-01-21
帖子: 667

Re: 重拾Python Django web

models.py 文件

# coding:utf8
from django.db import models

class Book(models.Model):
   
    name = models.CharField(max_length=255)
    title = models.CharField(max_length=255)
    price = models.IntegerField()
    ...
   
class Category(models.Model):
   
    CATEGORY_CHOICES = (
        ('00', 'English'),
        ('01', 'Computer'),
    )
   
    book = models.ForeignKey(Book)
    category = models.CharField(max_length=255, choices=CATEGORY_CHOICES)
    remark = models.CharField(max_length=255)
    ...

admin.py 文件(以 category 为例)

# coding: utf8
from django.contrib import admin
from django import forms

from .models import Category

class CategoryAdmin(admin.ModelAdmin):

    search_fileds = ('book__name', 'book__title', 'book__price', 'category')  # 设置搜索栏范围,如果有外键,要注明外键的哪个字段,双下划线
    list_display = ('book', 'category')  # 在页面上显示的字段,若不设置则显示 models.py 中 __unicode__(self) 中所返回的值
    list_display_links = ('category')  # 设置页面上哪个字段可单击进入详细页面
    fields = ('category', 'book')  # 设置添加/修改详细信息时,哪些字段显示,在这里 remark 字段将不显示
   
admin.site.register(Category, CategoryAdmin)

[说明]
在使用 Django admin 系统中的搜索时可能会出现“related Field has invalid lookup: icontains”错误,主要原因是外键查询是需要指定相应的字段的。外键不应该只是一个model,而该是另一个表的明确的一个字段。所以我们需要指定特定的字段 "本表外键字段__外键所在表需查询字段"。

离线

#3 2016-05-31 09:48:11

xuyg
管理员
注册时间: 2015-01-21
帖子: 667

Re: 重拾Python Django web

django错误信息以及解决方法,有需要的朋友可以参考下。

1、错误信息:You're using the Django "sites framework" without having set the SITE_ID setting. Create a site in your database and set the SITE_ID setting to fix this error.
原因:settings.py里# Application definition中添加了'django.contrib.sites'模块后需要设置SITE_ID
处理:在settings.py里添加配置:SITE_ID = 1

2、错误信息:(1146, "Table 'django_db.django_site' doesn't exist")
原因:settings.py里# Application definition中添加了'django.contrib.sites'模块而没有创建相应的表
解决:python manage.py syncdb

3、访问html时提示UnicodeDecodeErroror等编码错误
解决:a、在数据库连接语句上添加:charset='utf8',对中文支持好一点。例如:conn=MySQLdb.connect(host="localhost", user="me", passwd="secret", db="mydb", charset='utf8')"
b、在html文件中, 要加,否则如果数据库中的数据有汉字,访问html文件时就有可能会抛出编码异常问题。

离线

#4 2016-05-31 13:41:43

xuyg
管理员
注册时间: 2015-01-21
帖子: 667

Re: 重拾Python Django web

django从数据库导出数据到excel表 (2012-10-24 14:21:40)转载▼
标签: python 杂谈    分类: 计算机技术
def exportAgencyCustomers(request):
    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment;filename=export_agencycustomer.xls'
    wb = xlwt.Workbook(encoding = 'utf-8')
    sheet = wb.add_sheet(u'订单')
    #1st line   
    sheet.write(0,0, '经销商编码')
    sheet.write(0,1, '经销商名称')
    sheet.write(0,2, '终端医院编码')
    sheet.write(0,3, '终端医院名称')
   
    row = 1
    for agencycustomer in AgencyCustomer.objects.all():
        sheet.write(row,0, agencycustomer.agency.cCusCode)
        sheet.write(row,1, agencycustomer.agency.cCusName)
        sheet.write(row,2, agencycustomer.cCusCode)
        sheet.write(row,3, agencycustomer.cCusName)
        row=row + 1
       
    output = StringIO.StringIO()
    wb.save(output)
    output.seek(0)
    response.write(output.getvalue())
    return response

离线

#5 2016-05-31 13:42:28

xuyg
管理员
注册时间: 2015-01-21
帖子: 667

Re: 重拾Python Django web

使用django-grappelli改善默认的django-admin后台

作者:    liuzemin
时间:    2011-1-25
目录

1   说明
2   环境
3   安装
3.1   安装django
3.2   安装django-greppelli
4   配置
4.1   配置seetings.py
4.2   配置urls.py
4.3   配置grapeelli静态文件目录
5   启动
5.1   启用admin管理后台
5.2   配置启动参数,指定的adminmedia到grapelli静态文件目录
6   其他资料
1   说明
django-grappelli是django admin后台管理第三方美化插件,前端采用jquery等开发,美化后的界面,请移步(http://code.google.com/p/django-grappelli/wiki/screenshots )查看

2   环境
以下是我本机的测试环境:

Debian(lxde) Python:2.5.2 Django1.2.4 django-grappelli2.3
3   安装
3.1   安装django
略过(这个应该大家都会吧)

移步django官网下载,里面有详细的安装说明

http://www.djangoproject.com/download/

3.2   安装django-greppelli
从code-google下载django-grappelli对应的版本 ( http://code.google.com/p/django-grappel … loads/list ),安装略过
如果安装了python的包管理器(setuptools)的话,采用easy_install -Z django-grappelli进行安装
4   配置
4.1   配置seetings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '/tmp/demo2.db', # Or path to database file if using sqlite3.#此处根据系统的不同指定名称目录,windows下直接使用绝对路径也可
'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.
}
} INSTALLED_APPS = (
'grappelli',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
4.2   配置urls.py
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^demo2/', include('demo2.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^grappelli/',include('grappelli.urls')), #添加url映射
(r'^admin/', include(admin.site.urls)),
)
4.3   配置grapeelli静态文件目录
将安装好的grepeeli目录下的media复制到你项目位置或者其他指定位置

例如我的系统在:/usr/lib/python2.5/site-packages/django_grappelli-2.3-py2.5.egg/grappelli/media,windows下在c盘python对应版本目录

linux下使用复制命令到指定位置

cp -R /usr/lib/python2.5/site-packages/django_grappelli-2.3-py2.5.egg/grappelli/media /home/alex/test/demograpelli/static/

windows下自行复制site-packages下此插件对应的media目录到指定位置

5   启动
5.1   启用admin管理后台
使用python manage.py syncdb命令创建admin后台数据库,按照向导输入用户名邮箱及密码信息创建即可

输入完后可以使用python manage.py runserver启动服务

输入127.0.0.1:8000/admin/查看是否后台已有admin login界面,默认还是django自带的

5.2   配置启动参数,指定的adminmedia到grapelli静态文件目录
使用

python manage.py runserver 192.168.17.235:8000 --adminmedia=/home/alex/test/demograpelli/static/

启动服务,adminmedia的目录根据个人系统设定相对路径即可,启动服务后,重新打开127.0.0.1:8000/admin/查看既有了grappelli后台管理了

6   其他资料
关于此django插件的详细资料,请参考:http://readthedocs.org/docs/django-grappelli/en/latest/index.html

demo下载: http://www.zeuux.org/group/django/file/content/273/

离线

#6 2016-06-06 17:56:38

xuyg
管理员
注册时间: 2015-01-21
帖子: 667

Re: 重拾Python Django web

Django升级1.9.6出现的中文本地化bug
新版本的django包版本中只有zh_Hans目录,没有zh_CN,把zh_Hans目录复制一个zh_CN就Ok了

离线

#7 2016-06-14 16:46:12

xuyg
管理员
注册时间: 2015-01-21
帖子: 667

Re: 重拾Python Django web

离线

#8 2016-06-14 16:47:28

xuyg
管理员
注册时间: 2015-01-21
帖子: 667

Re: 重拾Python Django web

django-import-export
Installation and configuration

django-import-export is available on the Python Package Index (PyPI), so it can be installed with standard Python tools like pip or easy_install:

$ pip install django-import-export

Alternatively, you can install the git repository directly to obtain the development version:

$ pip install -e git+https://github.com/django-import-export/django-import-export.git#egg=django-import-export

Now, you’re good to go, unless you want to use django-import-export from the admin as well. In this case, you need to add it to your INSTALLED_APPS and let Django collect its static files.

# settings.py
INSTALLED_APPS = (
    ...
    'import_export',
)
$ python manage.py collectstatic

All prequisites are set up! See Getting started to learn how to use django-import-export in your project.

Settings
You can use the following directives in your settings file:

IMPORT_EXPORT_USE_TRANSACTIONS

Global setting controls if resource importing should use database transactions. Default is False.

IMPORT_EXPORT_SKIP_ADMIN_LOG

Global setting controls if creating log entries for the admin changelist should be skipped when importing resource. The skip_admin_log attribute of ImportMixin is checked first, which defaults to None. If not found, this global option is used. This will speed up importing large datasets, but will lose changing logs in the admin changelist view. Default is False.

IMPORT_EXPORT_TMP_STORAGE_CLASS

Global setting for the class to use to handle temporary storage of the uploaded file when importing from the admin using an ImportMixin. The tmp_storage_class attribute of ImportMixin is checked first, which defaults to None. If not found, this global option is used. Default is
TempFolderStorage.
Example app
There’s an example application that showcases what django-import-export can do. You can run it via:

cd tests
./manage.py runserver

Username and password for admin are admin and password.

离线

#9 2016-06-16 09:42:21

xuyg
管理员
注册时间: 2015-01-21
帖子: 667

Re: 重拾Python Django web

django-import-export
安装步骤 经过实践发现该安装步骤在自己的电脑上装不上去,直接到github上下载zip包,把import_export文件夹拷贝到项目根目录下,再在按相关配置配即可。

如何使用

离线

#10 2016-06-17 12:27:20

xuyg
管理员
注册时间: 2015-01-21
帖子: 667

Re: 重拾Python Django web

问题:(1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DEBUG.


settings.py 文件如下:

DEBUG = True

TEMPLATE_DEBUG = DEBUG

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'myapp/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'debug': DEBUG,
            'DEBUG': DEBUG,
            'TEMPLATE_DEBUG': DEBUG
        },
    }, ]

修改为:
注释或删除 TEMPLATE_DEBUG = DEBUG

修改 TEMPLATES 如下

DEBUG = True

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'debug': DEBUG,
        },
    },
]

离线

#11 2016-06-17 14:13:56

xuyg
管理员
注册时间: 2015-01-21
帖子: 667

Re: 重拾Python Django web

Django 部署
参考1
参考2

注意个软件版本需要相适应

已配置成功的软件环境如下:
Apache:httpd-2.4.20-x86-r2-VC9
Python:2.7.9 win32
Django:1.9.6
mod_wsgi:mod_wsgi-4.4.23+ap24vc9-cp27-cp27m-win32

离线

页脚

©2019 YG Wang 备案号: 赣ICP备19010196号-1