一.创建App
manage.py startapp notification 在INSTALLED_APPS中添加 'notification',
二.修改notifications/models.py
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Notification(models.Model): title =models.CharField(max_length=256) message =models.TextField() viewed =models.BooleanField(default=False) user =models.ForeignKey(User) @receiver(post_save,sender=User) def create_welcome_message(sender,**kwargs): if kwargs.get('created',False): Notification.objects.create(user=kwargs.get('instance'), title="Welcome to our Django site!", message="Thanks for signing up!" )
三.运行
manage.py schemamigration notification --initial manage.py migrate
四.修改notification/urls.py
from django.conf.urls import patterns,url urlpatterns=patterns('notification.views', url(r'show/(?P<notification_id>\d+)/$','show_notification'), url(r'^delete/(?P<notification_id>\d+)/$','delete_notification'), )
五.修改notification/view.py
from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from models import Notification def show_notification(request,notification_id): n=Notification.objects.get(id=notification_id) return render_to_response('notification.html',{'notification':n}) def delete_notification(request,notification_id): n=Notification.objects.get(id=notification_id) n.viewed=True n.save() return HttpResponseRedirect('/accounts/loggedin')六.修改notification/templates/notification.html
{% extends "base.html" %} {% block content %} <h2>{{notification.title}}</h2> <p>{{notification.message}}</p> <p><a href="/notification/delete/{{notification.id}}/">Mark as read</a></p> {% endblock %}
七.修改templates/loggedin.html
{% extends "base.html" %} {% block content %} <h2>Hi {{full_name}} you are now logged in!</h2> {% if notifications.count >0 %} <h3>Notifications</h3> {% for n in notifications %} <p><a href="/notification/show/{{n.id}}">{{n.title}}</a></p> {% endfor %} {% endif %} <p>Click <a href="/accounts/logout/">here</a> to logout.</p> <p>Click <a href="/accounts/profile/">here</a> to edit your profile information</p> {% endblock %}
八.修改django_test/views.py
from notification.models import Notification def loggedin(request): n=Notification.objects.filter(user=request.user,viewed=False) return render_to_response('loggedin.html', {'full_name':request.user.username,'notifications':n} )
九.修改django_test/urls.py
(r'^notification/',include('notification.urls')),
十.添加notification/admin.py
from django.contrib import admin from models import Notification admin.site.register(Notification)