1. 创建 Django project
- start project
django-admin startproject name
2. 创建 Django App
- start app
python3 manage.py startapp firstapp
- setting 添加 app
INSTALLED_APPS在末尾添加创建的app的名字
3. 数据库
- 合并
python3 manage.py makemigrations
python3 manage.py migrate
- 运行服务器
python3 manage.py runserver
4.html&css文件
在app下创建templates&static
重置模板路径
'DIRS': [os.path.join(BASE_DIR, 'template').replace('\\','/')]
- html增加模板标签
{% staticfiles %}
herf = "{% static 'css/name.css' %}"
{% static 'images/name.png' %}
5.创建admin
python3 manage.py createsuperuser
http://127.0.0.1:8000/admin
- admin.py添加想要的数据项
from nameapp.modles import People
admin.site.register(People)
- models.py设置内容列表的标题
def __str__(self):
return self.name
- models.py添加文章列表
class Article(models.Model):
headline = models.CharField(null = True, blank = True, max_length=500)
content = models.TextField(null = True, blank = True)
- admin.py添加文章数据项
from firstapp.models import People,Article
admin.site.register(Article)
python manage.py makemigrations
python manage.py migrate
6.Views.py
from firstapp.models import People, Article
def index(request):
context = {}
article_list = Article.objects.all()
context['article_list'] = article_list
index_page = render(request, 'first_web_2.html', context)
return index_page
7. 向html文件中添加模板标签
{% for article in article_list %}
{{ article.headline }}
{{ article.content|truncatewords:20 }}
{% endfor %}
8. urls.py
from firstapp.views import index
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index', index, name='isndex'),
]
python manage.py runserver
http://127.0.0.1:8000/index