标签:django
这一节中,我们提供了bbs_pro完整的代码及最终的实现效果:
项目完整的文件:
分别给出代码:
# coding=utf-8 from django.db import models from django.contrib.auth.models import User # Create your models here. # 创建表 # 帖子表 class BBS(models.Model): category = models.ForeignKey(‘Category‘) title = models.CharField(max_length=64) # 帖子标题,标题可以重复 summary = models.CharField(max_length=256, blank=True, null=True) # 帖子介绍 content = models.TextField() # 评论 author = models.ForeignKey(‘BBS_user‘) # 作者 view_count = models.IntegerField() # 浏览数 ranking = models.IntegerField() # 排名 created_at = models.DateTimeField(auto_now_add=True) # 创建日期,自动添加 updated_at = models.DateTimeField(auto_now_add=True) # 修改日期 def __unicode__(self): return self.title # 模块表 版主 class Category(models.Model): name = models.CharField(max_length=32, unique=True) # 板块名称 administrator = models.ForeignKey(‘BBS_user‘) # 版主 def __unicode__(self): return self.name # BBS用户表 class BBS_user(models.Model): user = models.OneToOneField(User) # 一对一的外键 signature = models.CharField(max_length=128, default=‘This guy is too lazy to leave anything here‘) # 个性签名 photo = models.ImageField(upload_to="upload_imgs/", default="upload_imgs/user1.jpg") # 头像图片 def __unicode__(self): return self.user.username
# coding=utf-8 from django.contrib import admin from app01 import models class BBS_admin(admin.ModelAdmin): # 一行展示多列 list_display = (‘title‘, ‘summary‘, ‘author‘, ‘signature‘, ‘view_count‘, ‘created_at‘) # 按照创建时间过滤 list_filter = (‘created_at‘,) # 添加搜索 search_fields = (‘title‘, ‘author__user__username‘) # 在BBS表中显示author表中的signature def signature(self, object): return object.author.signature # Register your models here. admin.site.register(models.BBS, BBS_admin) admin.site.register(models.Category) admin.site.register(models.BBS_user)
# coding=utf-8 from django.shortcuts import render, render_to_response from django.http import HttpResponse , HttpResponseRedirect from django.template.context import RequestContext from django.contrib import auth import models from django.contrib import comments from django.contrib.contenttypes.models import ContentType # Create your views here. # 创建登陆视图 def acc_login(request): username = request.POST.get(‘username‘) password = request.POST.get(‘password‘) user = auth.authenticate(username=username, password=password) print username, password if user is not None: auth.login(request, user) content = ‘‘‘ Welcome %s !!! <a href=‘/logout/‘ >Logout</a> ‘‘‘ % user.username #return HttpResponse(content) return HttpResponseRedirect(‘/‘) else: return render_to_response(‘login.html‘,{‘login_err‘:‘Wrong username or password!‘}) def logout_view(request): user = request.user auth.logout(request) # Redirect to a success page. return HttpResponse("<b>%s</b> logged out! <br/><a href=‘/login/‘>Re-login</a>" % user) def Login(request): return render_to_response(‘login.html‘) def index(request): # 从数据库中取出bbs数据渲染到index.html中 bbs_list = models.BBS.objects.all() # 取出bbs的类别 bbs_categories = models.Category.objects.all() return render_to_response(‘index.html‘, {‘bbs_list‘: bbs_list, ‘user‘: request.user, # 将登陆认证后的信息返回 ‘bbs_category‘: bbs_categories, ‘bbs_id‘: 0, }) # bbs分类 def category(request, cate_id): bbs_list = models.BBS.objects.filter(category__id=cate_id) bbs_categories = models.Category.objects.all() return render_to_response(‘index.html‘, {‘bbs_list‘: bbs_list, ‘user‘: request.user, ‘bbs_category‘: bbs_categories, ‘bbs_id‘: int(cate_id), }) # bbs的详细介绍 def bbs_detail(request, bbs_id): # 取出bbs_id下的详细内容 bbs = models.BBS.objects.get(id=bbs_id) return render_to_response(‘bbs_detail.html‘, {‘bbs_obj‘: bbs, ‘user‘: request.user}) # 添加评论 def sub_comment(request): print request.POST bbs_id = request.POST.get(‘bbs_id‘) comment = request.POST.get(‘comment_content‘) comments.models.Comment.objects.create( content_type_id=7, # bbs表在数据库中的id号 object_pk=bbs_id, site_id=1, user_id=request.user.id, # 这里与源代码不同 如果不加.id,会出现int() argument must be a string or a number, not ‘SimpleLazyObject’错误 comment=comment, ) #重定向 return HttpResponseRedirect(‘/detail/%s‘% bbs_id) def bbs_pub(request): return render_to_response(‘bbs_pub.html‘) def bbs_sub(request): print request.POST.get(‘content‘) title = request.POST.get(‘title‘) content = request.POST.get(‘content‘) summary = request.POST.get(‘summary‘) author = models.BBS_user.objects.get(user__username=request.user) models.BBS.objects.create( title=title, summary=summary, content=content, author=author, view_count=1, ranking=1, #created_at=models.DateTimeField(auto_now_add=True), # 创建日期 #updated_at = models.DateTimeField(auto_now_add=True), # 修改日期 ) return HttpResponse("<h2>Bbs was published, please enter <br/><a href=‘/‘>return</a> to index!<h2>")
from django.conf.urls import patterns, include, url import views urlpatterns = patterns(‘‘, # Examples: # url(r‘^$‘, ‘bbs_project.views.home‘, name=‘home‘), # url(r‘^blog/‘, include(‘blog.urls‘)), (r‘^$‘, views.index), (r‘^detail/(\d+)/$‘, views.bbs_detail), (r‘^sub_comment/$‘, views.sub_comment), (r‘^bbs_pub/$‘, views.bbs_pub), (r‘^bbs_sub/$‘, views.bbs_sub), (r‘^category/(\d+)‘, views.category), )
# coding=utf-8 from django.conf.urls import patterns, include, url from django.contrib import admin from app01 import views import app01.urls urlpatterns = patterns(‘‘, # Examples: # url(r‘^$‘, ‘bbs_project.views.home‘, name=‘home‘), # url(r‘^blog/‘, include(‘blog.urls‘)), # 配置url url(r‘^admin/‘, include(admin.site.urls)), # 登陆页面url (r‘^accounts/login/$‘, ‘django.contrib.auth.views.login‘, {‘template_name‘: ‘login.html‘}), (r‘^login/$‘, views.Login ), (r‘^acc_login/$‘, views.acc_login), (r‘^logout/$‘, views.logout_view), url(r‘‘, include(app01.urls)), )
""" Django settings for bbs_project project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ‘(_*z%mh68uxoe6x2l7n5ykxq!fntmtdx-x2#gotx3-!lmy%udd‘ # SECURITY WARNING: don‘t run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘debugtools‘, ‘app01‘, ‘django.contrib.comments‘, ‘django.contrib.sites‘, ) MIDDLEWARE_CLASSES = ( ‘django.contrib.sessions.middleware.SessionMiddleware‘, ‘django.middleware.common.CommonMiddleware‘, #‘django.middleware.csrf.CsrfViewMiddleware‘, ‘django.contrib.auth.middleware.AuthenticationMiddleware‘, ‘django.contrib.auth.middleware.SessionAuthenticationMiddleware‘, ‘django.contrib.messages.middleware.MessageMiddleware‘, ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘, ‘django.middleware.locale.LocaleMiddleware‘ ) ROOT_URLCONF = ‘bbs_project.urls‘ WSGI_APPLICATION = ‘bbs_project.wsgi.application‘ # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { ‘default‘: { ‘ENGINE‘: ‘django.db.backends.mysql‘, ‘NAME‘: ‘bbs_pro‘, ‘USER‘: ‘root‘, ‘PASSWORD‘: ‘mysqladmin‘, ‘HOST‘: ‘127.0.0.1‘, ‘PORT‘: ‘3306‘, } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = ‘en-us‘ TIME_ZONE = ‘UTC‘ USE_I18N = True USE_L10N = True USE_TZ = True SITE_ID = 1 # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = ‘/static/‘ TEMPLATE_DIRS = ( os.path.join(BASE_DIR, ‘templates‘), ) STATICFILES_DIRS = ( os.path.join(BASE_DIR, "statics"), )
.center-container-hx,.footer { box-shadow: 2px 0 5px rgba(214, 214, 215, 0.9), -2px 0 5px rgba(214, 214, 215, 0.9); } /*.contents{margin-top: 20px;}*/ /*.container-hx {width:1000px;margin:0 auto;z-index:10;height:100%;text-align: left}*/ .contents {margin-top:20px;} /** {word-wrap:break-word;}*/ /*.comments{*/ /*width:70%*/ /*}*/
body { padding-top: 40px; padding-bottom: 40px; background-color: #eee; } .form-signin { max-width: 330px; padding: 15px; margin: 0 auto; } .form-signin .form-signin-heading, .form-signin .checkbox { margin-bottom: 10px; } .form-signin .checkbox { font-weight: normal; } .form-signin .form-control { position: relative; height: auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 10px; font-size: 16px; } .form-signin .form-control:focus { z-index: 2; } .form-signin input[type="text"] { margin-bottom: -1px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .form-signin input[type="password"] { margin-bottom: 10px; border-top-left-radius: 0; border-top-right-radius: 0; }
<!DOCTYPE html> <!-- saved from url=(0048)http://v3.bootcss.com/examples/navbar-fixed-top/ --> <html lang="zh-CN"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="http://v3.bootcss.com/favicon.ico"> <title>Fixed Top Navbar Example for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="/static/css/navbar-fixed-top.css" rel="stylesheet"> <!--从虎嗅网中导入的带阴影的边框,代码保存在/static/css/customize.css中--> <link href="/static/css/customize.css" rel="stylesheet"> <!-- Just for debugging purposes. Don‘t actually copy these 2 lines! --> <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]--> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- Fixed navbar --> <nav class="navbar navbar-inverse navbar-fixed-top"><!--导航标签--> <div class="container"> <!-- 导航的logo --> <div class="navbar-header"><!--导航的头部分--> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">抽屉</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <!--导航栏中的内容--> <li class="active"><a href="/">全部</a></li> {% for category in bbs_category %} {% ifequal category.id cate_id %} <li class="active"><a href="/category/{{ category.id }}/">{{ category.name }}</a></li> {% else %} <li class=""><a href="/category/{{ category.id }}/">{{ category.name }}</a></li> {% endifequal %} {% endfor %} </ul> <ul class="nav navbar-nav navbar-right"> <!--登陆设置,在最右端的下拉菜单--> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> {% if user.is_authenticated %} <!--信息认证--> {{ user.username }} {% else %} 登陆 {% endif %} <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="/login/">Login</a></li> <li><a href="/logout/">Logout</a></li> </ul> </li> </ul> </div><!--/.nav-collapse --> </div> </nav> <!--虎嗅网中的样式--> <div class="container center-container-hx"> <!-- 放置可重用的数据--> <!--下面的代码为动态页面,此页面为母版,其他网站可以重用block中的数据,只要继承母版即可--> {% block page-content %} <!-- Main component for a primary marketing message or call to action --> <ul class="nav nav-pills navbar-right" role="tablist"> <li role="presentation" class="active"> <a href="/bbs_pub/">发帖</a> </li> </ul> <br/> <hr> <div class="contents"> {% for bbs in bbs_list %} <!--论坛首页链接标题--> <a href="/detail/{{ bbs.id }}">{{ bbs.title }}</a><!--点击标题跳转到bbs_detail.html--> <br> {{ bbs.summary }} <br> <hr> {% endfor %} </div> {% endblock %} </div> <!-- /container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="/static/js/jquery-2.1.1.min.js"></script> <script src="/static/js/bootstrap.min.js"></script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> </body></html>
<link href="/static/css/signin.css" rel="stylesheet"> {%extends ‘index.html‘%} {% block page-content%} <div class="container"> <form action=‘/acc_login/‘ class="form-signin" method=‘POST‘> {# <input type=‘text‘ name=‘username‘ />#} {# <input type=‘password‘ name=‘password‘ />#} {##} {# <input type=‘submit‘ value=‘Login‘ />#} <h2 class="form-signin-heading">Please sign in</h2> <label for="in" class="sr-only">Username</label> <input type="text" name="username" class="form-control" placeholder="Username" required> <label for="inputPassword" class="sr-only">Password</label> <input type="password" name="password" class="form-control" placeholder="Password" required> <div class="checkbox"> <label> <input type="checkbox" value="remember-me"> Remember me </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> {# <input type=‘submit‘ value=‘Sign in‘ />#} <span style=‘color:red‘>{{login_err}}</span> </form> </div> {%endblock%}
{% extends ‘index.html‘ %} {% load comments %} {% block page-content %} <!--bbs-contents--> <div class="contents"> {{ bbs_obj.title }} <br> {{ bbs_obj.content | safe}} </div> <hr> <div class="comments"> <div> {% get_comment_count for bbs_obj as comment_count %} <span class="glyphicon glyphicon-comment"> </span> {{ comment_count }} </div> <br> {% if user.is_authenticated %} <form action="/sub_comment/" method="POST"> <textarea cols="80" rows="3" name=‘comment_content‘></textarea><br> <input type="hidden" name="bbs_id" value="{{ bbs_obj.id }}" /> <input type="submit" value="Add comment" id="id_submit" /> </form> {% else %} <p>Please <a href="/login/">Login</a> to comment </p> {% endif %} <hr> {% get_comment_list for bbs_obj as comment_list %} {% for comment in comment_list reversed %} {{ comment.submit_date }} <br> {{ comment.comment }} <hr> {% endfor %} </div> {% endblock %}
<link href="/static/css/signin.css" rel="stylesheet"> {% extends ‘index.html‘ %} {% block page-content %} <!-- Place inside the <head> of your HTML --> <script type="text/javascript" src="/static/tinymce/js/tinymce/tinymce.min.js"></script> <script type="text/javascript"> tinymce.init({ selector: "textarea", theme: "modern", plugins: [ "advlist autolink lists link image charmap print preview hr anchor pagebreak", "searchreplace wordcount visualblocks visualchars code fullscreen", "insertdatetime media nonbreaking save table contextmenu directionality", "emoticons template paste textcolor colorpicker textpattern" ], toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image", toolbar2: "print preview media | forecolor backcolor emoticons", image_advtab: true, templates: [ {title: ‘Test template 1‘, content: ‘Test 1‘}, {title: ‘Test template 2‘, content: ‘Test 2‘} ] }); </script> <!-- Place this in the body of the page content --> <form method="post" action="/bbs_sub/"> <h3>Title</h3> <input type="text" name="title" class="form-control" placeholder="" required> <hr> <h3>Content</h3> <textarea name="content"></textarea> <hr> <h3>Summary</h3> <input type="text" name="summary" class="form-control" placeholder="Summary" required> <br> <div class="form-signin"> <button class="btn btn-lg btn-primary btn-block" type="submit">Save</button> </div> {# <input type=‘submit‘ value=‘Save‘ />#} </form> {% endblock %}
其页面表现为:index.html
login.html
bbs_detail.html
bbs_pub.html
本文出自 “thystar” 博客,请务必保留此出处http://4440271.blog.51cto.com/4430271/1664072
标签:django
原文地址:http://4440271.blog.51cto.com/4430271/1664072