jang

阅读 / 问答 / 标签

django drf_yasg 非restful风格的api怎么在swagger上展示?

PS: 个人深感python开发者社区氛围比安卓/ios/java差多了。不过,这也许是个机会~前提: 本人开发环境是mac10.14.4,Python3.7.2django-rest-swagger vs drf-yasg百度google各种查询帖子,python中生成自动化API文档绝大部分用的都是django-rest-swagger库,然而此库作者表示在2019-06-04已停止更新,而且此库需要的第三方版本库是:Django 1.8+Django REST framework 3.5.1+Python 2.7, 3.5, 3.6换句话说,django-rest-swagger并不支持Python3.7的环境,所以本人选择了drf-yasg库,它需要的第三方版本库是:Django Rest Framework: 3.8, 3.9Django: 1.11, 2.1, 2.2Python: 2.7, 3.5, 3.6, 3.7drf-yasg快速上手安装pip install -U drf-yasg11在settings.py声明app,并将debug设置为trueINSTALLED_APPS = [ ... "drf_yasg", ...]DEBUG = True12345671234567在根url.py添加scheme_viewfrom rest_framework import permissionsfrom drf_yasg.views import get_schema_viewfrom drf_yasg import openapischema_view = get_schema_view( openapi.Info( title="API文档", default_version="v1.0.0", contact=openapi.Contact(name="联系开发者", email="your email"), ), permission_classes=(permissions.AllowAny,),)urlpatterns = [ ... url("swagger", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui"),]12345678910111213141516171234567891011121314151617踩坑1. 找不到drf目录下的静态文件解决方案:测试环境settings.py中的DEBUG设置为true(方便生成api文档), 生产环境设置为False。在python环境中,如果使用drf库生成API文档,需要将DEBUG设置为true,否则找不到静态文件。

《DjangoByExample》pdf下载在线阅读,求百度网盘云资源

《Django By Example》(Antonio Mele)电子书网盘下载免费在线阅读资源链接:链接:https://pan.baidu.com/s/1kQe_Jj9b55RbKRPaaIsB_g 密码:4ke3书名:Django By Example作者:Antonio Mele豆瓣评分:9.3出版社:Packt Publishing出版年份:2015-11-30页数:474内容简介:Learn Django by building four fully-functional, real-world web applications from scratchDevelop powerful web applications quickly using the best coding practicesIntegrate other technologies into your application with clear, step-by-step explanations and comprehensive example code作者简介:Antonio Mele holds an MSc in Computer Science. He has been developing Django projects since 2006 and leads the django.es Spanish Django community. He has founded Zenx IT, a technology company that creates web applications for clients of several industries. Antonio has also worked as a CTO for several technology-based start-ups. His father inspired his passion for computers and programming.

nerve-jangling 是什么意思

安静的意思

我有一点点Python的基本知识(非常基本) ,想学一下Django, 请推荐几本入门的Django教程,谢谢

看看这个免费教程,图片截不完全,内容非常丰富,吐血推荐刘江的Django教程

trojangames 是什么

特洛伊游戏(trojangames).给我加分哦!

django如何避免sql注入

什么是SQL注入?所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令。具体来说,它是利用现有应用程序,将(恶意的)SQL命令注入到后台数据库引擎执行的能力,它可以通过在Web表单中输入(恶意)SQL语句得到一个存在安全漏洞的网站上的数据库,而不是按照设计者意图去执行SQL语句。比如先前的很多影视网站泄露VIP会员密码大多就是通过WEB表单递交查询字符暴出的,这类表单特别容易受到SQL注入式攻击。比如现在数据库中有一个front_user表,表结构如下:class User(models.Model): telephone = models.CharField(max_length=11) username = models.CharField(max_length=100) password = models.CharField(max_length=100)然后我们使用原生sql语句实现以下需求:1. 实现一个根据用户id获取用户详情的视图。示例代码如下:def index(request): user_id = request.GET.get("user_id") cursor = connection.cursor() cursor.execute("select id,username from front_user where id=%s" % user_id) rows = cursor.fetchall() for row in rows: print(row) return HttpResponse("success")这样表面上看起来没有问题。但是如果用户传的user_id是等于1 or 1=1,那么以上拼接后的sql语句为:select id,username from front_user where id=1 or 1=1以上sql语句的条件是id=1 or 1=1,只要id=1或者是1=1两个有一个成立,那么整个条件就成立。毫无疑问1=1是肯定成立的。因此执行完以上sql语句后,会将front_user表中所有的数据都提取出来。2. 实现一个根据用户的username提取用户的视图。示例代码如下:def index(request): username = request.GET.get("username") cursor = connection.cursor() cursor.execute("select id,username from front_user where username="%s"" % username) rows = cursor.fetchall() for row in rows: print(row) return HttpResponse("success")这样表面上看起来也没有问题。但是如果用户传的username是zhiliao" or "1=1,那么以上拼接后的sql语句为:select id,username from front_user where username="zhiliao" or "1=1"以上sql语句的条件是username="zhiliao"或者是一个字符串,毫无疑问,字符串的判断是肯定成立的。因此会将front_user表中所有的数据都提取出来。sql注入防御,归类起来主要有以下几点:以上便是sql注入的原理。他通过传递一些恶意的参数来破坏原有的sql语句以便达到自己的目的。当然sql注入远远没有这么简单,我们现在讲到的只是冰山一角。那么如何防御sql注入呢?1. 永远不要信任用户的输入。对用户的输入进行校验,可以通过正则表达式,或限制长度;对单引号和 双"-"进行转换等。2. 永远不要使用动态拼装sql,可以使用参数化的sql或者直接使用存储过程进行数据查询存取。比如:def index(request): user_id = "1 or 1=1" cursor = connection.cursor() cursor.execute("select id,username from front_user where id=%s",(user_id,)) rows = cursor.fetchall() for row in rows: print(row) return HttpResponse("success")3. 永远不要使用管理员权限的数据库连接,为每个应用使用单独的权限有限的数据库连接。4. 不要把机密信息直接存放,加密或者hash掉密码和敏感的信息。5. 应用的异常信息应该给出尽可能少的提示,最好使用自定义的错误信息对原始错误信息进行包装。总结:1. 在网页中利用sql语句进行注入攻击,网页获取用户输入参数,但有些恶意用户利用特殊sql语句上传参数,后端获取参数若不对其正确性合法性进行判断,则有可能对数据库造成危害2. get和post上传数据的时候,做好对参数的检查3. 利用Dajngo的ORM可有效避免sql注入,因为Django已经对特殊字符进行转义

为什么某些国外编程爱好者如此推崇 ROR,Django

Ruby On Rails 确实很厉害!我的发展是.net(c#)到ROR到java的Spring经历了三个框架.net和java很相似。开发真的不如ruby快!Ruby极其随意。而且!!效率真的没有网上说的,不如java,单从网页这方面说,ruby在开发和效率上,有过之而无不及。10多万个的详情页,ruby完成的要比java快10多分钟。至于.net目前不了解了,当时只是觉得他在固步自封。

sqlite3常用命令以及django如何操作sqlite3数据库

1、确认sqlite3是否已经安装进去python命令行,执行>>>importsqlite3>>>没有报错,说明sqlite3已经成功安装了2、如何进入sqlite3命令行sqlite3/path/to/dbname直接执行sqlite3 加数据库名即可~sqlite3~/Downloads/django_test/cmdb/db.sqlite3sqlite3SQLiteversion3.14.02016-07-2615:17:14Enter".help"forusagehints.sqlite>3、.tables :查看所有表sqlite>.tablesauth_groupdjango_content_typeauth_group_permissionsdjango_migrationsauth_permissiondjango_sessionauth_userucloud_projectauth_user_groupsucloud_regionauth_user_user_permissionsucloud_uhostdjango_admin_logucloud_zone4、查询表中总的数据条目数selectcount()fromTableName;例如:sqlite>selectcount()fromucloud_zone;11sqlite>selectcount()fromucloud_uhost;147sqlite>selectcount()fromucloud_project;105、执行多条查询语句sqlite>select...>(selectcount(1)fromucloud_uhost)asuhost,...>(selectcount(1)fromucloud_project)asproject,...>(selectcount(1)fromucloud_region)asregion...>;147|10|86、格式化输出您可以使用下列的点命令来格式化输出为本教程下面所列出的格式:sqlite>.headeronsqlite>.modecolumnsqlite>.timeronsqlite>更多命令查看:http://www.runoob.com/sqlite/sqlite-commands.html 二、python如何执行sqlite查询命令python执行sqlite命令的流程:1、cx=sqlite3.connect("db.sqlite3)创建或打开数据库文件,如果数据库文件不存在,则创建,存在,则打开该文件。cx为数据库连接对象,它可以有以下操作: commit()--事务提交 rollback()--事务回滚 close()--关闭一个数据库连接 cursor()--创建一个游标2、cursor=cx.cursor()定义了一个游标。游标对象有以下的操作: execute()--执行sql语句 executemany--执行多条sql语句 close()--关闭游标 fetchone()--从结果中取一条记录 fetchmany()--从结果中取多条记录 fetchall()--从结果中取出多条记录 scroll()--游标滚动 关于对象的方法可以去 Python 主页上查看DB API的详细文档3、cursor.execute("""...select...(selectcount(1)fromucloud_uhost)asuhost...""")cursor.execute(sql语句)是执行sql语句4、cursor.close()关闭游标下面是操作数据库的过程>>>importsqlite3>>>fromdjango.dbimportconnectionscx=sqlite3.connect("/Users/cengchengpeng/Downloads/django_test/cmdb/db.sqlite3")cursor=cx.cursor()>>>cursor<sqlite3.Cursorobjectat0x10b24cb20>>>>cursor.execute("""...select...(selectcount(1)fromucloud_uhost)asuhost,...(selectcount(1)fromucloud_project)asproject,...(selectcount(1)fromucloud_zone)aszone...""")<sqlite3.Cursorobjectat0x10b24cb20>>>>cursor.description((‘uhost‘,None,None,None,None,None,None),(‘project‘,None,None,None,None,None,None),(‘zone‘,None,None,None,None,None,None))>>>columns=[_[0].lower()for_incursor.description]>>>columns[‘uhost‘,‘project‘,‘zone‘]>>>for_incursor:...print_...(147,10,11)>>>results=[dict(zip(columns,_))for_incursor]>>>results>>>results[{‘project‘:10,‘zone‘:11,‘uhost‘:147}]>>>cursor.close()写python脚本,来执行sqlite语句#coding:utf-8fromdjango.dbimportconnectionsdefopen_sql_dict(sql,connection_name=‘default‘):dbs=connections[connection_name]cursor=dbs.cursor()cursor.execute(sql)columns=[_[0].lower()for_incursor.description]results=[dict(zip(columns,_))for_incursor]cursor.close()returnresults这里脚本里面,用到了zip()方法和dict()方法本文出自 “zengestudy” 博客,请务必保留此出处http://zengestudy.blog.51cto.com/1702365/1904680sqlite3常用命令以及django如何操作sqlite3数据库标签:sqlite

教你如何在Django1.6中正确使用Signal

简单回答是: 在其他方法无法使用的情况下, 才最后考虑使用signal.因为新的django开发人员得知signal之后, 往往会很高兴去使用它. 他们在能使用signal的地方就使用signal, 并且这是他们觉得自己是django专家一样. 然而, 像这样编码一段时间后, django项目就会变得异常复杂, 许多内容都纠结在一起无法解开.许多开发者也会将django signal和异步消息列队(例如celery)搞混. signal是同步处理, 因此通过signal调用大处理量的进程时并无法提高性能. 事实上, 将这些需要大处理量的进程移到signal中被视作是一种不好的习惯.1. 何时使用signal以下情况不要使用signal:signal与一个model紧密相关, 并能移到该model的save()时signal能使用model manager代替时signal与一个view紧密相关, 并能移到该view中时以下情况可以使用signal:signal的receiver需要同时修改对多个model时将多个app的相同signal引到同一receiver中处理时在某一model保存之后将cache清除时无法使用其他方法, 但需要一个被调函数来处理某些问题时2. Signal的代替方法使用mod而来manager以下代码演示了当用户创建Event model时, 需要通知管理员, 如果改写model中的post_save(), 则需要添加额外的逻辑来区分用户还是管理员:# myapp/managers.py from django.db import models class EventManager(models.Manager): def create_event(self, title, start, end, creator): event = self.model(title=title, start=start, end=end, creator=creator) event.save() event.notify_admins() return event在model中设置model manager:# myapp/models.py from django.conf import settings from django.core.mail import mail_admins from django.db import models from model_utils.models import TimeStampedModel from .managers import EventManager class Event(TimeStampedModel): STATUS_UNREVIEWED, STATUS_REVIEWED = (0, 1) STATUS_CHOICES = ( (STATUS_UNREVIEWED, "Unreviewed"), (STATUS_REVIEWED, "Reviewed") ) title = models.CharField(max_length=100) start = models.DateTimeField() end = model.dateTimeField() status = models.IntegerField(choices=STATUS_CHOICES, default=STATUS_UNREVIEWED) creator = models.ForeignField(settings.AUTH_USER_MODEL) objects = EventManager() def notify_admins(self): subject = "{user} submitted a new event!".format(user=self.creator.get_full_name()) message = """TITLE: {title} START: {start} END: {end}""".format(title=self.title, start=self.start, end=self.end) mail_admins(subject=subject, message=message, fail_silently=False)在view中使用create_event()代替create()时, 便会通知管理员了.在其他代码中验证model如果你使用pre_save signal来验证某一model, 则应当尝试自己写一个validator取代之. 如果验证是通过ModelForm时, 通过改写clean()实现验证.使用model的save()和delete()如果使用pre_save 或 post_save signal, 如果可以, 则将这些代码移到model的save()方法中.同样如果使用pre_delete 或 post_delete signal, 如果可以, 则将这些代码移到model的delte()方法中.使用其他代码代替signal如果可能, 我们可以将signal的逻辑使用其他帮助程序实现.

Django和Flask这两个框架在设计上各方面有什么优缺点

一、整体设计方面首先,两者都是非常优秀的框架。整体来讲,两者设计的哲学是区别最大的地方。Django提供一站式的解决方案,从模板、ORM、Session、Authentication等等都分配好了,连app划分都做好了,总之,为你做尽量多的事情,而且还有一个killer级的特性,就是它的admin,配合django-suit,后台就出来了,其实最初Django就是由在新闻发布公司工作的人设计的。Flask只提供了一些核心功能,非常简洁优雅。它是一个微框架,其他的由扩展提供,但它的blueprint使它也能够很方便的进行水平扩展。二、路由设计Django的路由设计是采用集中处理的方法,利用正则匹配。Flask也能这么做,但更多的是使用装饰器的形式,这个有优点也有缺点,优点是读源码时看到函数就知道怎么用的,缺点是一旦源码比较长,你要查路由就不太方便了,但这也促使你去思考如何更合理的安排代码。三、应用模块化设计Django的模块化是集成在命令里的,也就是说一开始Django的目标就是为以后玩大了做准备的。每个都是一个独立的模块,为以后的复用提供了便利。Flask通过Blueprint来提供模块化,自己对项目结构划分成不同的模块进行组织。四、配置Django的配置主要还是靠settings.py来做,当然为了Development和Production环境分离,还有一些方法来处理配置。Flask的配置很灵活,有多种方法配置,不同环境的配置也非常方便。五、文档两者都提供了详尽的文档,Flask的文档风格很受我个人喜好,Django的文档也非常优秀,当时用学Django时,就是只看了Django的文档。

如何正确使用 Django Admin

1. Django Admin 不适合最终用户使用Django admin是为管理员设计的, 而不是给最终用户使用的. Django admin的存在是为了方便管理员添加修改删除数据和管理站点任务.2. 列表显示如上图, 因为model的默认文本显示是 xxx object, 所以在admin列表页中默认显示的也是xxx object. 如果希望显示更有用的信息 我们可以进行如下设置:为model写__unicode__()方法如果希望model在列表页中显示更多项, 则需要使用list_display__unicode()__例子: # models.py from django.db import modelsclass Article(models.Model): title = models.CharField(max_length=100) slug = models.CharField(max_length=100) content = models.TextField() is_published = models.BooleanField(default=False) def __unicode__(self): return self.title # admin.py from django.contrib import admin from .models import Article admin.site.register(Article)结果:如果希望显示其他项: # admin.py from django.contrib import admin from .models import Articleclass ArticleAdmin(admin.ModelAdmin): list_display = ("title", "is_published")admin.site.register(Article, ArticleAdmin)结果:3. 为ModelAdmin增加动作我们可以为ModelAdmin增加method或function, 以此使admin界面更符合我们的需求.例如, 我们希望在在admin界面中显示一个明确地URL, 但当我们在model中定义了get_absolute_url()方法后, django admin默认给我们的却是一个与我们想要的URL完全不同的URL. 于是我们可以通过以下方法定义该URL: # admin.py from django.contrib import admin from django.core.urlresolvers import reverse from django.utils.html import format_html from .models import Article class ArticleAdmin(admin.ModelAdmin): list_display = ("title", "is_published",) readonly_fields = ("show_url",) def show_url(self, instance): url = reverse("article_detail", kwargs={"pl": instance.pk}) response = format_html("""<a href="{0}">文章预览preview</a>""", url) return response show_url.short_description = u"文章预览" # 显示HTML tag # 对于用户提交的数据, 永远不要这么设置! show_url.allow_tags = True注意, allow_tags属性, 其默认值是False, 如果错误使用将会带来安全隐患. 如果设置为True, 在admin中会允许显示HTML tag. 因此我们使用的原则是, 对于用户输入的信息, 永远不设置allow_tags=True. 只有当其内容是系统生成, 用户无法修改的时, 才能使用allow_tags=True.4. 不在多用户编辑环境使用list_editabledjango admin为我们提供了在列表页修改model属性的功能, 这样方便管理员一次修改多个属性. 如果管理员只有一个人的话, 那就没问题, 但在多用户环境中时, 却是会存在一个很严重的潜在问题. 因为在list页提交的修改信息, 记录的是位置, 而不是model的主键. 举个例子, 文章列表页默认按照创建顺序逆序排列, 用户A打开文章列表页, 并开始修改, 同时用户B增加了一篇新文章, 此时, 当用户A提交修改后其后的文章信息都会出错.

如何使用Django创建简单的博客

网上不是很多django 创建博客教程,很清楚的

如何使用Django创建简单的博客

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432170876125c96f6cc10717484baea0c6da9bee2be4000

jingle jangle 歌词

歌曲名:jingle jangle歌手:Hot Hot Heat专辑:elevatorWatch your children round the,abandoned well,don"t askme to tell if theyslipped and fell im just asalesman with mysuitcase in hand and thethe perfect plan that should pull me outanother day, another night, another year,another smile, another lie, another tearthis better not be all I gotI never thought "d end up hereJingle jangle that"s thesound of coins spent onuseless toys made foruseless boys I"m just asalesman with mysuitcase in hand there"s aa piece of land that I got my eye onanother day another night another year,another smile, another lie, another tearthis better not be all I gotI never thought I"d end up hereFriday night I"ll raise myglass and say tomorrowthings will change I cantafford to wait but byMonday morning my alarm clock knowshow this story goesand the endings the same as the startanother day another night another year,another smile, another lie, another tearthis better not be all i gotI never thought I"d end up hereanother day another night another year,another smile, another lie, another tearthis better not be all i gotI never thought I"d end up hereWatch your children around theabandoned welldon"t askme to tell if they slipped and fellim just a salesman with mysuitcase in hand there"s aa perfect plan that I"m working on,that im working on,that im working on.http://music.baidu.com/song/14500393

python django怎么读

如果用拼音的话是 zhan gou

django & juliette是哪里牌子鞋

生命是一场懂得,万般姿态,独一无二

把几个名字翻译成韩语:焦玉洁,张华杰,杨晨梦,张雨萌,孙伟娜 再标上英语发音像 张根硕(JangKeunSuk

焦玉洁-ucd08uc625uacb0 cho ok gyeol张华杰-uc7a5ud654uac78 jang hua geol杨晨梦-uc591uc2e0ubabd yang sin mong张雨萌-uc7a5uc6b0ub9f9 jang u maeng孙伟娜-uc190uc704ub098 son wi na

django1.9.5怎么建立超级用户

首先我们要新建一个用户名,用来登陆管理网站,可以使用如下命令:python manage.py createsuperuser输入想要使用的用户名:Username (leave blank to use "administrator"): user01输入email:Email address: (在这里输入你的自己的邮箱帐号)输入密码,需要输入两次,并且输入密码时不会显示出来:Password:Password (again):当两次密码都相同的时候,就会提示超级帐号创建成功。Superuser created successfully.运行服务:python manage.py runserver

Django项目使用LDAP的配置问题

仅供参考:import ldap from auth_ldap.config import LDAPSearch,PosixGroupType,ActiveDirectoryGroupType AUTH_LDAP_SERVER_URI = "ldap://gfacser020.xxxx.com:389"AUTH_LDAP_BIND_DN = "cn=test,ou=ldpusers,dc=xxx,dc=com"AUTH_LDAP_BIND_PASSWORD = "xxxxx"AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=xxxx,DC=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)",)# Populate the Django user from the LDAP directory.AUTH_LDAP_USER_ATTR_MAP = { "first_name": "mailNickname",#mailNickname givenName "email": "mail",}# This is the defaultAUTH_LDAP_ALWAYS_UPDATE_USER = False# Cache group memberships for 5 minutes to reduce LDAP trafficAUTH_LDAP_CACHE_GROUPS = TrueAUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_X_TLS_REQUIRE_CERT: False, ldap.OPT_REFERRALS: False,}# Keep ModexampleBackend around for per-user permissions and maybe a local superuser.AUTHENTICATION_BACKENDS = ( "auth_ldap.backend.LDAPBackend", "django.contrib.auth.backends.ModelBackend", )

Jang Yoo的韩语意思是什么呀,希望能得到帮助,谢谢各位大虾。

张宇吧。。。

Django模型中的OneToOneField和ForeignKey有什么区别

  说是ForeignKey是one-to-many的,并举了一个车的例子:有两个配件表,一个是车轮表,另一个是引擎表。两个表都有一个car字段,表示该配件对应的车。对于车轮来说,多个对应一个car的情况很正常,所以car字段应该用ForeignKey来表示。对于引擎来说,一个引擎只可能对应一个car,所以必须用OneToOneField。OneToOneField(someModel) 可以理解为 ForeignKey(SomeModel, unique=True)。    两者的反向查询是有差别的:  ForeignKey反向查询返回的是一个列表(一个车有多个轮子)。  OneToOneField反向查询返回的是一个模型示例(因为一对一关系)。    另外的补充说明:  Be careful to realize that there are some differences between OneToOneField(SomeModel) andForeignKey(SomeModel, unique=True). As stated in The Definitive Guide to Django:  OneToOneField  A one-to-one relationship. Conceptually, this is similar toa ForeignKey with unique=True, but the "reverse" side of the relation will directly return a single object.  In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns aQuerySet.  Example  For example, if we have the following two models (full model code below):  Car model uses OneToOneField(Engine)  Car2 model uses ForeignKey(Engine2, unique=True)  From within python manage.py shell execute the following:  OneToOneField Example  >>> from testapp.models import Car, Engine>>> c = Car.objects.get(name="Audi")>>> e = Engine.objects.get(name="Diesel")>>> e.car<Car: Audi>  ForeignKey with unique=True Example  >>> from testapp.models import Car2, Engine2>>> c2 = Car2.objects.get(name="Mazda")>>> e2 = Engine2.objects.get(name="Wankel")>>> e2.car2_set.all()[<Car2: Mazda>]  Model Code  from django.db import modelsclass Engine(models.Model): name = models.CharField(max_length=25) def __unicode__(self): return self.nameclass Car(models.Model): name = models.CharField(max_length=25) engine = models.OneToOneField(Engine) def __unicode__(self): return self.nameclass Engine2(models.Model): name = models.CharField(max_length=25) def __unicode__(self): return self.nameclass Car2(models.Model): name = models.CharField(max_length=25) engine = models.ForeignKey(Engine2, unique=True) def __unicode__(self): return self.name    

django怎样自动创建数据库table

定义好models类后,在工程目录cmd 运行python manager.py sycndb

django 中template 怎么使用model自定义的方法

django model中使用多语言支持的快速方法, 该方法通过建立自定义的template tag 选取model中重复的语言field来达到多语言显示的目的.假设我们有这样一个models.py, 某一个model中包含多个重复的field, 每个重复的field都是用来保存其对应的显示语言: class MyObject(models.Model): name = models.CharField(max_length=50) title_en = models.CharField(max_length=50) title_es = models.CharField(max_length=100) title_fr = models.CharField(max_length=100) description_en = models.CharField(max_length=100) description_es = models.CharField(max_length=100) description_fr = models.CharField(max_length=100) class MyOtherObject(models.Model): name = models.CharField(max_length=50) content_en = models.CharField(max_length=200) content_es = models.CharField(max_length=200) content_fr = models.CharField(max_length=200)注意, 我们将下划线和语言代码作为后缀放在对应的field后面, 这将作为一个语言的查找标记.然后我们在settings.py中添加需要翻译的field名: TRANSLATION_FIELDS = ("title", "description", "content")在项目目录中添加templatetags目录(不要忘了怎家__init__.py), 并在其中建立lazy_tags.py: from django import template from settings import TRANSLATION_FIELDS register = template.Library() class LocalizedContent(template.Node): def __init__(self, model, language_code): self.model = model self.lang = language_code def render(self, context): model = template.resolve_variable(self.model, context) lang = template.resolve_variable(self.lang, context) for f in TRANSLATION_FIELDS: try: setattr(model, f, getattr(model, "%s_%s" % (f, lang))) except AttributeError: pass return "" @register.tag(name="get_localized_content") def get_localized_content(parser, token): bits = list(token.split_contents()) if len(bits) != 3: raise template.TemplateSyntaxError(""get_localized_content" tag takes exactly 2 arguments") return LocalizedContent(model=bits[1], language_code=bits[2])为了在template中使用自定义的tag, 我们首先载入: {% load lazy_tags %}然后使用自定义tag, 传入object和语言代码, 取的翻译. 比如西班牙语: {% get_localized_content object "es" %}此时, 如果没有语言代码传入, 那么无法使用obj.description调用某一个语言field. 所以我们配合django.core.context_processors.request, context processor一起使用: TEMPLATE_CONTEXT_PROCESSORS = ( ... "django.core.context_processors.request", )我们就能在template中这样使用: {% get_localized_content object request.LANGUAGE_CODE %}

patterns函数在新版django中为什么不用了

patterns函数在新版django中为什么不用了python的话,你可以把python的安装环境加到系统变量(我记得是自动添加的,可以在dos下直接运行python)至于django的话,可以直接运行django-admin startproject mysite2(django-admin不用.py),不用python django-admin.py startproject mysite2(如果要的话,需要在python安装包下的script添加到系统环境变量)1、可以扩充django模板的现有语法。例如switch case 等等,没有做不到,只有想不到。 2、为模板中加入函数功能。 3、把不同模板中的共有片段抽象出来,进行封装。好处是大大减少了代码量, 注意我这里说的复用既包。

django中include和extends有什么区别

其中funnytest是其中一个app,funnytest 目录下设置了一个Urls, 内容为: --- from django.conf.urls import patterns, include, url from views impor

如何解决Django 1.8在migrate时失败

1. 创建项目运行下面命令就可以创建一个 django 项目,项目名称叫 mysite :$ django-admin.py startproject mysite创建后的项目目录如下:mysite├── manage.py└── mysite├── __init__.py├── settings.py├── urls.py└── wsgi.py1 directory, 5 files说明:__init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。 这是一个空文件,一般你不需要修改它。manage.py :一种命令行工具,允许你以多种方式与该 Django 项目进行交互。 键入python manage.py help,看一下它能做什么。 你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便。settings.py :该 Django 项目的设置或配置。urls.py:Django项目的URL路由设置。目前,它是空的。wsgi.py:WSGI web 应用服务器的配置文件。更多细节,查看 How to deploy with WSGI接下来,你可以修改 settings.py 文件,例如:修改 LANGUAGE_CODE、设置时区 TIME_ZONESITE_ID = 1LANGUAGE_CODE = "zh_CN"TIME_ZONE = "Asia/Shanghai"USE_TZ = True 上面开启了 [Time zone](https://docs.djangoproject.com/en/1.7/topics/i18n/timezones/) 特性,需要安装 pytz:$ sudo pip install pytz2. 运行项目在运行项目之前,我们需要创建数据库和表结构,这里我使用的默认数据库:$ python manage.py migrateOperations to perform:Apply all migrations: admin, contenttypes, auth, sessionsRunning migrations:Applying contenttypes.0001_initial... OKApplying auth.0001_initial... OKApplying admin.0001_initial... OKApplying sessions.0001_initial... OK然后启动服务:$ python manage.py runserver你会看到下面的输出:Performing system checks...System check identified no issues (0 silenced).January 28, 2015 - 02:08:33Django version 1.7.1, using settings "mysite.settings"Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.这将会在端口8000启动一个本地服务器, 并且只能从你的这台电脑连接和访问。 既然服务器已经运行起来了,现在用网页浏览器访问 http://127.0.0.1:8000/。你应该可以看到一个令人赏心悦目的淡蓝色 Django 欢迎页面它开始工作了。你也可以指定启动端口:$ python manage.py runserver 8080以及指定 ip:$ python manage.py runserver 0.0.0.0:80003. 创建 app前面创建了一个项目并且成功运行,现在来创建一个 app,一个 app 相当于项目的一个子模块。在项目目录下创建一个 app:$ python manage.py startapp polls如果操作成功,你会在 mysite 文件夹下看到已经多了一个叫 polls 的文件夹,目录结构如下:polls├── __init__.py├── admin.py├── migrations│ └── __init__.py├── models.py├── tests.py└── views.py1 directory, 6 files4. 创建模型每一个 Django Model 都继承自 django.db.models.Model在 Model 当中每一个属性 attribute 都代表一个 database field通过 Django Model API 可以执行数据库的增删改查, 而不需要写一些数据库的查询语句打开 polls 文件夹下的 models.py 文件。创建两个模型:import datetimefrom django.db import modelsfrom django.utils import timezoneclass Question(models.Model):question_text = models.CharField(max_length=200)pub_date = models.DateTimeField("date published")def was_published_recently(self):return self.pub_date >= timezone.now() - datetime.timedelta(days=1)class Choice(models.Model):question = models.ForeignKey(Question)choice_text = models.CharField(max_length=200)votes = models.IntegerField(default=0)然后在 mysite/settings.py 中修改 INSTALLED_APPS 添加 polls:INSTALLED_APPS = ("django.contrib.admin","django.contrib.auth","django.contrib.contenttypes","django.contrib.sessions","django.contrib.messages","django.contrib.staticfiles","polls",)在添加了新的 app 之后,我们需要运行下面命令告诉 Django 你的模型做了改变,需要迁移数据库:$ python manage.py makemigrations polls你会看到下面的输出日志:Migrations for "polls":0001_initial.py:- Create model Choice- Create model Question- Add field question to choice你可以从 polls/migrations/0001_initial.py 查看迁移语句。运行下面语句,你可以查看迁移的 sql 语句:$ python manage.py sqlmigrate polls 0001输出结果:BEGIN;CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";DROP TABLE "polls_choice";ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");COMMIT;你可以运行下面命令,来检查数据库是否有问题:$ python manage.py check再次运行下面的命令,来创建新添加的模型:$ python manage.py migrateOperations to perform:Apply all migrations: admin, contenttypes, polls, auth, sessionsRunning migrations:Applying polls.0001_initial... OK总结一下,当修改一个模型时,需要做以下几个步骤:修改 models.py 文件运行 python manage.py makemigrations 创建迁移语句运行 python manage.py migrate,将模型的改变迁移到数据库中你可以阅读 django-admin.py documentation,查看更多 manage.py 的用法。创建了模型之后,我们可以通过 Django 提供的 API 来做测试。运行下面命令可以进入到 python shell 的交互模式:$ python manage.py shell下面是一些测试:>>> from polls.models import Question, Choice # Import the model classes we just wrote.# No questions are in the system yet.>>> Question.objects.all()[]# Create a new Question.# Support for time zones is enabled in the default settings file, so# Django expects a datetime with tzinfo for pub_date. Use timezone.now()# instead of datetime.datetime.now() and it will do the right thing.>>> from django.utils import timezone>>> q = Question(question_text="What"s new?", pub_date=timezone.now())# Save the object into the database. You have to call save() explicitly.>>> q.save()# Now it has an ID. Note that this might say "1L" instead of "1", depending# on which database you"re using. That"s no biggie; it just means your# database backend prefers to return integers as Python long integer# objects.>>> q.id1# Access model field values via Python attributes.>>> q.question_text"What"s new?">>> q.pub_datedatetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)# Change values by changing the attributes, then calling save().>>> q.question_text = "What"s up?">>> q.save()# objects.all() displays all the questions in the database.>>> Question.objects.all()[<Question: Question object>]打印所有的 Question 时,输出的结果是 [<Question: Question object>],我们可以修改模型类,使其输出更为易懂的描述。修改模型类:from django.db import modelsclass Question(models.Model):# ...def __str__(self): # __unicode__ on Python 2return self.question_textclass Choice(models.Model):# ...def __str__(self): # __unicode__ on Python 2return self.choice_text接下来继续测试:>>> from polls.models import Question, Choice# Make sure our __str__() addition worked.>>> Question.objects.all()[<Question: What"s up?>]# Django provides a rich database lookup API that"s entirely driven by# keyword arguments.>>> Question.objects.filter(id=1)[<Question: What"s up?>]>>> Question.objects.filter(question_text__startswith="What")[<Question: What"s up?>]# Get the question that was published this year.>>> from django.utils import timezone>>> current_year = timezone.now().year>>> Question.objects.get(pub_date__year=current_year)<Question: What"s up?># Request an ID that doesn"t exist, this will raise an exception.>>> Question.objects.get(id=2)Traceback (most recent call last):...DoesNotExist: Question matching query does not exist.# Lookup by a primary key is the most common case, so Django provides a# shortcut for primary-key exact lookups.# The following is identical to Question.objects.get(id=1).>>> Question.objects.get(pk=1)<Question: What"s up?># Make sure our custom method worked.>>> q = Question.objects.get(pk=1)# Give the Question a couple of Choices. The create call constructs a new# Choice object, does the INSERT statement, adds the choice to the set# of available choices and returns the new Choice object. Django creates# a set to hold the "other side" of a ForeignKey relation# (e.g. a question"s choice) which can be accessed via the API.>>> q = Question.objects.get(pk=1)# Display any choices from the related object set -- none so far.>>> q.choice_set.all()[]# Create three choices.>>> q.choice_set.create(choice_text="Not much", votes=0)<Choice: Not much>>>> q.choice_set.create(choice_text="The sky", votes=0)<Choice: The sky>>>> c = q.choice_set.create(choice_text="Just hacking again", votes=0)# Choice objects have API access to their related Question objects.>>> c.question<Question: What"s up?># And vice versa: Question objects get access to Choice objects.>>> q.choice_set.all()[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>>> q.choice_set.count()3# The API automatically follows relationships as far as you need.# Use double underscores to separate relationships.# This works as many levels deep as you want; there"s no limit.# Find all Choices for any question whose pub_date is in this year# (reusing the "current_year" variable we created above).>>> Choice.objects.filter(question__pub_date__year=current_year)[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]# Let"s delete one of the choices. Use delete() for that.>>> c = q.choice_set.filter(choice_text__startswith="Just hacking")>>> c.delete()>>> 上面这部分测试,涉及到 django orm 相关的知识,详细说明可以参考 Django中的ORM。5. 管理 adminDjango有一个优秀的特性, 内置了Django admin后台管理界面, 方便管理者进行添加和删除网站的内容.新建的项目系统已经为我们设置好了后台管理功能,见 mysite/settings.py:INSTALLED_APPS = ("django.contrib.admin", #默认添加后台管理功能"django.contrib.auth","django.contrib.contenttypes","django.contrib.sessions","django.contrib.messages","django.contrib.staticfiles","mysite",)同时也已经添加了进入后台管理的 url, 可以在 mysite/urls.py 中查看:url(r"^admin/", include(admin.site.urls)), #可以使用设置好的url进入网站后台接下来我们需要创建一个管理用户来登录 admin 后台管理界面:$ python manage.py createsuperuserUsername (leave blank to use "june"): adminEmail address:Password:Password (again):Superuser created successfully.总结最后,来看项目目录结构:mysite├── db.sqlite3├── manage.py├── mysite│ ├── __init__.py│ ├── settings.py│ ├── urls.py│ ├── wsgi.py├── polls│ ├── __init__.py│ ├── admin.py│ ├── migrations│ │ ├── 0001_initial.py│ │ ├── __init__.py│ ├── models.py│ ├── templates│ │ └── polls│ │ ├── detail.html│ │ ├── index.html│ │ └── results.html│ ├── tests.py│ ├── urls.py│ ├── views.py└── templates└── admin└── base_site.htm

如何创建一个Django网站

本文演示如何创建一个简单的 django 网站,使用的 django 版本为1.7。1. 创建项目运行下面命令就可以创建一个 django 项目,项目名称叫 mysite :$ django-admin.py startproject mysite创建后的项目目录如下:mysite├── manage.py└── mysite ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py1 directory, 5 files说明:__init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。 这是一个空文件,一般你不需要修改它。manage.py :一种命令行工具,允许你以多种方式与该 Django 项目进行交互。 键入python manage.py help,看一下它能做什么。 你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便。settings.py :该 Django 项目的设置或配置。urls.py:Django项目的URL路由设置。目前,它是空的。wsgi.py:WSGI web 应用服务器的配置文件。更多细节,查看 How to deploy with WSGI接下来,你可以修改 settings.py 文件,例如:修改 LANGUAGE_CODE、设置时区 TIME_ZONESITE_ID = 1LANGUAGE_CODE = "zh_CN"TIME_ZONE = "Asia/Shanghai"USE_TZ = True 上面开启了 [Time zone](https://docs.djangoproject.com/en/1.7/topics/i18n/timezones/) 特性,需要安装 pytz:$ sudo pip install pytz2. 运行项目在运行项目之前,我们需要创建数据库和表结构,这里我使用的默认数据库:$ python manage.py migrateOperations to perform: Apply all migrations: admin, contenttypes, auth, sessionsRunning migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying sessions.0001_initial... OK然后启动服务:$ python manage.py runserver你会看到下面的输出:Performing system checks...System check identified no issues (0 silenced).January 28, 2015 - 02:08:33Django version 1.7.1, using settings "mysite.settings"Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.这将会在端口8000启动一个本地服务器, 并且只能从你的这台电脑连接和访问。 既然服务器已经运行起来了,现在用网页浏览器访问 http://127.0.0.1:8000/。你应该可以看到一个令人赏心悦目的淡蓝色 Django 欢迎页面它开始工作了。你也可以指定启动端口:$ python manage.py runserver 8080以及指定 ip:$ python manage.py runserver 0.0.0.0:80003. 创建 app前面创建了一个项目并且成功运行,现在来创建一个 app,一个 app 相当于项目的一个子模块。在项目目录下创建一个 app:$ python manage.py startapp polls如果操作成功,你会在 mysite 文件夹下看到已经多了一个叫 polls 的文件夹,目录结构如下:polls├── __init__.py├── admin.py├── migrations│ └── __init__.py├── models.py├── tests.py└── views.py1 directory, 6 files4. 创建模型每一个 Django Model 都继承自 django.db.models.Model在 Model 当中每一个属性 attribute 都代表一个 database field通过 Django Model API 可以执行数据库的增删改查, 而不需要写一些数据库的查询语句打开 polls 文件夹下的 models.py 文件。创建两个模型:import datetimefrom django.db import modelsfrom django.utils import timezoneclass Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1)class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)然后在 mysite/settings.py 中修改 INSTALLED_APPS 添加 polls:INSTALLED_APPS = ( "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "polls",)在添加了新的 app 之后,我们需要运行下面命令告诉 Django 你的模型做了改变,需要迁移数据库:$ python manage.py makemigrations polls你会看到下面的输出日志:Migrations for "polls": 0001_initial.py: - Create model Choice - Create model Question - Add field question to choice你可以从 polls/migrations/0001_initial.py 查看迁移语句。运行下面语句,你可以查看迁移的 sql 语句:$ python manage.py sqlmigrate polls 0001输出结果:BEGIN;CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";DROP TABLE "polls_choice";ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");COMMIT;你可以运行下面命令,来检查数据库是否有问题:$ python manage.py check再次运行下面的命令,来创建新添加的模型:$ python manage.py migrateOperations to perform: Apply all migrations: admin, contenttypes, polls, auth, sessionsRunning migrations: Applying polls.0001_initial... OK总结一下,当修改一个模型时,需要做以下几个步骤:修改 models.py 文件运行 python manage.py makemigrations 创建迁移语句运行 python manage.py migrate,将模型的改变迁移到数据库中你可以阅读 django-admin.py documentation,查看更多 manage.py 的用法。创建了模型之后,我们可以通过 Django 提供的 API 来做测试。运行下面命令可以进入到 python shell 的交互模式:$ python manage.py shell下面是一些测试:>>> from polls.models import Question, Choice # Import the model classes we just wrote.# No questions are in the system yet.>>> Question.objects.all()[]# Create a new Question.# Support for time zones is enabled in the default settings file, so# Django expects a datetime with tzinfo for pub_date. Use timezone.now()# instead of datetime.datetime.now() and it will do the right thing.>>> from django.utils import timezone>>> q = Question(question_text="What"s new?", pub_date=timezone.now())# Save the object into the database. You have to call save() explicitly.>>> q.save()# Now it has an ID. Note that this might say "1L" instead of "1", depending# on which database you"re using. That"s no biggie; it just means your# database backend prefers to return integers as Python long integer# objects.>>> q.id1# Access model field values via Python attributes.>>> q.question_text"What"s new?">>> q.pub_datedatetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)# Change values by changing the attributes, then calling save().>>> q.question_text = "What"s up?">>> q.save()# objects.all() displays all the questions in the database.>>> Question.objects.all()[<Question: Question object>]打印所有的 Question 时,输出的结果是 [<Question: Question object>],我们可以修改模型类,使其输出更为易懂的描述。修改模型类:from django.db import modelsclass Question(models.Model): # ... def __str__(self): # __unicode__ on Python 2 return self.question_textclass Choice(models.Model): # ... def __str__(self): # __unicode__ on Python 2 return self.choice_text接下来继续测试:>>> from polls.models import Question, Choice# Make sure our __str__() addition worked.>>> Question.objects.all()[<Question: What"s up?>]# Django provides a rich database lookup API that"s entirely driven by# keyword arguments.>>> Question.objects.filter(id=1)[<Question: What"s up?>]>>> Question.objects.filter(question_text__startswith="What")[<Question: What"s up?>]# Get the question that was published this year.>>> from django.utils import timezone>>> current_year = timezone.now().year>>> Question.objects.get(pub_date__year=current_year)<Question: What"s up?># Request an ID that doesn"t exist, this will raise an exception.>>> Question.objects.get(id=2)Traceback (most recent call last): ...DoesNotExist: Question matching query does not exist.# Lookup by a primary key is the most common case, so Django provides a# shortcut for primary-key exact lookups.# The following is identical to Question.objects.get(id=1).>>> Question.objects.get(pk=1)<Question: What"s up?># Make sure our custom method worked.>>> q = Question.objects.get(pk=1)# Give the Question a couple of Choices. The create call constructs a new# Choice object, does the INSERT statement, adds the choice to the set# of available choices and returns the new Choice object. Django creates# a set to hold the "other side" of a ForeignKey relation# (e.g. a question"s choice) which can be accessed via the API.>>> q = Question.objects.get(pk=1)# Display any choices from the related object set -- none so far.>>> q.choice_set.all()[]# Create three choices.>>> q.choice_set.create(choice_text="Not much", votes=0)<Choice: Not much>>>> q.choice_set.create(choice_text="The sky", votes=0)<Choice: The sky>>>> c = q.choice_set.create(choice_text="Just hacking again", votes=0)# Choice objects have API access to their related Question objects.>>> c.question<Question: What"s up?># And vice versa: Question objects get access to Choice objects.>>> q.choice_set.all()[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>>> q.choice_set.count()3# The API automatically follows relationships as far as you need.# Use double underscores to separate relationships.# This works as many levels deep as you want; there"s no limit.# Find all Choices for any question whose pub_date is in this year# (reusing the "current_year" variable we created above).>>> Choice.objects.filter(question__pub_date__year=current_year)[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]# Let"s delete one of the choices. Use delete() for that.>>> c = q.choice_set.filter(choice_text__startswith="Just hacking")>>> c.delete()>>> 上面这部分测试,涉及到 django orm 相关的知识,详细说明可以参考 Django中的ORM。5. 管理 adminDjango有一个优秀的特性, 内置了Django admin后台管理界面, 方便管理者进行添加和删除网站的内容.新建的项目系统已经为我们设置好了后台管理功能,见 mysite/settings.py:INSTALLED_APPS = ( "django.contrib.admin", #默认添加后台管理功能 "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "mysite",)同时也已经添加了进入后台管理的 url, 可以在 mysite/urls.py 中查看:url(r"^admin/", include(admin.site.urls)), #可以使用设置好的url进入网站后台接下来我们需要创建一个管理用户来登录 admin 后台管理界面:$ python manage.py createsuperuserUsername (leave blank to use "june"): adminEmail address:Password:Password (again):Superuser created successfully.总结最后,来看项目目录结构:mysite├── db.sqlite3├── manage.py├── mysite│ ├── __init__.py│ ├── settings.py│ ├── urls.py│ ├── wsgi.py├── polls│ ├── __init__.py│ ├── admin.py│ ├── migrations│ │ ├── 0001_initial.py│ │ ├── __init__.py│ ├── models.py│ ├── templates│ │ └── polls│ │ ├── detail.html│ │ ├── index.html│ │ └── results.html│ ├── tests.py│ ├── urls.py│ ├── views.py└── templates └── admin └── base_site.htm 通过上面的介绍,对 django 的安装、运行以及如何创建视 图和模型有了一个清晰的认识,接下来就可以深入的学习 django 的自动化测试、持久化、中间件、国 际 化等知识。

韩国歌手jim jang hoon的简介

  ARTIST: Kim,Jang Hoon  ALBUM: Vol. 9 - It"s Me  LABEL: CJ Music  GENRE: Pop  BITRATE: 192kbps.Avg  RELEASE DATE: 2006-10-25  Description  Track List  01 . Honey  02 . uc138uc218  03 . ub2ecub824ub77c ub2ecub824  04 . ucee4ud50c  05 . ub0a8uc790ub77cuc11c uc6c3uc5b4uc694  06 . ubabbuc78auc5b4  07 . uc624ub798ub418ub358 ub0a0  08 . ube59uae00ube59uae00(Zucker version)  09 . ucc9cuc0acuc5d0uac8c  10 . ud5c8ub2c8(Mania version)  11 . ub0b4 ub9c8uc74cuc5d0uc11c ub110 ub5a0ub098ubcf4ub0b4uace0  Kim Jang Hoon 继2005年第八张大碟《Piece》。由第四张唱片开始,他主攻唱功方面,在新碟中转向监制及编曲方式。有别于之前的“感觉”方向,他想以新音乐、狂野唱腔来“感动”各位乐迷。  2006年推出的最新专辑《It"s Me》,歌曲简单又动人情歌,相信不少听众也会被新歌深深打动!爱作崭新尝试的Kim Jang Hoon认为音乐只要能感动他人,便经已成功。  http://nowok.net/CD/CD16729.htm

韩文张岩 장연罗马拼音Jang yeon 장암罗马拼音jang arm 这两个哪个对

第一个对~~

Jin-yeongJang出生于哪里

Jin-yeongJangJin-yeongJang,导演,主要作品《再相见》。外文名:Jin-yeongJang职业:导演代表作品:《再相见》合作人物:金芝美

韩文 Jang Jeong

话说那个不久已经是拼音了么?

跪求stella jang 的colors mp3百度云啊

提取码:6zef

求CCTV央视英文频道的女主播蒋继芸(JANG JI-YUN)的资料,还有照片。在网上找不到,郁闷。。

可以肯定不是中国人,因为(JANG)不是汉语拼音拼写方式JANG JI-YUN 为韩裔加拿大人,韩文中的JANG对应中文为张,所以有人叫她做张霁云。生于1984年3月7日,毕业于加拿大英属哥伦比亚大学这是此女目前公开所知的资料,满意还请及时采纳

疒字头下面一个八字,用什么方法可以电脑打出来字典没有这字,念“ka”还有 身字后面一个小字jang

用手写王

HUAGJANG冰箱压缩机是什么品牌?

冰箱压缩机是什么品牌?应该是三星吧?

jang牛肉用多长时间

两到三个小时酱牛肉的做法〔主料辅料〕牛腱子500克 精盐2克酱油100克 白糖15克甜面酱50克 料酒10克大葱50克 鲜姜50克蒜10瓣 香油25克肉料35克〔烹制方法〕1.将牛腱子顺肉纹切成拳头大小的块,用开水焯透,去净血沫后捞出。2.将大葱、姜择洗干净,切成块与蒜、精盐、酱油、面酱、白糖、料酒、香油、肉料一起放入锅中,加入牛肉汤烧开,煮成酱汤。3.将牛肉放入酱汤锅中,以漫过牛肉为准煮5~10分钟,改微人炯约2-3小时,保持汤微开冒泡,要勤翻动牛肉,使之受热均匀,待汤汁渐浓,牛肉用竹筷子可以扦透时捞出,晾凉后切成薄片,即可装盘食用。〔工艺关键〕1.肉料:花椒50克、大料10克、桂皮10克、丁香2克、陈皮5克、白芒5克、砂仁5克、豆寇5克、大茴香2克、小茴香之克。制作本菜用以上肉料的1/3,用纱布包好,料酒宜用绍兴黄酒。2、将剩余的汤卤汁撇去浮油,用豆包布包滤一下,留待酱其它东西时使用。3.牛肉要焯透而不宜煮透。酱牛肉的做法1.选料:选用鲜嫩牛肉,(沙仁、豆蔻、丁香、肉桂、大料、小茴香各2克用纱布扎成小口袋) 葱姜少许蒜和辣椒备用。2.清洗:先将选好的牛肉放入清水中,浸泡4~6小时,把牛肉中的淤血泡出、洗净,然后用板刷刷洗1次,再用清凉水过4次。3.糖色:炒锅放少许底油,油热,将白糖放入锅里炒,要把握好火候,看见有蘑菇沫子时加开水冲成糖色,白糖的量按牛肉的量放,如2斤大概放1两左右。4.煮制:锅底码放骨头或竹板子,将嫩肉码放中间,老肉码放四边,兑进开水,加入全料口袋,老抽多加,葱姜蒜等用旺火煮半小时后压锅。压锅的方法是用竹板子或其它如盘子等压在牛肉上,竹板上加重物压住。5.出锅:压锅后,改小火汤刚刚煮起即可,用小火煮3个小时出锅。出锅时要做到轻铲稳托放平,肉出锅后要放在竹屉内免得把酱牛肉碰碎,待凉后即可切用。做一锅酱牛肉大约需要4小时,每5千克生牛肉可出熟肉2.5千克。要点:肉熟后留汤,下次煮续用多次使用形成老汤煮肉味道更好。

Jang-hoonAhn多大了

Jang-hoonAhnJang-hoonAhn是一名演员,代表作品有《竞猜王》《忧郁的申石基》等。外文名:Jang-hoonAhn职业:演员代表作品:《竞猜王》合作人物:张镇

Jang的《太傻瓜》 歌词

太傻瓜作词/作曲/和声/混音/演唱/Jang我之前其实就是一个傻瓜时常听你讲一大堆的笑话和尚怎么还能长头发长头发怎么还能叫出家刚一到五月就叫我吃苦瓜瞧我脸上透露一些想法今天说的话全部作假过时的假话也别出来大夸我不是大家 能透彻尔虞我诈我只是傻瓜 在你嘴边玩耍庆祝千万别用烟花我会就地伏法化解你真诚的假我不是傻瓜 两只眼一睁一瞎我愿做大家 能辨清仿古造假迷人千万别送情话专用手语打哑就当是愚人 愚己 我再愚他我之前其实就是一个傻瓜(一个傻瓜)时常听你讲一大堆的笑话(大堆笑话哦)和尚怎么还能长头发长头发怎么还能叫出家刚一到五月就叫我吃苦瓜瞧我脸上透露一些想法(什么想法)今天说的话全部作假过时的假话也别出来大夸我不是大家 能透彻尔虞我诈我只是傻瓜 在你嘴边玩耍庆祝千万别用烟花我会就地伏法化解你真诚的假我不是傻瓜 两只眼一睁一瞎我愿做大家 能辨清仿古造假迷人千万别送情话专用手语打哑就当是愚人 愚己 我再愚他ye 傻瓜 哦~~~~~ ye你也是傻瓜我也是傻瓜其实我们真的太傻瓜我不是傻瓜 两只眼一睁一瞎我愿做大家 能辨清仿古造假迷人千万别送情话专用手语打哑就当是愚人 愚己 我再愚他http://music.baidu.com/song/14740746

Jang的《耙耳朵》 歌词

耙耳朵作词:Jang作曲:Jang演唱:Jang当古榕树的年轮圈了一圈又一圈成色已旧的黑白照片贪恋永远爷爷和奶奶那天肯定笑得很甜到现在依旧蹒跚去 小湖边隔壁家张阿姨的小猫慵懒在夏天我呆在家里写歌 歌词想了半天当一阵风吹过凉爽沁入心田我电话接到耳边叫我陪她去逛街哎 陪你走啊走啊走啊走到什么时候太阳当头牵着小手还要去吃土豆绕了我 放开我 可我不敢开口凭什么我就这么耙耳朵溜啊溜啊溜啊溜啊溜到百货大楼你的心思我早已懂为了那件潮流没关系 五百块 表面我不心疼又得算计明天怎么去求助朋友当古榕树的年轮圈了一圈又一圈成色已旧的黑白照片贪恋永远爷爷和奶奶那天肯定笑得很甜到现在依旧蹒跚去 小湖边隔壁家张阿姨的小猫慵懒在夏天我呆在家里写歌 歌词想了半天当一阵风吹过凉爽沁入心田我电话接到耳边叫我陪她去逛街陪你走啊走啊走啊走到什么时候太阳当头牵着小手还要去吃土豆绕了我 放开我 可我不敢开口凭什么我就这么耙耳朵溜啊溜啊溜啊溜啊溜到百货大楼你的心思我早已懂为了那件潮流没关系 五百块 表面我不心疼又得算计明天怎么去求助朋友陪你走啊走啊走啊走到什么时候太阳当头牵着小手还要去吃土豆绕了我 放开我 可我不敢开口凭什么我就这么耙耳朵溜啊溜啊溜啊溜啊溜到百货大楼你的心思我早已懂为了那件潮流没关系 五百块 表面我不心疼又得算计明天怎么去求助朋友http://music.baidu.com/song/14740795

Jang的《刺痛》 歌词

《刺痛》作词:Jang作曲:Jang演唱:Jang怪不得我的眼皮一直在跳不安的预兆竟躲藏一丝美妙是你在我的心里拼命逃跑两人的眼神不过相互半秒听我大声哀嚎听我痛苦学狗叫我将要去何处寻找救命稻草我的刺痛 你不会懂 天色灰朦脓唱着唱着 只怕眼泪 会有始无终上次你说 不能难过 不要想太多这次认了 这次懂了 这次不会了我是你的 你是我的 已经很久了频繁做错 你的快乐 渐行渐远着不痛不痛 不说不痛 心却在蜷缩他做你的 你做他的 爱给你们了注视着你的神情我能猜到剪去的发梢衬托我无可救药你还在我的心里拼命奔跑我满脸醉红没有力气舞蹈听我大声哀嚎听我痛苦学狗叫我将要去何处寻找救命稻草我的刺痛 你不会懂 天色灰朦脓唱着唱着 只怕眼泪 会有始无终上次你说 不能难过 不要想太多这次认了 这次懂了 这次不会了我是你的 你是我的 已经很久了频繁做错 你的快乐 渐行渐远着不痛不痛 不得不痛 心也在蜷缩他能给的 我束手无策 把爱给你们了给你们了http://music.baidu.com/song/14740723

请问“jang”这个单词中文意思是什么?谢谢!

一月

哈喽,我是jang,你想知道我过去几年的变化吗?让我来告诉你吧 过去的我很有时会

相对来说我觉得变化的话应该的确会非常大的感受。

电影Lucy《超体》里面大反派Mr.Jang张先生吸的是什么烟?

不认识,看了很多遍也看不出来。《超体》,又名《露西》,是一部由法国导演吕克·贝松执导、好莱坞知名女影星斯嘉丽·约翰逊主演的科幻动作片。该片在中国台湾台北取景,综合美国百老汇影星摩根·弗里曼,韩国知名名演员崔岷植等。影片于2014年7月25日在北美上映。《超体》讲述一个年轻女人被迫变成毒贩,然后这种毒品倾入她自己身体,反而给了她超于常人的力量:包括心灵感应、瞬间吸收知识等技能,让其成为一名无所不能到“女超人”。

she is name is jang对吗

应是Her name is jang. 一句话里不能有两个动词

张慧翻译成韩国人的英文名字,( uc7a5 jang ud574 hae ) Jang Hae翻得对吗

rabish

姓氏张 在英语里是jang 还是zhang?有没有好听一点的写法?

就是zhang

韩国名字Jeonghun Jang怎么读

姓 uc7a5 zhang名 uc885 ud6c8 zhong hun

《我的邻居是EXO》女主弟弟扮演者是谁?Jang Yoo-sang个人资料

昨晚韩剧我的邻居是exo女主弟弟完全抢走了10位小鲜肉主角关怀!本来我的邻居是exo完全就是看这10位小鲜肉颜值的,事实上刚好相反!在昨晚的剧情中,我的邻居是exo女主弟弟一登场就受到大批网民关注,虽然颜值比不上那几位主角,but,身上呈现的小受气质俘获大批腐女之心啊! 话说,女主弟弟看起来挺眼熟的,似乎在韩国同性恋电影《仅此一夜》出现过!下面让我们来欣赏女主弟弟扮演者Jang Yoo-sang个人资料! Jang Yoo-sang个人资料没有中字,大家可以多了解Jang Yoo-sang电影《仅此一夜》 【译名】:一夜 / 一夜基情 / 仅此一夜 【片名】:One Night Only 【年代】:2014 【类型】:爱情 / 同性 【国家】:韩国 【语言】:韩语 【导演】:Kim Jho Kwang-soo (uae40uc870uad11uc218), Kim Tae-yong-I (uae40ud0dcuc6a9) 【主演】:Yoo Min-gyoo (uc720ubbfcuaddc), Jo Bok-rae (uc870ubcf5ub798), Park Soo-jin-I (ubc15uc218uc9c4), Jang Yoo-sang (uc7a5uc720uc0c1) 【上映日期】:2014-07-03 韩国

汉语拼音里的jiang为什么不能拼jang?

汉语发音中没有jang 的音

请帮握翻译一下这个名字,是韩文喔! Hyun Jun Jang ,谢谢!

黄俊江

张泳欣 翻译成罗马文是什么?比如 张 的罗马文就是Jang 求急用!!!

jang ei kin

JANG是出自哪里的?是英文的对照吗?还是韩国的字母表?

很明显是韩语Moon不就叫JangJaeHo

英语Jang什么意思

汉语

JANG CHEUNG CHANG ZHANG哪个才是英语的"张"的写法

cheung是通用的,比如张国荣 Leslie Cheung,张学友 Jacky Cheung,张曼玉 maggie cheung等等~~

这个韩文的中文译音大概怎样读:jang

uc7a5 janguc7a5就是 “张”这个姓的韩语 发音你都写出来了啊.. J+ang 能发出来的啊 .. 再不行就发zang也可以吧 发音算是比较相近的

Jang这个词什麼意思

韩语 장 通常做姓氏翻译为张 蒋

jang 的资料谁有啊??他唱的好好听哦 jang 的资料谁有啊??他唱的好好听哦

- -你说的是网络歌手JANG貌似那个资料找不到我也超喜欢他的歌

有jang这个拼音吗

这是不正确的。要么是jian ,要么是jiang

jang汉字怎么写

左边牛右边羊:?(没有还加马,就没有这个字) ? 韩国汉字(读音jang) 解释: ①牝羊也。或作牂。 ②妖气之一也。似狗。~云。「二曰~云,如狗,赤色长尾,为乱君,为兵乱。」(天文类抄.下.妖气) 左边牛右边羊:?(没有还加马,就没有这个字) ? 韩国汉字(读音jang) 解释: ①牝羊也。或作牂。 ②妖气之一也。似狗。~云。「二曰~云,如狗,赤色长尾,为乱君,为兵乱。」(天文类抄.下.妖气)

jang是什么汉字

没有jang的汉字,有jiang的汉字,如下所示:jiāng:姜、江、疆、僵、将、浆。jiǎng:奖、桨、讲、港、蒋、桨。jiàng:酱、降、浆、匠、将、强。释义:一、江1.大河:长江。珠江。黑龙江。2.(Jiāng)指长江:江汉。江淮。江南。江左。3.姓。二、姜1.多年生草本植物,叶子披针形,花冠黄绿色,通常不开花。根状茎黄褐色,有辣味,是常用的调味品,也可入药。2.这种植物的根状茎。3.姓。三、奖1.奖励;夸奖:褒奖。嘉奖。有功者奖。2.为了鼓励或表扬而给予的荣誉或财物等:得奖。发奖。一等奖。四、酱1.一种调味品。用发酵后的豆、麦等加盐制成:黄酱。甜面酱。2.像酱的糊状食物:果酱。芝麻酱。3.用酱或酱油腌制(菜蔬):酱了点黄瓜。五、降1.落下(跟“升”相对):降落。降雨。温度降下来了。2.使落下;降低(跟“升”相对):降价。降级。3.姓。

django 框架开发的网站有哪些?

Django + Python:Disqus,Pinterest,Instagram,Washington Post。国内用Python开发的知名网站有豆瓣和知乎等等。不可否认,国内用Django开发的大型网站还不多,但随着Python越来越热及Django越来越成熟,相信会有更多人选择Django来提高Python Web开发效率。Python的Django框架是Python web框架中最重量级的一个了,使用它几乎能完成各种需求的网站开发。扩展资料:Django的主要目标是使网站开发变得简单。Django注重组件的重用性和“可插拔性”(即模块化)。在Django中Python被普遍使用,甚至包括配置文件和数据模型。Django于2008年6月17日正式成立基金会。Django框架的核心包括:一个面向对象的映射器,用作数据模型(以Python类的形式定义)和关系型数据库间的介质;一个基于正则表达式的URL分发器;一个视图系统,用于处理请求;一个模板系统。

django session可以存对象吗

1. 将Session存储在数据库中:如果要将Session存储在数据库中,我们需要将 "django.contrib.sessions" 加入到INSTALLED_APPS 变量中。然后运行 manage.py syncdb 在数据库中创建相应的存储Session的数据库表。2. 将Session存储在缓存中:如果想获得更好的性能,我们可以将Session保存在缓存中。这里有两种配置方式:一种是设置SESSION_ENGINE 为”django.contrib.sessions.backends.cache” 。这是一种简单配置,Session将之被保存在缓存中,但是不保证Session总是能取到(比如缓存溢出时Session会丢失);另一种方式是设置SESSION_ENGINE 为 “django.contrib.sessions.backends.cached_db”。这种方式下,Session在保存到缓存的同时还会被保存到数据库中,当Django在缓存中找不到Session时,会从数据库中找到。第二种方式会有一点点性能开销,但是安全性和冗余性更好。3. 将Session存储在文件系统中:最后一种方式是将Session存储在文件系统中。需要设置SESSION_ENGINE 为”django.contrib.sessions.backends.file”,这时你还需要同时设置SESSION_FILE_PATH 变量,它代表Session文件保存的位置,缺省的设置一般是tempfile.gettempdir(),表示系统的临时目录。这里要确保应用程序对那个目录有读写的权限。

韩语jang jeonguc7a5uc815怎么读?

如果你是中国人,无论你叫张正还是叫张晶韩文名字都对如果你想韩文名字翻译中文的话,这很难说,韩文对应N个汉字。。。一个韩国人有韩文名字还有对应的中文字名。

如何解决Django 1.8在migrate时失败

1. 创建项目运行下面命令就可以创建一个 django 项目,项目名称叫 mysite :$ django-admin.py startproject mysite创建后的项目目录如下:mysite├── manage.py└── mysite ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py1 directory, 5 files说明:__init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。 这是一个空文件,一般你不需要修改它。manage.py :一种命令行工具,允许你以多种方式与该 Django 项目进行交互。 键入python manage.py help,看一下它能做什么。 你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便。settings.py :该 Django 项目的设置或配置。urls.py:Django项目的URL路由设置。目前,它是空的。wsgi.py:WSGI web 应用服务器的配置文件。更多细节,查看 How to deploy with WSGI接下来,你可以修改 settings.py 文件,例如:修改 LANGUAGE_CODE、设置时区 TIME_ZONESITE_ID = 1LANGUAGE_CODE = "zh_CN"TIME_ZONE = "Asia/Shanghai"USE_TZ = True 上面开启了 [Time zone](https://docs.djangoproject.com/en/1.7/topics/i18n/timezones/) 特性,需要安装 pytz:$ sudo pip install pytz2. 运行项目在运行项目之前,我们需要创建数据库和表结构,这里我使用的默认数据库:$ python manage.py migrateOperations to perform: Apply all migrations: admin, contenttypes, auth, sessionsRunning migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying sessions.0001_initial... OK然后启动服务:$ python manage.py runserver你会看到下面的输出:Performing system checks...System check identified no issues (0 silenced).January 28, 2015 - 02:08:33Django version 1.7.1, using settings "mysite.settings"Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.这将会在端口8000启动一个本地服务器, 并且只能从你的这台电脑连接和访问。 既然服务器已经运行起来了,现在用网页浏览器访问 http://127.0.0.1:8000/。你应该可以看到一个令人赏心悦目的淡蓝色 Django 欢迎页面它开始工作了。你也可以指定启动端口:$ python manage.py runserver 8080以及指定 ip:$ python manage.py runserver 0.0.0.0:80003. 创建 app前面创建了一个项目并且成功运行,现在来创建一个 app,一个 app 相当于项目的一个子模块。在项目目录下创建一个 app:$ python manage.py startapp polls如果操作成功,你会在 mysite 文件夹下看到已经多了一个叫 polls 的文件夹,目录结构如下:polls├── __init__.py├── admin.py├── migrations│ └── __init__.py├── models.py├── tests.py└── views.py1 directory, 6 files4. 创建模型每一个 Django Model 都继承自 django.db.models.Model在 Model 当中每一个属性 attribute 都代表一个 database field通过 Django Model API 可以执行数据库的增删改查, 而不需要写一些数据库的查询语句打开 polls 文件夹下的 models.py 文件。创建两个模型:import datetimefrom django.db import modelsfrom django.utils import timezoneclass Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1)class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)然后在 mysite/settings.py 中修改 INSTALLED_APPS 添加 polls:INSTALLED_APPS = ( "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "polls",)在添加了新的 app 之后,我们需要运行下面命令告诉 Django 你的模型做了改变,需要迁移数据库:$ python manage.py makemigrations polls你会看到下面的输出日志:Migrations for "polls": 0001_initial.py: - Create model Choice - Create model Question - Add field question to choice你可以从 polls/migrations/0001_initial.py 查看迁移语句。运行下面语句,你可以查看迁移的 sql 语句:$ python manage.py sqlmigrate polls 0001输出结果:BEGIN;CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";DROP TABLE "polls_choice";ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");COMMIT;你可以运行下面命令,来检查数据库是否有问题:$ python manage.py check再次运行下面的命令,来创建新添加的模型:$ python manage.py migrateOperations to perform: Apply all migrations: admin, contenttypes, polls, auth, sessionsRunning migrations: Applying polls.0001_initial... OK总结一下,当修改一个模型时,需要做以下几个步骤:修改 models.py 文件运行 python manage.py makemigrations 创建迁移语句运行 python manage.py migrate,将模型的改变迁移到数据库中你可以阅读 django-admin.py documentation,查看更多 manage.py 的用法。创建了模型之后,我们可以通过 Django 提供的 API 来做测试。运行下面命令可以进入到 python shell 的交互模式:$ python manage.py shell下面是一些测试:>>> from polls.models import Question, Choice # Import the model classes we just wrote.# No questions are in the system yet.>>> Question.objects.all()[]# Create a new Question.# Support for time zones is enabled in the default settings file, so# Django expects a datetime with tzinfo for pub_date. Use timezone.now()# instead of datetime.datetime.now() and it will do the right thing.>>> from django.utils import timezone>>> q = Question(question_text="What"s new?", pub_date=timezone.now())# Save the object into the database. You have to call save() explicitly.>>> q.save()# Now it has an ID. Note that this might say "1L" instead of "1", depending# on which database you"re using. That"s no biggie; it just means your# database backend prefers to return integers as Python long integer# objects.>>> q.id1# Access model field values via Python attributes.>>> q.question_text"What"s new?">>> q.pub_datedatetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)# Change values by changing the attributes, then calling save().>>> q.question_text = "What"s up?">>> q.save()# objects.all() displays all the questions in the database.>>> Question.objects.all()[<Question: Question object>]打印所有的 Question 时,输出的结果是 [<Question: Question object>],我们可以修改模型类,使其输出更为易懂的描述。修改模型类:from django.db import modelsclass Question(models.Model): # ... def __str__(self): # __unicode__ on Python 2 return self.question_textclass Choice(models.Model): # ... def __str__(self): # __unicode__ on Python 2 return self.choice_text接下来继续测试:>>> from polls.models import Question, Choice# Make sure our __str__() addition worked.>>> Question.objects.all()[<Question: What"s up?>]# Django provides a rich database lookup API that"s entirely driven by# keyword arguments.>>> Question.objects.filter(id=1)[<Question: What"s up?>]>>> Question.objects.filter(question_text__startswith="What")[<Question: What"s up?>]# Get the question that was published this year.>>> from django.utils import timezone>>> current_year = timezone.now().year>>> Question.objects.get(pub_date__year=current_year)<Question: What"s up?># Request an ID that doesn"t exist, this will raise an exception.>>> Question.objects.get(id=2)Traceback (most recent call last): ...DoesNotExist: Question matching query does not exist.# Lookup by a primary key is the most common case, so Django provides a# shortcut for primary-key exact lookups.# The following is identical to Question.objects.get(id=1).>>> Question.objects.get(pk=1)<Question: What"s up?># Make sure our custom method worked.>>> q = Question.objects.get(pk=1)# Give the Question a couple of Choices. The create call constructs a new# Choice object, does the INSERT statement, adds the choice to the set# of available choices and returns the new Choice object. Django creates# a set to hold the "other side" of a ForeignKey relation# (e.g. a question"s choice) which can be accessed via the API.>>> q = Question.objects.get(pk=1)# Display any choices from the related object set -- none so far.>>> q.choice_set.all()[]# Create three choices.>>> q.choice_set.create(choice_text="Not much", votes=0)<Choice: Not much>>>> q.choice_set.create(choice_text="The sky", votes=0)<Choice: The sky>>>> c = q.choice_set.create(choice_text="Just hacking again", votes=0)# Choice objects have API access to their related Question objects.>>> c.question<Question: What"s up?># And vice versa: Question objects get access to Choice objects.>>> q.choice_set.all()[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>>> q.choice_set.count()3# The API automatically follows relationships as far as you need.# Use double underscores to separate relationships.# This works as many levels deep as you want; there"s no limit.# Find all Choices for any question whose pub_date is in this year# (reusing the "current_year" variable we created above).>>> Choice.objects.filter(question__pub_date__year=current_year)[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]# Let"s delete one of the choices. Use delete() for that.>>> c = q.choice_set.filter(choice_text__startswith="Just hacking")>>> c.delete()>>> 上面这部分测试,涉及到 django orm 相关的知识,详细说明可以参考 Django中的ORM。5. 管理 adminDjango有一个优秀的特性, 内置了Django admin后台管理界面, 方便管理者进行添加和删除网站的内容.新建的项目系统已经为我们设置好了后台管理功能,见 mysite/settings.py:INSTALLED_APPS = ( "django.contrib.admin", #默认添加后台管理功能 "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "mysite",)同时也已经添加了进入后台管理的 url, 可以在 mysite/urls.py 中查看:url(r"^admin/", include(admin.site.urls)), #可以使用设置好的url进入网站后台接下来我们需要创建一个管理用户来登录 admin 后台管理界面:$ python manage.py createsuperuserUsername (leave blank to use "june"): adminEmail address:Password:Password (again):Superuser created successfully.总结最后,来看项目目录结构:mysite├── db.sqlite3├── manage.py├── mysite│ ├── __init__.py│ ├── settings.py│ ├── urls.py│ ├── wsgi.py├── polls│ ├── __init__.py│ ├── admin.py│ ├── migrations│ │ ├── 0001_initial.py│ │ ├── __init__.py│ ├── models.py│ ├── templates│ │ └── polls│ │ ├── detail.html│ │ ├── index.html│ │ └── results.html│ ├── tests.py│ ├── urls.py│ ├── views.py└── templates └── admin └── base_site.htm 通过上面的介绍,对 django 的安装、运行以及如何创建视 图和模型有了一个清晰的认识,接下来就可以深入的学习 django 的自动化测试、持久化、中间件、国 际 化等知识。

django 数据模型中 null=True 和 blank=True 有什么区别

null: If True, Django will store empty values as NULL in the database. Defaultis False. 如果为True,空值将会被存储为NULL,默认为False。blank: If True, the field is allowed to be blank. Default is False. 如果为True,字段允许为空,默认不允许。

用python的django或者web.py做服务器,性能上有瓶颈吗?

不过,既然接受了Python的简单易用和快速开发优势,作为tradeoff,就要学会接受和处理Python的一些缺点。用django作数据服务器两年多,确实会有一些性能问题。1.异步django的http请求是同步的,通过gevent的协程来实现异步就解决了,很快。2.缓存和队列用ZeroMQ、Memcached来做缓存和队列就解决了。3.影响性能的函数如果真的有CPU密集型的函数影响性能,可以编译成C来解决性能问题,一些矩阵操作也可以通过numpy来解决

Django Web开发指南的作者介绍

Jeffery Forcier现在是Digital Pulp,Inc.的一名系统管理员和Web后台工程师。他在PHP/Python的Web开发上有7年的经验,自2005年Django问世起他就在工作和业余时间里使用这个框架。Paul Bissex很早就开始使用Django,并且开发维护着Django社区的在线着色网站dpaste.com。从1996年起,他就开始主持The Well(well.com),Wired杂志称之为“全世界最有影响力的在线社区”。Wesley Chun是Prentice Hall的畅销书《Core Python Programming》(corepython.com)、配套的视频教程《Python Fundamentals》(LiveLessons DVD)的作者,以及本书(withdjango.com)的合著者。

如何用Django实现收藏功能

1. Django Forms的强大之处有些django项目并不直接呈现HTML, 二是以API框架的形式存在, 但你可能没有想到, 在这些API形式的django项目中也用到了django forms. django forms不仅仅是用来呈现HTML的, 他们最强的地方应该是他们的验证能力. 下面我们就介绍几种和Django forms结合使用的模式:2. 模式一: ModelForm和默认验证最简单的使用模式便是ModelForm和model中定义的默认验证方式的组合:myapp/views.pyfrom django.views.generic import CreateView, UpdateViewfrom braces.views import LoginRequiredMixinfrom .models import Articleclass ArticleCreateView(LoginRequiredMixin, CreateView):model = Articlefields = (;title;, ;slug;, ;review_num;)class ArticleUpdateView(LoginRequiredMixin, UpdateView):model = Articlefields = (;title;, ;slug;, ;review_num;)正如以上代码中看到的一样:ArticleCreateView和ArticleUpdateView中设置model为Article两个view都基于Article model自动生成了ModelForm这些ModelForm的验证, 是基于Article model中定义的field转换而来的3. 模式二, 在ModelForm中修改验证在上面的例子中, 如果我们希望每篇article title的开头都是new, 那么应该怎么做呢? 首先我们需要建立自定义的验证(validator):utils/validator.pyfrom django.core.exceptions import ValidationErrordef validate_begins(value):if not value.startswith(u;new;):raise ValidationError(u;Must start with new;)可见, 在django中的验证程序就是不符合条件便抛出ValidationError的function, 为了方便重复使用, 我们将它们放在django app utils的validators.py中.接下来, 我们可以在model中加入这些validator, 但为了今后的方便修改和维护, 我们更倾向于加入到ModelForm中:myapp/forms.pyfrom django import formsfrom utils.validators import validate_beginfrom .models import Articleclass ArticleForm(forms.ModelForm):dev __init__(self, *args, **kwargs):super(ArticleForm, self).__init__(8args, **kwargs)self.fields[title].validators.append(validate_begin)class Meta:model = ArticleDjango的edit views(UpdateView和CreateView等)的默认行为是根据view中model属性, 自动创建ModelForm. 因此, 我们需要调用我们自己的Modelform来覆盖自动创建的:myapp/views.pyfrom django.views.generic import CreateView, UpdateViewfrom braces.views import LoginRequiredMixinfrom .models import Articlefrom .forms import ArticleFormclass ArticleCreateView(LoginRequiredMixin, CreateView):model = Articlefields = (;title;, ;slug;, ;review_num;)form_class = ArticleFormclass ArticleUpdateView(LoginRequiredMixin, UpdateView):model = Articlefields = (;title;, ;slug;, ;review_num;)form_class = ArticleForm4. 模式三, 使用form的clean()和clean_lt;field;()方法如果我们希望验证form中的多个field, 或者验证涉及到已经存在之后的数据, 那么我们就需要用到form的clean()和clean_lt;field;()方法了. 以下代码检查密码长度是否大于7位, 并且password是否和password2相同:myapp/forms.pyfrom django import formsclass MyUserForm(forms.Form):username = forms.CharField()password = forms.CharField()password2 = forms.CharField()def clean_password(self):password = self.cleaned_data[;password;]if len(password) lt;= 7:raise forms.ValidationError(password insecure)return passworddef clean():cleaned_data = super(MyUserForm, self).clean()password = cleaned_data.get(;password;, ;;)password2 = cleaned_data.get(;password2;, ;;)if password != password2:raise forms.ValidationError(passwords not match)return cleaned_data其中需要注意的是, clean()和clean_lt;field;()的最后必须返回验证完毕或修改后的值.5. 模式四, 自定义ModelForm中的field我们会经常遇到在form中需要修改默认的验证, 比如一个model中有许多非必填项, 但为了信息完整, 你希望这些field在填写时是必填的:myapp/models.pyfrom django.db import modelsclass MyUser(models.Model):username = models.CharField(max_lenh=100)password = models.CharField(max_lenh=100)address = models.TextField(blank=True)phone = models.CharField(max_lenh=100, blank=True)为了达到以上要求, 你可能会通过直接增加field改写ModelForm:请不要这么做myapp/forms.pyfrom django import formsfrom .models import MyUserclass MyUserForm(forms.ModelForm):请不要这么做address = forms.CharField(required=True)请不要这么做phone = forms.CharField(required=True)class Meta:model = MyUser请不要这么做, 因为这违反不重复的原则, 而且经过多次的拷贝粘贴, 代码会变得复杂难维护. 正确的方式应当是利用__init__():myapp/forms.pyfrom django import formsfrom .models import MyUserclass MyUserForm(forms.ModelForm):def __init__(self, *args, **kwarg):super(MyUserForm, self).__init__(*args, **kwargs)self.fields[;address;].required = Trueself.fields[;phone;].required = Trueclass Meta:model = MyUser值得注意的是, Django forms也是Python类, 类可以继承和被继承, 也可以动态修改.

为什么很多星际1高手打不好星际2,像bisu,stork,jangbi,反而像星际1一般的roro,rain反而都很强势

都有孩子了。

这段Django代码有什么问题吗?(Django version 4.1.4)

根据您提供的代码片段,目前我看不到任何明显的错误。然而,这是一个部分代码,可能存在其他问题,例如导入语句或函数实现。在评估代码的准确性和问题之前,建议您提供完整的代码段,包括所有导入语句、视图函数的实现以及其他相关部分。这样我就能够更全面地检查代码,并提供有关可能存在的问题或改进建议的更准确的反馈。请提供完整的代码段,以便我能够给出更准确的评估和帮助。

mac下的pycharm不能安装Django

贴出你的这个文件/Library/Python/2.5/site-packages/pip-1.4.1-py2.5.egg/pip/vendor/distlib/compat.py的第276行,return b""的上下30行

django cursor = connection.cursor是干什么用的

CursorLocation 属性 (ADO) 设置或返回游标引擎的位置。 设置和返回值 设置或返回可设置为以下某个常量的长整型值。 常量 说明 adUseNone 没有使用游标服务。(该常量已过时并且只为了向后兼容才出现)。

Myeong-gapJang人物介绍

Myeong-gapJangMyeong-gapJang是一名演员,代表作品有《那天之后》等。外文名:Myeong-gapJang职业:演员代表作品:《那天之后》合作人物:李淑经电影作品

24-8,janggogae-ro,117beon-gil,seo-gu,incheon,south korea韩国地址,求大神翻译

janggogae ro, 8, 117beon uc9c8uc740, uc11cuc6b8 uc778ucc9c, ud55cuad6d.