Django 1.5.4 专题十 database relationships

一.修改article/models.py的内容如下

from django.db import models

# Create your models here.
class Article(models.Model):
    title       =models.CharField(max_length=200)
    body        =models.TextField()
    pub_date    =models.DateTimeField('date published')
    likes       =models.IntegerField()

    def __unicode__(self):
        return self.title
class Comment(models.Model):
    name    =models.CharField(max_length=200)
    body    =models.TextField()
    pub_date = models.DateTimeField('date published')
    article  = models.ForeignKey(Article)

二.修改article/forms.py的内容如下

from django import forms
from models import Article,Comment

class ArticleForm(forms.ModelForm):

    class Meta:
        model=Article
        fields=('title','body','pub_date')
class CommentForm(forms.ModelForm):

    class Meta:
        model=Comment
        fields=('name','body')

三.修改article/urls.py的内容如下

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

urlpatterns = patterns('',
        url(r'^all/$','article.views.articles'),
        url(r'^get/(?P<article_id>\d+)/$','article.views.article'),
        url(r'^language/(?P<language>[a-z\-]+)/$','article.views.language'),
        url(r'^create/$','article.views.create'),
        url(r'^like/(?P<article_id>\d+)/$','article.views.like_article'),
        url(r'^add_comment/(?P<article_id>\d+)/$','article.views.add_comment'),
        )

四.修改article/views.py的内容如下

from django.http import HttpResponse
from django.shortcuts import render_to_response
from article.models import Article,Comment
from forms import ArticleForm,CommentForm
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.utils import timezone

def hello(request):
    name    ="Mike"
    html    =" <html> <body> Hi %s,this seems to have worked!  </body> </html> " % name
    return HttpResponse(html)

def hello_template_simple(request):
    name    ="Mike"
    return render_to_response('hello.html',{'name':name})

def articles(request):
    language    ='en-gb'
    session_language    ='en-gb'
    if 'lang' in request.COOKIES:
        language    = request.COOKIES['lang']

    if 'lang' in request.session:
        session_language =request.session['lang']

    return render_to_response('articles.html',
            {'articles':Article.objects.all(),'language':language,'session_language':session_language})
def article(request,article_id=1):
    return render_to_response('article.html',
            {'article':Article.objects.get(id=article_id)})
def language(request,language='en-gb'):
    response    =HttpResponse("setting language to %s" % language)
    response.set_cookie('lang',language)
    request.session['lang']=language
    return response
def create(request):
    if request.POST:
        form=ArticleForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/articles/all')
    else:
        form=ArticleForm()
    args={}
    args.update(csrf(request))
    args['form']=form

    return render_to_response('create_article.html',args)
def like_article(request,article_id):
    if article_id:
        a=Article.objects.get(id=article_id)
        count=a.likes
        count+=1
        a.likes=count
        a.save()
    return HttpResponseRedirect('/articles/get/%s' % article_id)
def add_comment(request,article_id):
    a=Article.objects.get(id=article_id)
    if request.method == "POST":
        f=CommentForm(request.POST)
        if f.is_valid():
            c=f.save(commit=False)
            c.pub_date=timezone.now()
            c.article=a
            c.save()
            return HttpResponseRedirect('/articles/get/%s' % article_id)
    else:
        f=CommentForm()
    args={}
    args.update(csrf(request))

    args['article']=a
    args['form']=f
    return render_to_response('add_comment.html',args)

五.修改aritlce/templates/add_comment.html的内容如下

{% extends "base.html" %}
{% block sidebar %}
<ul>
    <li><a href="/articles/get/{{article.id}}">Cancel</a></li>
</ul>
{% endblock %}

{% block content %}
<form action="/articles/add_comment/{{article.id}}/" method="post">{% csrf_token %}
    <ul> {{form.as_ul}} </ul>
    <input type="submit" name="submit" value="Post Comment">
</form>

{% endblock %}

六.运行python manage.py syncdb,修改article/templates/article.html的内容如下

{% extends "base.html" %}

{% block sidebar %}
<ul>
    <li><a href="/articles/all">Articles</a></li>
</ul>
{% endblock %}

{% block content %}
<h1> {{ article.title }} </h1>
<p> {{ article.body }} </p>
<p> <a> {{ article.likes }} people liked this article </a> </p>
<p><a href="/articles/like/{{article.id}}">Like</a></p>

<h2>Comment</h2>
{% for c in article.comment_set.all %}
<p>{{c.name}}:{{c.body}}</p>
{% endfor %}
<p><a href="/articles/add_comment/{{article.id}}">Add Comment</a></p>
{% endblock %}


七.最终运行效果如下






你可能感兴趣的:(django)