Environment:
Python3.5+
Conda
Django 2.0
pip install django==2.0
Commands to Start a Project
1. Create a project:
sudo django-admin startproject xxx
3. Create a app in project
sudo python3 manage.py startapp app1
Different Usages of Files
1. views.py
Deal with visible things
2. models.py
Define the models
3. admin.py
Define Admin module
4. apps.py
Defile the apps
5. tests.py
place to write test cases
6. urls.py (We create ourselves)
manage routers
Url Address:
http://127.0.0.1:8000/app1/hello_world
Create Models
- Update defined date to database
Defile models in models.py:
class Article(models.Model):
# ID
article_id = models.AutoField(primary_key = True)
# Title
title = models.TextField()
# Abstract
abstract = models.TextField()
# Date
pub_date = models.DateTimeField(auto_now = True)
# Content
content = models.TextField()
1. Create migration files
sudo python3 manage.py makemigrations
2. Migratie files
sudo python3 manage.py migrate
Then, database will automatically update according to the setting
Django Shell
- Using Django Shell to create an article
1. Open shell mode
sudo python3 manage.py shell
2. import model
from app1.models import Article
3. Create a new article
a = Article()
4. define properties
a.title = 'test shell'
a.content = 'test content'
a.article_id = 1
a.abstract = 'test abstract'
Django Admin Module
How to Use Django Admin
http://127.0.0.1:8000/admin
Show title in admin page
def __str__(self):
return self.title
Register models in admin
from .models import Article
admin.site.register(Article)
Display content in the page
def article_content(request):
article = Article.objects.all()[0]
id = article.article_id
title = article.title
content = article.content
abstract = article.abstract
pub_date = article.pub_date
return_str = 'id: %s, ' \
'title: %s, ' \
'content: %s, ' \
'abstract: %s, ' \
'pub_date: %s' % (id,
title,
content,
abstract,
pub_date)
return HttpResponse(return_str)
path('content', app1.views.article_content)
path('app1/', include('app1.urls'))
Comments
Post a Comment