Django笔记
基础部分
结构:
- URLs -->views --> models --> Templates
- URLs的参数<?P< name >\d+>可以传入views和Templates
创建项目:
- django-admin startproject project_name
创建数据库
创建模型:
- python manage.py startapp app_name
激活模型(settings.py):
- INSTALLED_APPS添加app_name
- python manage.py makemigrations app_name
- python manage.py sql app_name
- python manage.py syncdb
返回SQL语句:
- python manage.py sqlmigrate app_name 0001
创建一个管理员用户
- python manage.py createsuperuser
广播
- python manage.py runserver 127.0.0.1:8080
中级部分
models.py的设置:
- models.ForeignKey(类名)设置外键
views.py的设置:
a = app_classname.objects.all() 返回app_classname的所有项目(添加app_classname的__str__方法才能返回a的实际值)
app_classname.objects.get(id或者pk)
app_classname.objects.filter()
{ 当类型为CharField的时候,有_startwith的方法
为DateTimeField的时候,有_year等方法 }
- a.id
- a.classdefname 对于外键的,有all(),create(),count()方法
admin.py设置:
- 使app在管理站点中可编辑: admin.site.register(app_classname)
- 高级:
(类)表单管理:
class ChoceInline(admin.StackedInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields':['question_text']}),
('Date information',{'fields':['pub_date'],'classes':['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields = ['question_text']
admin.site.register(Question, QuestionAdmin)
```
#### URL:
* from django.conf.urls import url url(regex, views,kwargs, name)
* 主URL:
url(r'^$', views.class_name, name)
* app_url:
url(r'^app/', include('app.urls'))
#### HTML:
* url中:blog/article/(?P<article_id>\d+)$ 则{% url 'blog:detail' article.id %}
* {% url '主url_name:次url_name' 传入参数 %}