Django personal simple Blog-data model, djangoblog

Source: Internet
Author: User

Django personal simple Blog-data model, djangoblog

When talking about the data model, you must mention MVC. MVC is the most popular development framework in modern web development. It separates data from business logic, reducing the high coupling between applications. I personally like the MVC development framework very much. In addition to the above features, it makes web development very flexible, in ASP. NET, the traditional ASP. NET development often uses a lot of bloated server-side controls, it is very troublesome to customize and has limitations. In recent years, MVC has been developed everywhere. java, php, ruby,. NET, and even javascript all have corresponding MVC frameworks. Of course, django is also one of them.

As a part of MVC, the data model is used to encapsulate data related to the application's business logic and the data processing method, and has the right to directly access the data, and does not care about the specific business logic.

Today, we will go on to the previous article about django's personal simple Blog-building the project structure. This system is used as an example to describe the design and operation of the data model in django.

The system uses mysql for database storage. Therefore, you must first ensure that mysql is installed and then install the MySQLdb module. You can download and install the latest version of windows or linux, and then enter the following in the Command window:

pythonimport MySQLdb

If no error is displayed, the installation is successful.

Enable the background management function provided by django:

In fact, django comes with a complete and available background management system, which is part of the django. contrib package and can flexibly expand the new app features we have added. You only need to run a few simple commands to easily connect the data model with the mysql database. First, open the settings. py file in the project we created. The default configuration in the file contains the following Configuration:

INSTALLED_APPS = (    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',)

Each app has its own data model. For example, the blogapp we created in the previous article has models under its directory. the py file is used to define the data model, and the django app can also be found in the django installation directory.

To interact with mysql DATA, you must first configure the mysql connection information, similar to the connection string in. NET. The configuration information is in the settings. py file. The configuration format is as follows:

# Windows: DATABASES = {'default': {'Engine ': 'django. db. backends. mysql ', # identifies the database engine type. postgresql, sqlite3, and oracle 'name' can also be used: "mypythonblog", # Database NAME 'user': 'xxxxxx ', # If the user name is sqlite3, it can be blank 'Password': 'xxxxxxxxxx', # If the PASSWORD is sqlite3, it can be blank 'host': 'localhost', # server 'Port ': '', # port default port can be empty mysql default port is 3306 }}# linux CentOS6.5DATABASES = {'default': {'Engine ': 'django. db. backends. mysql ', 'name': "mypythonblog", 'user': 'root', # username. 'Password': 'xxxxxxx', # PASSWORD 'host': '/var/lib/mysql. sock ', # mysql uses Unix socket to connect to the specified socket 'Port ':'',}}


Go to the root directory of the project and run the following command to start the interactive Interpreter: python manage. py shell

Enter the following code:

from django.db import connectioncursor = connection.cursor()

If no error occurs, the database configuration is normal. Otherwise, a specific error message is displayed.

Next, we will take a crucial step to synchronize the data model that comes with django to the database. In this process, django will verify its correctness Based on the app set under INSTALLED_APPS and synchronize the model to the database, to generate the corresponding table structure, run the following command to enter the project root directory, that is, manage. directory where py is located:

python syncdb

After running the command, the following content appears:

Http: // 1989/admin. The following logon interface is displayed:

Data Model Design:

As this is just a simple blog and has limited functions, the data model is also relatively simple, including only three tables: Article table, classification table, and comment table, for user authentication, use the user table that comes with django.

In the blogapp we created, there is a models. py file, and the Model definition is in this file. Each data Model corresponds to a class, as long as the class inherits from models. Model.

The "article" model definition, the definition code is as follows:

Class fz_Article (models. model): title = models. charField (max_length = 56, verbose_name = 'title') content = models. textField (verbose_name = 'Article content') author = models. foreignKey (User) # User is a built-in User model definition of django. contrib. auth. models import User tags = models. charField (max_length = 1023, verbose_name = 'tag', blank = True) classic = models. foreignKey (fz_classic) publish_date = models. dateTimeField () ispublished = models. booleanField () commentcount = models. integerField (blank = True) readcount = models. integerField (blank = True)

The "classification" model definition code is as follows:

class fz_classic(models.Model):    name = models.CharField(max_length=56)    articecount = models.IntegerField()    def __unicode__(self):        return

"Comment" model definition, the Code is as follows:

class fz_comment(models.Model):    article = models.ForeignKey(fz_Article)    comment_content = models.TextField()    comment_date = models.DateField()    email = models.EmailField()    commentator = models.TextField()

I will not talk about the definition rules and how to define the model. I don't need to talk about it. I will understand it when I find a book or read several articles.

Start to install the custom model, find settings. py, add 'fengzhengblog. blogapp' to the value set in INSTALLED_APPS, set the package name to fengzhengBlog, and set the app name to blogapp>

Run the following command to check whether the model definition is correct: python manage. py validate. If it is correct, the system will prompt: 0 errors found.

Run the following command to generate the SQL statement corresponding to the model: python manage. py sqlall blogapp. The generated SQL statement is as follows:

BEGIN;CREATE TABLE `blogapp_fz_classic` (    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,    `name` varchar(56) NOT NULL,    `articecount` integer NOT NULL);CREATE TABLE `blogapp_fz_article` (    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,    `title` varchar(56) NOT NULL,    `content` longtext NOT NULL,    `author_id` integer NOT NULL,    `tags` varchar(1023) NOT NULL,    `classic_id` integer NOT NULL,    `publish_date` datetime NOT NULL,    `ispublished` bool NOT NULL,    `commentcount` integer NOT NULL,    `readcount` integer NOT NULL);ALTER TABLE `blogapp_fz_article` ADD CONSTRAINT `author_id_refs_id_a7f24472` FOREIGN KEY (`author_id`) REFERENCES `auth_user` (`id`);ALTER TABLE `blogapp_fz_article` ADD CONSTRAINT `classic_id_refs_id_992b177f` FOREIGN KEY (`classic_id`) REFERENCES `blogapp_fz_classic` (`id`);CREATE TABLE `blogapp_fz_comment` (    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,    `article_id_id` integer NOT NULL,    `comment_content` longtext NOT NULL,    `comment_date` date NOT NULL);ALTER TABLE `blogapp_fz_comment` ADD CONSTRAINT `article_id_id_refs_id_cbb24377` FOREIGN KEY (`article_id_id`) REFERENCES `blogapp_fz_article` (`id`);CREATE INDEX `blogapp_fz_article_e969df21` ON `blogapp_fz_article` (`author_id`);CREATE INDEX `blogapp_fz_article_3da92ebb` ON `blogapp_fz_article` (`classic_id`);CREATE INDEX `blogapp_fz_comment_0f1c6027` ON `blogapp_fz_comment` (`article_id_id`);COMMIT;

The script contains the table structure and the dependency between the primary and Foreign keys. You can see that the data table to be generated is renamed to "app name_model name ". This command only generates an SQL statement and is not executed in the database. To execute synchronization, run the following command: python manage. py syncdb. This command has been executed once. If it is executed again, the models not synchronized to the database under INSTALLED_APPS will be synchronized to the database, and those that have already been synchronized in the database will not be synchronized, fields are modified or not synchronized. After successful synchronization, open the SQL statement and you will find that the table structure corresponding to the above model already exists.

If the file is not synchronized and there is no error, it may be because the migrations folder exists in blogapp. After deletion, run the command again.

Next, start the website and access http: // 1989/admin/. Enter the user name and password to go to the Management page, if you say that you want to install an app, the corresponding management function will appear. How can we still only use the management function area of the app Auth. Don't worry, there is an admin in the blogapp directory. the file of py already exists. Its function is to register this app to the background management, and you can also set some functions related to the background management function here, such as sorting fields and searchable fields. I don't need complex functions. As long as the most basic functions are available, open admin. py and add the following code in it:

From django. contrib import adminfrom fengzhengBlog. blogapp. models import * # import model definition # Register your models here. # register the model to the admin console. site. register (fz_Article) admin. site. register (fz_comment) admin. site. register (fz_classic)

After saving, refresh the page and come out. The Blogapp is added below Auth to manage articles, categories, and comments. The English interface is not very refreshing. Find the required age_code = 'en-us' in settings. py and change it to required age_code = 'zh-cn'. Then, refresh it.

The preceding Code defines the data model, synchronizes data to the database through commands, and then activates the background management function provided by django. The basic functions are available here, including managing users, user groups, managing articles, categories, and comments can all be done through the built-in background management interface. Of course, using it does not mean it is easy to use, I will introduce how to develop my own background management functions and how to display them later.

Create a simple blog using the python-django framework

A comment box is displayed when an article is displayed. After the user inputs the text, it is submitted to the background to verify whether the article and comment are the same user. A prompt is displayed, indicating that the comment cannot be sent to the user, otherwise, save the comment and prompt that the comment is successful.
Blog development in python + django

It is estimated that the INSTALLED_APPS settings in your settings. py are incorrect.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.