Django项目的第1个应用
Posted 老人与小孩
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django项目的第1个应用相关的知识,希望对你有一定的参考价值。
1.在Django项目中,每一个应用都是一个python包,都用同一个技术规范。Django自带工具startapp,可以自动生成应用的基础目录结构。
如: diango-damin startapp pollsapp
2.运行后会创建一个pollsapp目录,不同之处是多一个空的views.py文件,存放视图。
3.实现网页能看到视图:
一是要有内容:在view.py中定义返回的函数,用HttpResponse()装载要展示的内容
from django.http import HttpResponse def index(request): return HttpResponse("This is pollsapp index page.")
二是能找到:配置一个URL路由映射到上面写的视图函数,URL路由需要在URLconf模块urls.py中定义。urls.py需要自己写,pollsapp中没有自动生成该空文件。
from django.urls import path from . import views urlpatterns = [ path(\'\',views.index,name=\'index\'), ]
三是在主项目的主应用中指定上面创建的路由pollsapp.urls模块,这样就全部连接上了。
from django.contrib import admin from django.urls import path,include urlpatterns = [ path(\'admin/\', admin.site.urls), path(\'pollsapp/\',include("pollsapp.urls")), #前边的pollsapp,是运行时候的关键字127.0.0.1:8000/pollsapp/ ]
path的用法不是很明了,两个里边都有path
用html页面模板使用django完成个人博客
1、进入虚拟环境: workon 虚拟环境名
2、找到我们的项目管理文件夹django,进入创建项目django-admin startproject blog
3、进入到我们的项目文件夹当中,创建我们的第一个应用 python manage.py startapp user 用于用户管理
创建我们的第二个应用python manage.py startapp articles 用于文章管理
4、使用pycharm打开创建的项目blog,在pycharm当中设置项目的虚拟环境
5、由于我们在创建项目的过程中会遇到两个或者以上的应用,为了便于管理,我们一般创建一个新的文件夹(apps)用于管理所有的应用:
6、然后将apps设置成为根目录:
7、将应用拖入apps中:
8、设置settings
""" Django settings for blog project. Generated by \'django-admin startproject\' using Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os,sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,\'apps\') #目的是将文件夹apps设置为根目录 # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = \'i)hua049@1k6g-mf=b%h3-g8ma&#$i#*al8zu%gg!z-l8o_rz2\' # SECURITY WARNING: don\'t run with debug turned on in production! DEBUG = True # True为调试模式,Fasle为生产模式 ALLOWED_HOSTS = [] # Application definition #里面写入应用名称 INSTALLED_APPS = ( \'django.contrib.admin\', \'django.contrib.auth\', \'django.contrib.contenttypes\', \'django.contrib.sessions\', \'django.contrib.messages\', \'django.contrib.staticfiles\', \'users\', \'articles\', ) AUTH_USER_MODEL = \'users.UserProfile\' #中间键设置,一般默认的就行了 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.security.SecurityMiddleware\', \'mymiddlewears.HandlerRequestMiddleWare\' ) ROOT_URLCONF = \'blog.urls\' #设置静态文件配置,一般会创建一个templates文件夹用于存放静态文件 TEMPLATES = [ { \'BACKEND\': \'django.template.backends.django.DjangoTemplates\', \'DIRS\': [os.path.join(BASE_DIR,\'templates\')], \'APP_DIRS\': True, \'OPTIONS\': { \'context_processors\': [ \'django.template.context_processors.debug\', \'django.template.context_processors.request\', \'django.contrib.auth.context_processors.auth\', \'django.contrib.messages.context_processors.messages\', \'django.template.context_processors.media\',#用于图片的处理 ], }, }, ] WSGI_APPLICATION = \'blog.wsgi.application\' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { \'default\': { \'ENGINE\': \'django.db.backends.mysql\', #处理器使用的数据库,这里是mysql \'NAME\': \'blog\', #mysql数据库名字 \'USER\': \'root\', #mysql数据库用户 \'PASSWORD\': \'root\',#密码 \'HOST\': \'localhost\', \'PORT\': \'3306\', } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ # # 编码显示配置 LANGUAGE_CODE = \'zh-CN\' TIME_ZONE = \'Asia/Shanghai\' USE_I18N = True USE_L10N = True USE_TZ = False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = \'/static/\' STATICFILES_DIRS = [ os.path.join(BASE_DIR,\'static\') ] #配置媒体文件夹 MEDIA_URL = \'/static/media/\' MEDIA_ROOT = os.path.join(BASE_DIR,\'static/media\')
9、再到mysql数据库里创建数据库blog。
10、blog中urls代码:
"""blog URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r\'^$\', views.home, name=\'home\') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r\'^$\', Home.as_view(), name=\'home\') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r\'^blog/\', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from django.views.static import serve from users.views import index from blog.settings import MEDIA_ROOT urlpatterns = [ url(r\'^admin/\', include(admin.site.urls)), url(r\'^users/\',include(\'users.urls\',namespace=\'users\')), url(r\'^articles/\',include(\'articles.urls\',namespace=\'articles\')), url(r\'^$\',index,name=\'index\'), url(r\'^static/media/(?P<path>.*)\',serve,{\'document_root\':MEDIA_ROOT}) ]
11、user 中forms.py中代码:
from django import forms class UserRegistForm(forms.Form): username=forms.CharField(max_length=20,min_length=6,required=True,error_messages={ \'max_length\':\'用户名最大长度为20\', \'min_length\':\'用户名最小长度为6\', \'required\':\'用户名为必填\' }) email=forms.EmailField(max_length=100,min_length=8,required=False,error_messages={ \'invalid\':\'邮箱格式为:xxx@xx.com\' }) url=forms.URLField(max_length=100,min_length=8,required=False,error_messages={ \'invalid\':\'网址格式为:http://www.xxx.com\' }) password=forms.CharField(max_length=20,min_length=8,required=True,error_messages={ \'max_length\':\'密码最大长度为20\', \'min_length\':\'密码名最小长度为8\', \'required\':\'密码为必填\' }) password1=forms.CharField(max_length=20,min_length=8,required=True,error_messages={ \'max_length\':\'密码最大长度为20\', \'min_length\':\'密码名最小长度为8\', \'required\':\'密码为必填\' }) class UserloginForm(forms.Form): username=forms.CharField(max_length=20,min_length=6,required=True) password=forms.CharField(max_length=20,min_length=8,required=True)
12、user 中models.py中代码:
from django.db import models from django.contrib.auth.models import AbstractUser from datetime import datetime # Create your models here. class UserProfile(AbstractUser): nick_name=models.CharField(max_length=20,verbose_name=\'用户昵称\',null=True,blank=True) url=models.URLField(max_length=100,verbose_name=\'用户主页\',null=True,blank=True) add_time=models.DateTimeField(default=datetime.now,verbose_name=\'添加时间\') def __str__(self): return self.username class Meta: verbose_name=\'用户信息\' verbose_name_plural=verbose_name
完成后 注意生成迁移文件命令:python3 manage.py makemigrations
执行sql语句生成数据表命令:python3 manage.py migrate
13、user 中urls.py中代码:
"""blog URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r\'^$\', views.home, name=\'home\') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r\'^$\', Home.as_view(), name=\'home\') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r\'^blog/\', include(blog_urls)) """ from django.conf.urls import include, url from .views import user_regist,user_login,user_logout urlpatterns = [ url(r\'^user_regist/$\',user_regist,name=\'user_regist\'), url(r\'^user_login/$\',user_login,name=\'user_login\'), url(r\'^user_logout/$\',user_logout,name=\'user_logout\'), ]
14、user 中views.py中代码:
from django.shortcuts import render,redirect from django.core.urlresolvers import reverse from .forms import UserRegisterForm,UserLoginForm from .models import UserProfile from django.contrib.auth import authenticate,logout,login from articles.models import ArticleInfo,TagInfo # Create your views here. from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage def index(request): all_articles = ArticleInfo.objects.all() #在django内部orm模型查询集上可以支持排序和切片,但是切片不能是负索引 #浏览排行 date_time = all_articles.datetimes(\'add_time\',\'day\',order=\'DESC\') click_sort = all_articles.order_by(\'-click_num\')[:6] #站长推荐 pro_arts = all_articles.order_by(\'-add_time\')[:6] all_tags = TagInfo.objects.all() year = request.GET.get(\'year\',\'\') month = request.GET.get(\'month\',\'\') day = request.GET.get(\'day\',\'\') tagid = request.GET.get(\'tagid\', \'\') if year and month and day: all_articles = all_articles.filter(add_time__year=year,add_time__month=month,add_time__day=day) all_articles_set = set(all_articles) if tagid: tag = TagInfo.objects.filter(id=int(tagid))[0] all_articles = tag.article.all() all_articles_set1 = set(all_articles) # all_articles = [article for article in all_tag_articles if article in all_articles] try: a = list(all_articles_set & all_articles_set1) if a: all_articles = a except: pass pa = Paginator(all_articles,2) pagenum = request.GET.get(\'pagenum\',1) try: pages = pa.page(pagenum) except PageNotAnInteger: pages = pa.page(1) except EmptyPage: pages = pa.page(pa.num_pages) return render(request,\'index.html\',{ # \'all_articles\':all_articles \'pages\':pages, \'click_sort\':click_sort, \'pro_arts\':pro_arts, \'all_tags\':all_tags, \'tagid\':tagid, \'date_time\':date_time, \'year\':year, \'month\':month, \'day\':day }) def user_register(request): if request.method == \'GET\': return render(request,\'reg.html\') else: #实例化form类,用来验证用户提交的数据 user_register_form = UserRegisterForm(request.POST) #一个判断方法:判断这个form验证是否通过(合法),如果合法返回True,不合法返回False if user_register_form.is_valid(): #如果验证合法,那么会把合法的干净的数据存储在form对象的一个属性cleaned_data #当中,这个属性是一个字典,我们可以这样去拿干净的数据 username = user_register_form.cleaned_data[\'username\'] email = user_register_form.cleaned_data[\'email\'] url = user_register_form.cleaned_data[\'url\'] password = user_register_form.cleaned_data[\'password\'] password1 = user_register_form.cleaned_data[\'password1\'] user = UserProfile.objects.filter(username=username) if user: return render(request,\'reg.html\',{ \'msg\':\'帐号已经存在\' }) else: if password == password1: a = UserProfile() a.username =username a.email = email a.url = url a.password = password a.set_password(password) a.save() return redirect(reverse(\'users:user_login\')) else: return render(request, \'reg.html\', { \'msg\': \'密码不一致\' }) else: return render(request, \'reg.html\', { \'user_register_form\': user_register_form }) def user_login(request): if request.method == \'GET\': return render(request,\'login.html\') else: user_login_form = UserLoginForm(request.POST) if user_login_form.is_valid(): username = user_login_form.cleaned_data[\'username\'] password = user_login_form.cleaned_data[\'password\'] user = authenticate(username = username,password = password) if user: login(request,user) return redirect(reverse(\'index\')) else: return render(request,\'login.html\',{ \'msg\':\'用户名或者密码错误\' }) else: return render(request, \'login.html\', { \'user_login_form\': user_login_form }) def user_logout(request): logout(request) return redirect(reverse(\'index\'))
15、articles 中admin.py中代码:
from django.contrib import admin from .models import ArticleInfo,Category,TagInfo,CommentInfo # Register your models here. # Create your models here. class CategoryAdmin(admin.ModelAdmin): list_display = [\'name\',\'add_time\'] fields = [\'name\',\'add_time\'] class ArticleInfoAdmin(admin.ModelAdmin): list_display = [\'title\', \'author\',\'desc\',\'content\',\'is_delete\',\'click_num\',\'love_num\',\'image\',\'add_time\',\'category\'] fields = [\'title\', \'author\',\'desc\',\'content\',\'is_delete\',\'click_num\',\'love_num\',\'image\',\'add_time\',\'category\'] class TagInfoAdmin(admin.ModelAdmin): list_display = [\'name\', \'add_time\'] fields = [\'name\', \'add_time\',\'article\'] filter_horizontal = [\'article\'] class CommentInfoAdmin(admin.ModelAdmin): list_display = [\'comment_man\', \'add_time\',\'comment_art\',\'comment_content\',\'is_delete\'] fields = [\'comment_man\', \'add_time\',\'comment_art\',\'comment_content\',\'is_delete\'] admin.site.register(Category,CategoryAdmin) admin.site.register(ArticleInfo,ArticleInfoAdmin) admin.site.register(TagInfo,TagInfoAdmin) admin.site.register(CommentInfo,CommentInfoAdmin)
16、articles 中models.py中代码:
from django.db import models from datetime import datetime from users.models import UserProfile # Create your models here. class Category(models.Model): name = models.CharField(max_length=20,verbose_name="文章类别") add_time = models.DateTimeField(default=datetime.now,verbose_name="添加时间") def __str__(self): return self.name class Meta: verbose_name = "类别信息" verbose_name_plural = verbose_name class ArticleInfo(models.Model): title = models.CharField(max_length=50,verbose_name="文章标题") author = models.ForeignKey(UserProfile,verbose_name=\'文章作者\') category = models.ForeignKey(Category,verbose_name="所属类别",null=True,blank=True) desc = models.CharField(max_length=200,verbose_name="文章摘要") content = models.TextField(verbose_name="文章内容") is_delete = models.BooleanField(default=False,verbose_name="是否删除") click_num = models.IntegerField(default=0,verbose_name="浏览量") love_num = models.IntegerField(default=0,verbose_name="点赞数") image = models.ImageField(max_length=200,verbose_name="文章图片",upload_to=\'article/%y/%m/%d\') add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") def __str__(self): return self.title class Meta: verbose_name = \'文章信息\' verbose_name_plural = verbose_name class TagInfo(models.Model): name = models.CharField(max_length=20,verbose_name=\'以上是关于Django项目的第1个应用的主要内容,如果未能解决你的问题,请参考以下文章Django L1 编写你的第一个Django应用,第1部分