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

BabbleDay posted @ 2015年6月28日 00:34 in Web Development , 679 阅读
  • 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

 


 

Avatar_small
UBSE 10th Class Syl 说:
2023年7月16日 01:38

Uttarakhand Board High School Parents can use the Syllabus to Understand the Concepts and Prepare their Children for the Exam, Accordingly, The Uttarakhand 10th Class Syllabus 2024 All Subject Chapter UBSE 10th Class Syllabus 2024 Wise Students Prepare for the Upcoming Class Exam, it is quite Essential that they have the Complete Knowledge of the Uttarakhand 10th Class Latest Syllabus 2024 of All Relevant Subjects, Knowing the Details of Prescribed Topics and the weight age Allotted to Them Makes it easy to plan your Studies Meticulously so that you can make Effective Preparations for your Exam and obtain desired marks.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter