码迷,mamicode.com
首页 > 其他好文 > 详细

Django学习笔记之二

时间:2015-01-28 00:48:55      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:

一、使用Django自带的后端管理平台

1、后台创建管理员

python manage.py createsuperuser
Email address: admin@example.com
Password: **********
Password (again): *********
Superuser created successfully.

2、打开后台页面

http://127.0.0.1:8000/admin/

技术分享

输入刚才的用户名及密码登陆:

技术分享

此时还看不到我们刚才创建的数据表

那我们打开polls/admin.py文件,把我们所创建的数据表配置进去后台,可以通过修改models.py / admin.py代码来设置多种显示格式,其中一种如下:

from django.contrib import admin
from polls.models import Choice, Question


class ChoiceInline(admin.StackedInline):
    model = Choice
    extra = 3


class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {‘fields‘: [‘question_text‘]}),
        (‘Date information‘, {‘fields‘: [‘pub_date‘], ‘classes‘: [‘collapse‘]}),
    ]
    inlines = [ChoiceInline]

admin.site.register(Question, QuestionAdmin)
技术分享

 

二、自定义模板

先在polls文件夹下方创建一个名叫templates的目录,再修改如下配置文件,把目录添加到系统路径

mysite/settings.py
TEMPLATE_DIRS = [os.path.join(BASE_DIR, ‘templates‘)]

各种template如下:
templates/polls/index.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static ‘polls/style.css‘ %}" />
{% if latest_question_list %}
  <ul>
      {% for question in latest_question_list %}
          <li><a href="{% url ‘polls:detail‘ question.id %}">{{ question.question_text }}</a></li>
      {% endfor %}
  </ul>
{% else %}
  <p>No polls are available.</p>
{% endif %}
templates/polls/detail.html
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url ‘polls:vote‘ question.id %}" method="post">
 {% csrf_token %}
 {% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label>
    <br />
 {% endfor %}
 <input type="submit" value="Vote" />
</form>
templates/polls/results.html
<h1>{{ question.question_text }}</h1>
  <ul>
      {% for choice in question.choice_set.all %}
          <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
      {% endfor %}
  </ul>
<a href="{% url ‘polls:detail‘ question.id %}">Vote again?</a>

 

 

三、创建视图

polls/views.py

from django.shortcuts import render,get_object_or_404
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone

from polls.models import Choice, Question

# Create your views here.


class IndexView(generic.ListView):
    template_name=‘polls/index.html‘
    context_object_name=‘latest_question_list‘

    def get_queryset(self):
        """Return the last five published question"""
        return Question.objects.filter(
            pub_date__lte=timezone.now()
        ).order_by(‘-pub_date‘)[:5]

class DetailView(generic.DetailView):
    model = Question
    template_name = ‘polls/detail.html‘
    def get_queryset(self):
        return Question.objects.filter(pub_date__lte=timezone.now())

    
class ResultsView(generic.DetailView):
    model=Question
    template_name = ‘polls/results.html‘

def vote(request, question_id):
    p=get_object_or_404(Question,pk=question_id)
    try:
        selected_choice=p.choice_set.get(pk=request.POST[‘choice‘])
    except (KeyError, Choice.DoesNotExist):
        return render(request,‘polls/detail.html‘,{
            ‘question‘:p,
            ‘error_message‘:"You didn‘t select a choice",
            })
    else:
        selected_choice.votes += 1
        selected_choice.save()                                         
    return HttpResponseRedirect(reverse(‘polls:results‘,args=(p.id,)))

mysite/urls.py   总的url配置

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

urlpatterns = patterns(‘‘,
    url(r^polls/, include(polls.urls,namespace="polls")),
    url(r^admin/, include(admin.site.urls)),
)

polls/urls.py  子url配置

from django.conf.urls import patterns,url
from polls import views

urlpatterns=patterns(‘‘,
    url(r^$,views.IndexView.as_view(),name=index),
    url(r^(?P<pk>\d+)/$,views.DetailView.as_view(),name=detail),
    url(r^(?P<pk>\d+)/results/$,views.ResultsView.as_view(),name=results),
    url(r^(?P<question_id>\d+)/vote/$,views.vote,name=vote),
)

四、最终Models如下:

polls/models.py

import datetime
from django.db import models
from django.utils import timezone
# Create your models here.


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(date published)
    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        now = timezone.now()
        return now >= self.pub_date >= now - datetime.timedelta(days=1)
    was_published_recently.admin_order_field=pub_date
    was_published_recently.bollean = True
    was_published_recently.short_description=Published recently?

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

五、自定义样式/静态文件位置配置,在polls文件夹下面创建static文件夹

静态文件如:polls/static/polls/style.css

mysite/settings.py 文件中应有下面的默认配置,如果没有,手动添加

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATIC_URL = /static/
#STATIC_URL = [os.path.join(BASE_DIR,‘static‘)]

 

  

 

Django学习笔记之二

标签:

原文地址:http://www.cnblogs.com/fastmover/p/4254631.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!