在html中加入Google Drive上的视频流

当然,在网页中加入媒体可以使用静态文件

 

<video controls>
        <source src="{% static "video/video_name.m4v" %}">
</video>

 

要加入Google Drive上的视频流就要先把视频上传到Google Drive,然后把访问权限调整为public(任何人均能访问),必要时需将所在文件夹也设为public。

之后就是要获得视频流的url了。Google Drive直接分享的链接并不是直接的视频文件,但是却包含了视频文件的ID:

https://drive.google.com/open?id=blabla

我们需要记录下这个ID,然后在html文件中写:

 

<video controls>
        <source src="https://www.googledrive.com/host/the_ID_you_copied"/>
        Your browser does not support the video tag.
</video>

注意,url的https不能省略,否则就无法加载出视频。

关于Django部署到Apache2之后admin的css不见的问题

在本地的时候,admin的css是在django的目录下的。当部署到服务器之后,这些静态文件路径需要修正。

方法是在服务器上 /etc/apache2/sites-enables/PersonalWebsite.conf里面写好 路径的Alias 并且 给目录赋予权限:

注意这里alias有先后,不然alias会重叠,就无效了。

WSGIScriptAlias / /home/ubuntu/PersonalWebsite/PersonalWebsite/wsgi.py
WSGIPythonPath /home/ubuntu/PersonalWebsite
<Directory /home/ubuntu/PersonalWebsite/PersonalWebsite>
    <Files wsgi.py>
        Order deny,allow
        Require all granted
    </Files>
</Directory>

Alias /media/ /home/ubuntu/PersonalWebsite/media/ 

Alias /static/admin/ /usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/

Alias /static/ /home/ubuntu/PersonalWebsite/static/

 

<Directory /usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin>

    Require all granted

</Directory>

<Directory /home/ubuntu/PersonalWebsite/static> Require all granted </Directory> <Directory /home/ubuntu/PersonalWebsite/media> Require all granted </Directory>

Deploy to Heroku时的问题

Deploy to Heroku

 
https://devcenter.heroku.com/articles/getting-started-with-django#prerequisites
 
 pip install django-toolbelt
Error: pg_config executable not found.
Solution:sudo apt-get install libpq-dev python-dev
 

EC2上部署Django个人网站并连上Godaddy域名

项目命名为PersonalWebsite,后面各处取名时会用到。此项目数据库用的是Django自带的sqlite。

第一步:在AWS上创建新的EC2,选择Ubuntu Free Tier

这就是网站服务器了,可以通过ssh连接之。为了方便,写一个命令:$ ssh PersonalWebsite

# edit ~/.ssh/config

Host PersonalWebsite
HostName <ec2_hostname>
User ubuntu
IdentityFile "~/.ssh/<your_key_pair>.pem"

安装必要程序。可以通过执行写好的脚本文件

 

# filename: install.sh

sudo apt-get update && upgrade;
sudo apt-get install apache2 libapache2-mod-wsgi;
sudo apt-get install python-pip;
sudo pip install django;
sudo apt-get install mysql-server python-mysqldb;
sudo apt-get install git;

 

第二步 植入网站

先从github上拉下来: $ git clone <url>

我的Django网站文件结构如下

 

~/
    PersonalWebsite/
        App/
            __init__.py
            admin.py
            models.py
            tests.py
            urls.py
            views.py
        PersonalWebsite/
            __init__.py
            settings.py
            urls.py
            views.py
            wsgi.py
        static/
            css/
            images/
        template/
            app/
            other_html.html
        db.sqlite3
        manage.py

配置Apache服务器,在/etc/apache2/sites-enabled/PersonalWebsite.conf里声明wsgi.py和静态文件的路径。

 

WSGIScriptAlias / /home/ubuntu/PersonalWebsite/PersonalWebsite/wsgi.py
WSGIPythonPath /home/ubuntu/PersonalWebsite
<Directory /home/ubuntu/PersonalWebsite/PersonalWebsite>
    <Files wsgi.py>
        Order deny,allow
        Require all granted
    </Files>
</Directory>

Alias /media/ /home/ubuntu/PersonalWebsite/media/ 
Alias /static/ /home/ubuntu/PersonalWebsite/static/

<Directory /home/ubuntu/PersonalWebsite/static>
    Require all granted
</Directory>

<Directory /home/ubuntu/PersonalWebsite/media>
    Require all granted
</Directory> 

 

第三步 绑定域名

  1. 首先,在AWS里将EC2绑定一个Elastic IP(The Elastic IP address assigned to the instance, if applicable. Elastic IP addresses are static IP addresses assigned to your account that you can quickly remap to other instances.
    操作路径:AWS Dashboard => (左侧导航栏)Security & Network下的Elastic IP
     
  2. 在Godday.com购买了example.com域名
    在Domain => Domain Details => DNS ZONE FILE 中修改A(Host)的Record:
    使 @ (即此域名)对应上一步中的Elastic IP

 

小贴士

网站的更新流程可以是:在本地开发 --> 上传至Github --> 登入EC2 --> $ git pull --> 重启Apache

Django博客搭建工作笔记 四 其他

 


	

8.1. Forms - Basic Workflow 略

The basic steps involved in creating a form and allowing users to enter data via the form is as follows.

This workflow is a bit more complicated than previous workflows, and the views that we have to construct have a lot more complexity as well. However, once you undertake the process a few times it will be pretty clear how everything pieces together.

If you haven’t already got one, create a forms.py file within your Django application’s directory to store form-related classes.

Create a ModelForm class for each model that you wish to represent as a form.

Customise the forms as you desire.

Create or update a view to handle the form - including displaying the form, saving the form data, and flagging up errors which may occur when the user enters incorrect data (or no data at all) in the form.

Create or update a template to display the form.

Add a urlpattern to map to the new view (if you created a new one).

Function: add comment

 

9. User Authentication 略

 


	

 

11. Cookies and Sessions 略

 

12. User Authentication with Django-Registration-Redux 略

 

 

13. Bootstrapping Blog

 

		
  •  

  • 21. Deploying Your Project

    http://www.tangowithdjango.com/book17/chapters/deploy.html
  •  

  • Deploy!!!!!

  •  

  • on pythonAnywhere

  •  

  • First, open a Bash console from the PythonAnywhere Consoles tab by clicking the Bash link. When the terminal is ready for you to interact, enter the following commands.

    $ source virtualenvwrapper.sh
    $ mkvirtualenv rango
    https://github.com/Librius/PersonalWebsite.git
  •  

 

Django博客搭建工作笔记 三 Admin & Database & Static Media

  • Django中自带Admin

Run the server and visit http://127.0.0.1:8000/admin/

如果发生TemplateDoesNotExist at /admin/login/错误

check settings.py: in TEMPLATES, whether the “APP_DIR” is true. Since the template of admin is under its app directory
 
revise blog/admin.py
from django.contrib import admin
from blog.models import Category, Article

# Register your models here.

admin.site.register(Category)
admin.site.register(Article)
 

	

you can check out the official Django documentation on the admin interface for more information if you’re interested.

  • Database

 

Basic Workflows

Now that we’ve covered the core principles of dealing with Django’s models functionality, now is a good time to summarise the processes involved in setting everything up. We’ve split the core tasks into separate sections for you.

1. Setting up your Database

With a new Django project, you should first tell Django about the database you intend to use (i.e. configure DATABASES in settings.py). You can also register any models in the admin.py file to make them accessible via the admin interface.

2. Adding a Model

The workflow for adding models can be broken down into five steps.

  1. First, create your new model(s) in your Django application’s models.py file.
  2. Update admin.py to include and register your new model(s).
  3. Then perform the migration $ python manage.py makemigrations
  4. Apply the changes $ python manage.py migrate. This will create the necessary infrastructure within the database for your new model(s).
  5. Create/Edit your population script for your new model(s).

Invariably there will be times when you will have to delete your database. In which case you will have to run the migrate command, then createsuperuser command, followed by the sqlmigrate commands for each app, then you can populate the database.

Undertake the part two of official Django tutorial if you have not done so. 

 

 


		

		

在PersonalWebsite/settings.py里声明你的数据库

DATABASES = {

    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

挪到服务器上的话最好用MySQL之类 https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-DATABASE-ENGINE

 


		

 

To create a population script for Rango’s database, we start by creating a new Python module within our Django project’s root directory (e.g. <workspace>/tango_with_django_project/). Create the populate_rango.py file and add the following code.

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')

import django
django.setup()

from rango.models import Category, Page


def populate():
    python_cat = add_cat('Python')

    add_page(cat=python_cat,
        title="Official Python Tutorial",
        url="http://docs.python.org/2/tutorial/")

    add_page(cat=python_cat,
        title="How to Think like a Computer Scientist",
        url="http://www.greenteapress.com/thinkpython/")

    add_page(cat=python_cat,
        title="Learn Python in 10 Minutes",
        url="http://www.korokithakis.net/tutorials/python/")

    django_cat = add_cat("Django")

    add_page(cat=django_cat,
        title="Official Django Tutorial",
        url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")

    add_page(cat=django_cat,
        title="Django Rocks",
        url="http://www.djangorocks.com/")

    add_page(cat=django_cat,
        title="How to Tango with Django",
        url="http://www.tangowithdjango.com/")

    frame_cat = add_cat("Other Frameworks")

    add_page(cat=frame_cat,
        title="Bottle",
        url="http://bottlepy.org/docs/dev/")

    add_page(cat=frame_cat,
        title="Flask",
        url="http://flask.pocoo.org")

    # Print out what we have added to the user.
    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print "- {0} - {1}".format(str(c), str(p))

def add_page(cat, title, url, views=0):
    p = Page.objects.get_or_create(category=cat, title=title)[0]
        p.url=url
        p.views=views
        p.save()
    return p

def add_cat(name):
    c = Category.objects.get_or_create(name=name)[0]
    return c

# Start execution here!
if __name__ == '__main__':
    print "Starting Rango population script..."
    populate()
 


 

  • 
    		
    Static Media
    
    			

     

    在PersonalWebsite, blog, templates平行下建立static/images,并放入一张图片cat.png

    编辑settings.py

    STATIC_PATH = os.path.join(BASE_DIR,'static')
    
    STATIC_URL = '/static/'
    
    STATICFILES_DIRS = (
        STATIC_PATH,
    )
    

    在index.html中: html外写{% load staticfiles %}, body里加入<img src="{% static "images/cat.png" %}" alt="Picture of Cat" />

    we need to inform Django’s template system that we will be using static media with the {% loadstatic %} tag. This allows us to call the static template tag as done in {% static "rango.jpg" %}. As you can see, Django template tags are denoted by curly brackets { }. In this example, the static tag will combine the STATIC_URL with "rango.jpg" so that the rendered HTML looks like the following

    如何调用javascript和css

    <!DOCTYPE html>
    
    {% load static %}
    
    <html>
    
        <head>
            <title>Rango</title>
            <link rel="stylesheet" href="{% static "css/base.css" %}" /> <!-- CSS -->
            <script src="{% static "js/jquery.js" %}"></script> <!-- JavaScript -->
        </head>
    
        <body>
            <h1>Including Static Media</h1>
            <img src="{% static "images/rango.jpg" %}" alt="Picture of Rango" /> <!-- Images -->
        </body>
    
    </html>

    如果要放在服务器上,请参考

Deploying static files

https://docs.djangoproject.com/en/1.7/howto/static-files/deployment/
 

 


	

关于Deploy #TODO(leifos): the DEBUG variable in settings.py, lets you control the output when an error occurs, and is used for debugging. When the application is deployed it is not secure to leave DEBUG equal to True. When you set DEBUG to be False, then you will need to set the ALLOWED_HOSTS variable in settings.py, when running on your local machine this would be 127.0.0.1. You will also need to update the project urls.py file:

 

上传Media 与static, templates并列建立文件夹media; 在PersonalWebsite/urls.py里加入

# At the top of your urls.py file, add the following line:
from django.conf import settings

# UNDERNEATH your urlpatterns definition, add the following two lines:
if settings.DEBUG:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)',
        'serve',
        {'document_root': settings.MEDIA_ROOT}), )

The settings module from django.conf allows us access to the variables defined within our project’s settings.py file. The conditional statement then checks if the Django project is being run in DEBUGmode. If the project’s DEBUG setting is set to True, then an additional URL matching pattern is appended to the urlpatterns tuple. The pattern states that for any file requested with a URL starting with media/, the request will be passed to the django.views.static view. This view handles the dispatching of uploaded media files for you.

 

编辑PersonalWebsite/settings.py 加入

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Absolute path to the media directory

Summary

Creating a template and integrating it within a Django view is a key concept for you to understand. It takes several steps, but becomes second nature to you after a few attempts.

The steps involved for getting a static media file onto one of your pages is another important process you should be familiar with. Check out the steps below on how to do this.

First, create the template you wish to use and save it within the templates directory you specified in your project’s settings.py file. You may wish to use Django template variables (e.g. {{variable_name }}) within your template. You’ll be able to replace these with whatever you like within the corresponding view.

Find or create a new view within an application’s views.py file.

Add your view-specific logic (if you have any) to the view. For example, this may involve extracting data from a database.

Within the view, construct a dictionary object which you can pass to the template engine as part of the template’s context.

Make use of the  render() helper function to generate the rendered response. Ensure you reference the request, then the template file, followed by the context dictionary!

If you haven’t already done so, map the view to a URL by modifying your project’s urls.py file - and the application-specific urls.py file if you have one.

Take the static media file you wish to use and place it within your project’s static directory. This is the directory you specify in your project’s STATICFILES_DIRS tuple within settings.py.

Add a reference to the static media file to a template. For example, an image would be inserted into an HTML page through the use of the <img /> tag.

Remember to use the {% load staticfiles %} and {% static "filename" %} commands within the template to access the static files.

 

Django博客搭建工作笔记 二 Controller & View

  • Templates/

建立templates文件夹与Blog,PersonalWebsite并列

 


	

建立templates/blog/index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
    <h1>Librius says...</h1>
    hello world! <strong>{{ boldmessage }}</strong><br/>
    <a href="/blog/">Blog.index</a><br/>
</body>
</html>

 

修改Blog/views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):

    # Construct a dictionary to pass to the template engine as its context.
    # Note the key boldmessage is the same as {{ boldmessage }} in the template!
    context_dict = {'boldmessage': "I am bold font from the context"}

    # Return a rendered response to send to the client.
    # We make use of the shortcut function to make our lives easier.
    # Note that the first parameter is the template we wish to use.

    return render(request, 'blog/index.html', context_dict)

# 一般路径不要从“/”开始,不然会错

 

 

  • render() takes as input the user’s request, the template file name, and the context dictionary.

  • context_dict 将参数传入模版

 

在settings.py里设置template的path

TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates’)
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_PATH, ],
        'APP_DIRS': False,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

	
  • There are five main steps that you must undertake to create a data driven webpage in Django.

    1. First, import the models you wish to use into your application’s views.py file.
    2. Within the view you wish to use, query the model to get the data you want to present.
    3. Pass the results from your model into the template’s context.
    4. Setup your template to present the data to the user in whatever way you wish.
    5. If you have not done so already, map a URL to your view.
     
  • blog/view.py

在index(request)下加入:

category_list = Category.objects.order_by(‘id’) context_dict = {'categories': category_list}

 

在template/blog/index.html里<body>加入

{% if categories %}
    <ul>
        {% for category in categories %}
            <li>{{ category.name }}</li>
        {% endfor %}
    </ul>
{% else %}
    <strong>There are no categories present.</strong>
{% endif %}

	
  • we could just use the category name as part of the URL. 

在blog/models.py里class Category

        slug = models.SlugField(unique=True)

        def save(self, *args, **kwargs):
                self.slug = slugify(self.name)
                super(Category, self).save(*args, **kwargs)
  • 对已存在的row添加slug值,修改blog/admin.py
from django.contrib import admin
from blog.models import Category, Article

# Register your models here.

class CategoryAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug':('name',)}

admin.site.register(Category, CategoryAdmin)
admin.site.register(Article)
  •  Category Page Workflow

    With our URLs design chosen, let’s get started. We’ll undertake the following steps.

    We’ll also need to update the index() view and index.html template to provide links to the category page view.

    1. Import the Page model into blog/views.py.

    2. Create a new view in blog/views.py - called category - The category view will take an additional parameter, category_name_url which will stored the encoded category name.
       
      • We will need some help functions to encode and decode the category_name_url.
       
      from blog.models import Category, Article
      from django.http import HttpResponse
      
      # Create your views here.
      
      def category(request, category_name_slug):
      
          # Create a context dictionary which we can pass to the template rendering engine.
          context_dict = {}
      
          try:
              # Can we find a category name slug with the given name?
              # If we can't, the .get() method raises a DoesNotExist exception.
              # So the .get() method returns one model instance or raises an exception.
              category = Category.objects.get(slug=category_name_slug)
              context_dict['category_name'] = category.name
      
              # Retrieve all of the associated pages.
              # Note that filter returns >= 1 model instance.
              articles = Article.objects.filter(category=category)
      
              # Adds our results list to the template context under name pages.
              context_dict['article'] = articles
              # We also add the category object from the database to the context dictionary.
              # We'll use this in the template to verify that the category exists.
              context_dict['category'] = category
          except Category.DoesNotExist:
              # We get here if we didn't find the specified category.
              # Don't do anything - the template displays the "no category" message for us.
              pass
      
          # Go render the response and return it to the client.
          return render(request, 'blog/category.html', context_dict)
    3. Create a new template, templates/blog/category.html.

      <!DOCTYPE html>
      <html>
      <head>
          <title>Blog</title>
      </head>
      
      <body>
      <h1>{{ category_name }}</h1>
      {% if category %}
          {% if articles %}
              <ul>
                  {% for article in articles %}
                      <li>{{ article.title }}</li>
                  {% endfor %}
              </ul>
          {% else %}
              <strong>No pages currently in category.</strong>
          {% endif %}
      {% else %}
          The specified category {{ category_name }} does not exist!
      {% endif %}
      </body>
      </html>
    4. Update Rango’s urlpatterns to map the new category view to a URL pattern in blog/urls.py.

      url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category’),
      5. add category link on the index, update blog/index.html
      <li><a href="/rango/category/{{ category.slug }}">{{ category.name }}</a></li>
  • 加入Articles

blog/models.py

class Article(models.Model):
    category = models.ForeignKey(Category)
    created = models.DateTimeField(auto_now=True)
    modified = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=128, unique=True)
    text = models.TextField()
    views = models.IntegerField(default=0)
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Article, self).save(*args, **kwargs)

    def __unicode__(self):      # For Python 2, use __str__ on Python 3
        return self.title

 

blog/views.py

def article(request, article_title_slug):

    # Create a context dictionary which we can pass to the template rendering engine.
    context_dict = {}

    try:
        print article_title_slug
        theArticle = Article.objects.get(slug=article_title_slug)
        context_dict['article'] = theArticle
        context_dict['article_name'] = theArticle.title
        context_dict['article_content'] = theArticle.text
    except Category.DoesNotExist:
        # We get here if we didn't find the specified category.
        # Don't do anything - the template displays the "no category" message for us.
        pass

    # Go render the response and return it to the client.
    return render(request, 'blog/article.html', context_dict)

 

blog/urls.py

url(r'^article/(?P<article_title_slug>[\w\-]+)/$', views.article, name='article'),

 

templates/blog/article.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Article Webpage</title>
</head>
<body>

{% if article %}
<h1>{{ article_name }}</h1>

   <p> {{ article_content }} </p>

{% else %}
    The article does not exist!
{% endif %}

</body>
</html>

 

templates/blog/category.html

<li><a href="/blog/article/{{ article.slug }}">{{ article.title }}</a></li>
 

	

 

 

 

  • Referring to URLs in Templates

    So far we have been directly coding the URL of the page/view we want to show within the template, i.e. <a href="/rango/about/"> About  </a>. However, the preferred way is to use the template tag url to look up the url in the urls.py files. To do this we can change the way we reference the URL as follows:

    <li><a href="{% url 'about' %}">About</a></li>
    

    The Django template engine will look up the urls.py files for a url with the name='about' (and then reverse match the actual url). This means if we change the url mappings in urls.py then we do not have to go through all the templates and update them. If we had not given our urlpattern a name, we could directly reference it as follows:

    <li><a href="{% url 'rango.views.about' %}">About</a></li>
    

    Here we need to specify the application, and the view about.

    You can now update the base template with the url template tag so that links in base template are rendered using the following code:

    <div>
            <ul>
        {% if user.is_authenticated %}
            <li><a href="{% url 'restricted' %}">Restricted Page</a></li>
            <li><a href="{% url 'logout' %}">Logout</a></li>
            <li><a href="{% url 'add_category' %}">Add a New Category</a></li>
        {% else %}
            <li><a href="{% url 'register' %}">Register Here</a></li>
            <li><a href="{% url 'login' %}">Login</a></li>
        {% endif %}
    
        <li><a href="{% url 'about' %}">About</a></li>
        </ul>
    </div>
    

    In your index.html template you will notice that you have a parameterized url pattern, i.e. the categoryurl/view takes the category.slug as a parameter. To handle this you can pass the url template tag the name of the url/view and the slug, i.e. {% url ‘category’ category.slug %} within the template, as follows:

    {% for category in categories %}
        <li><a href="{% url 'category'  category.slug %}">{{ category.name }}</a></li>
    {% endfor %}
    

    #TODO(leifos): The official tutorial provides an overview of how to use the url template tag, http://django.readthedocs.org/en/latest/intro/tutorial03.html and the answer at stackoverflow was helpful too: http://stackoverflow.com/questions/4599423/using-url-in-django-templates

    #TODO(leifos): Also point out how the urls can be placed in a namespace and referenced accordingly, see http://django.readthedocs.org/en/latest/intro/tutorial03.html

 


 

Django博客搭建工作笔记 一 Model

  • 使用IntelliJ向导建立Django项目PersonalWebsite,并且建立叫做blog的app
    如果在已有项目里建立一个app的话,点击Tools | Run manage.py task,输入startapp


    如果不使用IDE的话,用命令行terminal进入希望放置项目的目录下

    $ django-admin startproject PersonalWebsite
    然后进入PersonalWebsite文件夹,并创建名叫blog的app
    $ python manage.py startapp blog

    这里的manage.py是运行整个django网站需要的文件,在后面使用命令行调试网站的时候需要使用命令告知电脑现在在运行此项目
    $ python manage.py shell

    至此,文件结构已成
    PersonalWebsite/
        manage.py
        PersonalWebsite/
            __init__.py
            settings.py
            urls.py
            wsgi.py
        blog/
            views.py
            models.py
            ...
        templates/
            blog/
            ...
    
    
  • 在PersonalWebsite项目目录下创建templates存放各种html文件。
    Django的MVC在命名上比较奇怪,Model就是<app_name>/models.py负责定义各种数据模型,Controller是<app_name>/views.py定义如何表达数据模型并且使用哪一个html渲染,View就是templates文件夹了。

  • 当网站主页被访问时,根据PersonalWebsite/settings里的ROOT_URLCONF指定的文件(在这里也就是’PersonalWebsite.urls')进行url和具体的view映射。(具体在PersonalWebiste.url里的具体函数是django.conf.urls.url()。)

  • blog/views.py

from django.http import HttpResponse

def index(request):

    return HttpResponse("Rango says hey there world!”)
  • PersonalWebsite/urls.py

    from django.conf.urls import url, include
    from django.contrib import admin
    
    urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^blog/', include('blog.urls')),
    url(r'^admin/', include(admin.site.urls)),
    

这里的name是对该映射的命名,以便区分,或者反映射。另外要注意import进来的包urls.py应该给每一个app建立,所以映射文件里可以把url映射到文件的相对路径

  • blog/models.py

    from django.db import models
    from django.template.defaultfilters import slugify
    
    # Create your models here.
    class Category(models.Model):
        name = models.CharField(max_length=128, unique=True)
        slug = models.SlugField(unique=True)
    
        def save(self, *args, **kwargs):
            self.slug = slugify(self.name)
            super(Category, self).save(*args, **kwargs)
    
        def __unicode__(self):  # For Python 2, use __str__ on Python 3
            return self.name
    
    class Article(models.Model):
        category = models.ForeignKey(Category)
        created = models.DateTimeField(auto_now=True)
        modified = models.DateTimeField(auto_now_add=True)
        title = models.CharField(max_length=128, unique=True)
        text = models.TextField()
        views = models.IntegerField(default=0)
        slug = models.SlugField(unique=True)
    
        def save(self, *args, **kwargs):
            self.slug = slugify(self.title)
            super(Article, self).save(*args, **kwargs)
    
        def __unicode__(self):      # For Python 2, use __str__ on Python 3
            return self.title

这里定义了两个数据模型,Category和Article,每个class的属性看名字就能理解了。有一个重点是save:这里运用了slug,有了这个在点击查看博文的时候,url里面会出现博文的名字而不是一些数字或者别的没有意义的符号们。

第一次操作还要创建管理员,现在是管理数据库,后期操作admin。

$ python manage.py createsuperuser

设定好了数据,就要对app注册其变化

$ python manage.py makemigrations APP_NAME
$ python manage.py migrate

在shell里检查一下数据库 


 $ python manage.py shell

# Import the Category model from the Rango application
>>> from rango.models import Category

# Show all the current categories
>>> print Category.objects.all()
[] # Returns an empty list (no categories have been defined!)

# Create a new category object, and save it to the database.
>>> c = Category(name="Test")
>>> c.save()

# Now list all the category objects stored once more.
>>> print Category.objects.all()
[<Category: test>] # We now have a category called 'test' saved in the database!

# Quit the Django shell.
>>> quit()

参考资料:

official Django Tutorial to learn more about interacting with the models

official Django documentation on the list of available commands

Django博客搭建工作笔记 序

工作目标:

使用Django搭建个人网站,从主页上的链接进入博客,博客存放一些文章。

[Dream Idea]想要一个能够记录自己生命轨迹的个人网站,有三大块分类:技术,视野,情感

笔记概要:

是Django入门学习笔记,本人初次接触网站开发,结合自己经验展示如何造出一个MVC的Django博客。

工作环境:

IDE使用IntelliJ IDEA,系统是OS X,Python版本2.7,Django版本1.8

参考资料:

Tango with Django 这是一个不错的英文教程,我基本照着它来的,但是省略了一些暂时可以不实现的操作。

官方文档和教程 在做这个网站之前,跟着官方教程走了一遍,做了一个小投票的网站,有了初步印象。

在AWS的EC2上部署你的Django Demo 这是我在WordPress上写的笔记,前后有一个系列,可以参考。