Django 1.5.4 주제 5 cookies 및 sessions

2463 단어 django
하나.article/views를 수정합니다.py의 내용은 다음과 같다
from django.http import HttpResponse
from django.shortcuts import render_to_response
from article.models import Article

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

둘.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'),
        )

셋.article/templates/articles를 수정합니다.html의 내용은 다음과 같다.
{% extends "base.html" %}

{% block content %}

<h2>Language is :{{ language }}</h2>

<h2>Session Language is : {{ session_language }}</h2>

{% if articles.count > 0 %}

{% for article in articles %}
<div>
    <h2><a href="/articles/get/{{ article.id }}/">{{ article.title }}</a></h2>
    <p> {{ article.body|lower|truncatewords:"10" }}</p>
</div>
{% endfor %}
{% else %}

<p>None to show!</p>

{% endif %}

{% endblock %}

좋은 웹페이지 즐겨찾기