Develop Web site "Go" in Eclipse environment with Python+django

Source: Internet
Author: User
Tags central time zone sessions sqlite database



First, create a project
If this is your first time using Django, then you have to do some initial setup. That is, by automatically generating code to build a Django project--a set of settings for a Django project, including database configuration, Django detailed options settings, and Application feature configuration, the following steps are shown below.



1. Create a new Django project


Select SQLite Database



2. Create a website module app



3. Test whether the newly created module is normal


Validating models...

0 errors found
March 12, 2014 - 10:26:53
Django version 1.6.2, using settings ‘mysite.settings‘
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.


After the server starts up, go to the browser to enter the URL: http://127.0.0.1:8000, you will see a delightful, soft light blue "Welcome to Django" page. Indicates that it is working properly!

Let's take a look at what MySite has created:

These files are:
A, the outer mysite directory is just a container for your project. For Django, the directory name is not important; You can rename it to your liking.
B, manage.py: A useful command-line tool that allows you to interact with the Django project in a variety of ways.
C, the inner MySite directory is the actual Python package in your project. The directory name is the Python package name, through which you can import anything inside it. (E.g.import mysite.settings).
D, mysite/__init__.py: an empty file that tells Python that the directory is a python package.
E, mysite/settings.py: setup/configuration for this Django project.
F, mysite/urls.py: The URL statement for the Django project; a Django-driven Web site "directory."
G, mysite/wsgi.py: A portal for a WSGI-compatible Web server to run your project.



Change port number
By default, the development server that is started:d the Jadmin:runserver command listens only to port 8000 on the local IP.



If you want to change the port of the server, pass it as a command line parameter. For example, the following command initiates a server that listens on port 8080:


C:\Users\D-117>cd F:\workspace\mysite\src\mysite\ #manage.py文件所在目录,即mysite项目下
C:\Users\D-117>f:
F:\workspace\mysite\src\mysite>python manage.py runserver 8080
Validating models...

0 errors found
March 12, 2014 - 10:31:27
Django version 1.6.2, using settings ‘mysite.settings‘
Starting development server at http://127.0.0.1:8080/
Quit the server with CTRL-BREAK.


If you want to change the server IP, pass it along with the port number. So, to listen to all public IP addresses (if you want to show off your work on other computers), use:
Python manage.py runserver 0.0.0.0:8000



Database Settings
Now, edit mysite/settings.py. This is a common Python module that contains the module-level variables that represent the Django settings. Change the value of the following key under ' Default ' in databases to match your database connection settings.
A, engine – from ' django.db.backends.postgresql_psycopg2 ', ' django.db.backends.mysql ', ' Django.db.backends.sqlite3 ', ' django.db.backends.oracle ' Select a
B, name – your database name. If you use SQLite, the database will be a file on your computer; In this case,: Setting:name will be a complete absolute path and also contain the name of the file. If the file is not  
exists, it is created automatically the first time the database is synchronized (see below). When you specify a path, you always use a forward slash, even under Windows (for example: ' C:/homes/user/mysite/sqlite3.db ').
C, user – your database user name (not required under SQLite).
D, password – your database password (not required under SQLite).
E, host – your database host address. If it is the same physical machine as your database server, leave it blank (or set to 127.0.0.1) (not required under SQLite).  
If you are creating a new database, we recommend using SQLite only, change the ENGINE to ' Django.db.backends.sqlite3 ' and set the NAME to the place where you want to store the database. SQLite is built into Python, so you don't need to install anything to support your database.



Attention:
If you're using PostgreSQL or MySQL, make sure you've created a database. or through your database interface "CREATE database database_name;" command to do this.
If you use SQLite, you don't need to create anything beforehand-the database file will be created automatically when needed.



When you edit settings.py, change the time_zone to your time zone. The default value is the U.S. Central Time Zone (Chicago). Also, note the Installed_apps settings at the bottom of the file. It saves the current Django instance that has been activated
There is a Django app. Each app can be used by multiple projects, and you can package and distribute it to other people in their projects.



By default,: Setting:installed_apps contains the following apps, which are provided by Django:


Django.contrib.auth – authentication system.
Django. Contrib. Contenttypes – content type framework.
Django.contrib.sessions – session framework.
Django.contrib.sites – website management framework.
Django. Contrib. Messages – message framework.
Django. Contrib. Staticfiles – static file management framework.


These apps are typically included by default.



Every app in these apps uses at least one database table, so we need to create the tables in the database before using them. To do this, run the following command: Python manage.py syncdb, as described below.



At this point, the project development environment has been established, we can start.



Second, create the model



4. Edit the Code
4.1 Modifying blog.models.py


from django.db import models
from django.contrib import admin

# Create your models here.
class BlogPost(models.Model):
    title = models.CharField(max_length = 150)
    content = models.TextField()
    timestamp = models.DateTimeField()
    
class BlogPostAdmin(admin.ModelAdmin):
    list_display = (‘title‘, ‘content‘, ‘timestamp‘)

admin.site.register(BlogPost, BlogPostAdmin)


We will create a blogpost model that contains the title, content, and timestamp three fields. Each model inherits from the class of the Django.db.models.Model subclass to describe. Each model
Have some class variables, each of which represents a database field.

Each field is represented by an instance of a field-for example, Charfield represents a field of character type and a field Datetimefield represents a datetime type. This will tell Django that each
What type of data is stored in the field.

Each field instance name is the name of the field (for example: title, content, timestamp), and its format belongs to the affinity machine type. This is used in your Python code.
Value, and your database will use this value as the column name for the table.



4.2 Modifying blog.views.py


# Create your views here.
from django.template import loader,Context
from django.http import HttpResponse
from blog.models import BlogPost

def archive(request):
    posts = BlogPost.objects.all()
    t = loader.get_template(‘archive.html‘)
    c = Context({‘posts‘: posts})
    return HttpResponse(t.render(c))


4.3 Modify mysite.setting.py, find the following section to modify


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


4.4 Modifying mysite.urls.py


from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

from blog.views import archive

urlpatterns = patterns(‘‘,
    # Examples:
    # url(r‘^$‘, ‘mysite.views.home‘, name=‘home‘),
    # url(r‘^blog/‘, include(‘blog.urls‘)),

    url(r‘^admin/‘, include(admin.site.urls)),
    url(r‘^blog/‘, archive),
)


5. Create a Style page template
Please add the Templates folder under the Package blog and set up two Web files under Templates: Archive.html and base.html



5.1 Edit archive.html


{% extends "base.html" %}  

{% block content %}  

{% for post in posts %}  

<h1>{{ post.title}}</h1>  

<p>{{ post.content }}</p>

<p>{{ post.timestamp|date:"1, F jS"}}</p>

{% endfor %}  

{% endblock %}


5.2 edit base.html
<html>
<style type="text/css">
body { color: #edf; background: #453; padding: 0 5em; margin:0 }
h1 { padding: 2em lem; background:#675 }
h2 { color: #bf8; border-top: 1px dotted #fff; margin-top: 2em }
p { margin: lem 0 }
</style>
<body>
<h1><center>Alexia‘s Blog</center></h1>
{% block content %}
{% endblock %}
</body>
</html>
3、 Synchronize database
Set up your account and password to prepare for logging in the blog management background.
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
You just installed Django‘s auth system, which means you don‘t have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use ‘d-117‘): root
Email address: [email protected]
Password: root
Password (again): root
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Finished "F:\workspace\mysite\src\mysite\manage.py syncdb" execution.
4、 Run tests
Login interface, login account and password are set when initializing the database.
After successful login, go to the following page:
On this page, you can add blog articles:
After publishing successfully, enter the website: http://127.0.0.1:8000/blog/ to view. The test is successful!
Using Python + Django to develop web site in eclipse environment




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: 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.