用Django搞网页(2)

用Django搞网页(2)


添加第一个简单的app

  • 运行虚拟环境
  • 在环境中添加一个app
(LN_env) cyz@DESKTOP-LAPNLQ4:~/Program$ python manage.py startapp Learning_note
(LN_env) cyz@DESKTOP-LAPNLQ4:~/Program$ ls
LN_env  Learning_note  Note  db.sqlite3  manage.py
(LN_env) cyz@DESKTOP-LAPNLQ4:~/Program$ vi Learning_note/
(LN_env) cyz@DESKTOP-LAPNLQ4:~/Program$ vi Learning_note/
__init__.py  admin.py     apps.py      migrations/  models.py    tests.py     views.py

实际上就是建立了一个目录,名字就是app的名字,里面放着实现这个app功能的必要文件。其中models.py就是管项目的,比如这个app中需要用户建立一个叫做’Topic‘的条目,那就要在里面添加一个叫做”Topic“的类(在网站的角度,大概叫做模型吧),并且设置好它的属性,这样每次添加一条这个条目,就相当于建立了一个Topic的实例。

models.py里面就写成这样:


from django.db import models

# Create your models here.
class Topic(models.Model):
    """Topics of users learning"""
    text = models.CharField(max_length=200)    #一个属性,定义为具有字数限制的字符型数据
    date_add = models.DateTimeField(auto_now_add=True)   #记录创建时间

    def __str__(self):
        """return the strings expression of this model"""
        return self.text

然后在项目的”管理目录“下,也就是startprogram的时候建立的Note目录,找到”setting.py“文件——它将涉及到的所有app条目整理起来,好让Django知道加载哪些app——在其中加入新建的app名。然后对以上改动进行”同步“(书上说是叫做移植,我觉得大概就是保存更改的感觉)。

(LN_env) cyz@DESKTOP-LAPNLQ4:~/Program$ python manage.py makemigrations Learning_note
Migrations for 'Learning_note':
  Learning_note/migrations/0001_initial.py
    - Create model Topic
(LN_env) cyz@DESKTOP-LAPNLQ4:~/Program$ python manage.py migrate
Operations to perform:
  Apply all migrations: Learning_note, admin, auth, contenttypes, sessions
Running migrations:
  Applying Learning_note.0001_initial... OK

如何删除一个app?

其中出现了一个小失误,就是app名错写成了”Learing_note“,与setting.py中的录入信息”Learning_note“不相符,就不能成功移植。所以我又把原有的app删除:

在Django中如何正确的删除app

其中删除model这一步我好像没有用到,大概因为我的model过于简单,没有涉及文件引用,并且没有成功移植,所以直接进行了第二步。以后可以重新考虑这个。

建立一个超级用户

(LN_env) cyz@DESKTOP-LAPNLQ4:~/Program$ python manage.py createsuperuser
Username (leave blank to use 'cyz'): cyz
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.

然后还是要在

发布了29 篇原创文章 · 获赞 3 · 访问量 6709

猜你喜欢

转载自blog.csdn.net/weixin_43316938/article/details/87908889