Django Creates a simple blog

Source: Internet
Author: User

1. Create a MySite project using django-admin.py

[Email protected]:~/pycharmprojects$ django-admin.py startproject MySite

2. Enter the project directory, start the server, test connectivity

[Email protected]:~/pycharmprojects$ cd mysite/[email protected]-thinkpad-t450:~/pycharmprojects/mysite$./manage.py Runserver0.0.0.0:8000Validating Models ...0Errors Foundapril in, .- .: -: -Django version1.6.5, using Settings'mysite.settings'starting Development Server at http://0.0.0.0:8000/Quit the server with control-c.[ in/apr/ .  .: -: -]"get/http/1.1"  $ 1757

3. Create a blog app

[email protected]:~/pycharmprojects/mysite$./manage.py Startapp blog[email protected]-thinkpad-t450:~/ pycharmprojects/mysite$ Tree.├──blog│├──admin.py│├──__init__.py│├──models.py│├──tests.py│└──views . py├──manage.py└──mysite    ├──__init__.py    ├──__init__.pyc    ├──settings.py    ├──settings.pyc    ├── urls.py    ├──urls.pyc    ├──wsgi.py    └──wsgi.pyc2 files

4. Tell Django that the app is part of the project and edit the setting.py configuration file

Installed_apps = (
   'django.contrib.auth', 'Django.contrib.admin','Django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'Django.contrib.staticfiles', 'Blog', #添加的部分, pay attention to the back, number)

5. Design Model

The core part of the Django-based blog app: models.py. This is where the blog data structure is defined. Depending on the dry (code not duplicated) principle, Django will try to take advantage of the model information you provide to your application.

5.1 Under the models.py under the blog package to write the following code: Set 3 variables, there is a default ID variable, is self-increment. (In fact, it is the database column)

 from Import Models class blogpost (models. Model):    = models. Charfield (max_length=150)    = models. TextField ()    = models. Datetimefield ()

5.2 Setting up the database (using MySQL)

The default in Django is SQLite, and I'm using MySQL here, and I need to modify the database's basic information in the configuration file (first create the database, named Djangodb):

DATABASES = {    'default':{        'ENGINE':'Django.db.backends.mysql',        'NAME':'Djangodb',        'USER':'Root',        'PASSWORD':'xxxxxx', #连接数据库服务器的密码'HOST':'localhost',        'PORT':'3306',    }}

5.3 Creating a Table

[Email protected]:~/pycharmprojects/mysite$./manage.py syncdb

When executing the SYNCDB command, Django looks for each models.py file in the Installed_apps and creates a data table for each model found. Comparing with the parameters in Profile Installed_apps, you can see that SYNCDB has created one or more tables for each app.

In addition to the output of the SYNCDB command, there are

You just installed Django'sauth system, which means you don'T has anysuperusers defined. Would to createone now? (yes/'sunny'0object0 fixture (s)

This is the full output. After that, I built a super user in the AUTH system to easily join Django's automatic admin application.

5.4 Setting the Auto Admin app

The automated backend application admin is called the Django Jewel, creating the Gospel of a simple crud interface for Web applications. Since this is not a necessary component in Django, it must be specified in the setting.py file. Need to add a line ' django.contrib.admin ' under ' Django.contrib.auth ' in the Installed_apps tuple;

Each time you add a new app to your project, run the SYNCDB command to make sure that the tables it needs are already created in the database.

View the code in urls.py:

 fromDjango.conf.urlsImportpatterns, include, url fromDjango.contribImportadminadmin.autodiscover () urlpatterns= Patterns ("',    #Examples:    #URL (r ' ^$ ', ' mysite.views.home ', name= ' home '),    #URL (r ' ^blog/', include (' Blog.urls ')),URL (r'^admin/', include (Admin.site.urls)), #告诉Django去加载默认的admin站点, which is a special object that is used for the contrib admin application. )

After that, you need to tell the editing application what model to display in the admin window for editing. Edit the code in models.py in the blog, only need to define the previously mentioned default Admin site, and register it with blogpost model on the line:

 from Import Models  from Import Admin class blogpost (models. Model):    = models. Charfield (max_length=150)    = models. TextField ()    = models. Datetimefield () Admin.site.register (blogpost)

6. Using admin

Run the./manage.py runserver command, and then enter http://127.0.0.1:8000/admin/in the browser, a login window will appear

After logging in using the Superuser username and password, the following interface appears:

Click Add after blogpost, inside will appear in the model of the three elements title, body, Timestampe, add and click Save;

Add a Blogpostadmin class to the models.py file and add it to the registration code:

 fromDjango.dbImportModels fromDjango.contribImportAdminclassblogpost (models. Model): Title= Models. Charfield (max_length=150) Body=models. TextField () timestamp=models. Datetimefield ()classblogpostadmin (admin. Modeladmin): List_display= ('title','timestamp') Admin.site.register (blogpost,blogpostadmin)

The output is generated based on the List_display variable (title,timestamp) in the Blogpostadmin class.

7. Create a public part of the blog

This section is part of the public-facing page. From a Django perspective, a page has three typical components:

    • A template that is responsible for displaying the information that is passed in (in a Python-like Dictionary object context).
    • A view, which is responsible for getting the information to be displayed, is usually taken from the database.
    • A URL pattern that matches the received request to the view function and sometimes passes some parameters to the view.

7.1 Creating templates (Template)

Django creates a simple blog

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: info-contact@alibabacloud.com 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.