在此我将用Django来开发一个名为“Learning Log“的项目。这个项目让用户能够记录感兴趣的主题,并在学习每个主题的过程中可以添加日志条目。”Learning Log“的主页对这个网站进行描述,并邀请用户注册或者登录。用户登陆后就可创建新主题,添加新条目,以及阅读既有的条目。每个用户都有自己的数据,每个用户仅可观看和修改自己所拥有的条目。
一、效果图
二、文件存储路径图
三。创建项目以及所需文件
1、创建Learning_log项目。
2、创建数据库
python manage.py migrate
在使用SQLite的新项目中首次执行migrate这个命令式,Django将新建一个数据库。
3.安装django-bootstrap3
pip install django-bootstrap3
4、创建应用程序
命令 startapp appname 让Django建立创建应用程序所需的基础设施。
python manage.py startapp learning_logs#创建learning_logs应用程序 python manage.py startapp users#创建一个名为users的应用程序
4、定义模型
learning_logs/models.py
from django.db import modelsfrom django.contrib.auth.models import User# Create your models here.class Topic(models.Model): '''用户学习的主题''' text=models.CharField(max_length=200) date_added=models.DateTimeField(auto_now_add=True) owner=models.ForeignKey(User) def __str__(self): '''返回模型的字符串表示''' return self.textclass Entry(models.Model): '''学到的有关某个主题的具体知识''' topic=models.ForeignKey(Topic) text=models.TextField() date_added=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural='entries' def __str__(self): '''返回模型的字符串表示''' return self.text[:50]+"..."
settings.py
"""Django settings for learning_log project.Generated by 'django-admin startproject' using Django 1.11.6.For more information on this file, seehttps://docs.djangoproject.com/en/1.11/topics/settings/For the full list of settings and their values, seehttps://docs.djangoproject.com/en/1.11/ref/settings/"""import os# Build paths inside the project like this: os.path.join(BASE_DIR, ...)BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'xsxgdt)%7$b)ue=5lde!!s7d1-ey(ar0==li=g&t8)$5pluui!'# SECURITY WARNING: don't run with debug turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #第三方应用程序 'bootstrap3', #我的应用程序 'learning_logs', 'users',]MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',]ROOT_URLCONF = 'learning_log.urls'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', ], }, },]WSGI_APPLICATION = 'learning_log.wsgi.application'# Database# https://docs.djangoproject.com/en/1.11/ref/settings/#databasesDATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}# Password validation# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validatorsAUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },]# Internationalization# https://docs.djangoproject.com/en/1.11/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/1.11/howto/static-files/STATIC_URL = '/static/'#我的设置LOGIN_URL='/users/login/'#django-bootstrap3的设置BOOTSTRAP3={ 'include_jquery':True,}
admin.py
from django.contrib import admin# Register your models here.from learning_logs.models import Topic,Entryadmin.site.register(Topic)admin.site.register(Entry)
修改数据库库和创建超级用户
urls.py
"""learning_log URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/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. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))"""from django.conf.urls import url,includefrom django.contrib import adminurlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('learning_logs.urls',namespace='learning_logs')), url(r'^users/',include('users.urls',namespace='users')),]
learning_logs/urls.py
"""定义learning_logs的URL模式"""from django.conf.urls import urlfrom . import viewsurlpatterns=[ #主页 url(r'^$',views.index,name='index'), #显示所有的主题 url(r'^topics$',views.topics,name='topics'), #特定主题的详细页面 url(r'^topics/(?P\d+)/$',views.topic,name='topic'), #用于添加新主题的网页 url(r'^new_topic/$',views.new_topic,name='new_topic'), #用于添加新条目的页面 url(r'^new_entry/(?P \d+)/$',views.new_entry,name='new_entry'), #用于编辑条目的页面 url(r'^edit_entry/(?P \d+)/$',views.edit_entry,name='edit_entry'),]
learning_logs/views.py
from django.shortcuts import renderfrom .models import Topic,Entryfrom django.http import HttpResponseRedirectfrom django.core.urlresolvers import reversefrom .forms import TopicForm,EntryFormfrom django.contrib.auth.decorators import login_requiredfrom django.http import HttpResponseRedirect,Http404# Create your views here.def index(request): '''学习笔记的主页''' return render(request, 'learning_logs/index.html')@login_requireddef topics(request): '''显示所有的主题''' topics=Topic.objects.filter(owner=request.user).order_by('date_added') context={ 'topics':topics} return render(request, 'learning_logs/topics.html', context)@login_requireddef topic(request,topic_id): '''显示单个主题及其所有的条目''' topic=Topic.objects.get(id=topic_id) if topic.owner!=request.user: raise Http404 entries=topic.entry_set.order_by('-date_added') context={ 'topic':topic,'entries':entries} return render(request, 'learning_logs/topic.html', context)@login_requireddef new_topic(request): '''添加新主题''' if request.method!='POST': #未提交数据:创建一个新表单 form=TopicForm(request.POST) else: #POST提交的数据,对数据进行处理 form=TopicForm(request.POST) if form.is_vaild(): new_topic=form.save(commit=False) new_topic.owner=request.user new_topic.save() form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context={ 'form':form} return render(request, 'learning_logs/new_topic.html', context)@login_requireddef new_entry(request,topic_id): '''在特定的主题中添加新条目''' topic=Topic.objects.get(id=topic_id) if request.method!='POST': #未提交数据,创建一个新表单 form=EntryForm() else: #POST提交的数据,对数据进行处理 form=EntryForm(data=request.POST) if form.is_valid(): new_entry=form.save(commit=False) new_entry.topic=topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id])) context = { 'topic':topic,'form': form} return render(request, 'learning_logs/new_entry.html', context)@login_requireddef edit_entry(request,entry_id): '''编辑既有条目''' entry=Entry.objects.get(id=entry_id) topic=entry.topic if topic.owner!=request.user: raise Http404 if request.method!='POST': #初次请求,使用当前条目填充表单 form=EntryForm(instance=entry) else: #POST提交的数据,对数据进行处理 form=EntryForm(instance=entry,data=request.POST) if form.is_vail(): form.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id])) context = { 'entry': entry,'topic':topic, 'form': form} return render(request, 'learning_logs/edit_entry.html', context)
forms.py
from django import formsfrom .models import Topic,Entryclass TopicForm(forms.ModelForm): class Meta: model=Topic fields=['text'] labels={ 'text':''}class EntryForm(forms.ModelForm): class Meta: model=Entry fields=['text'] labels={ 'text':''} widgets={ 'text':forms.Textarea(attrs={ 'cols':80})}
在文件夹learning_logs中新建一个文件夹并将其命名为templates。在文件夹templates中,在创建一个名为learning_logs的文件夹,之后的模板都将保存在这个文件夹中。
base.html
{% load bootstrap3 %}Learning Log { % bootstrap_css %} { % bootstrap_javascript %}{ % block header %}{% endblock header %}{ % block content %}{% endblock content %}
index.html
Title { % extends "learning_logs/base.html" %}{ % block header %}{ % endblock header %}{ % block content %}Track your learning.
Register an account to make your own Learning Log,and list the topics you're learning about.
Whenever you learn something new about a topic,make an entry summarizing what you've learned.
{ % endblock content %}
topics.html
Title { % extends "learning_logs/base.html" %}{ % block header %}Topics
{ % endblock header %}{ % block content %}
- { % for topic in topics %}
-
{ { topic }}
{ % empty %} - No topics have been added yet. { % endfor %}
Add new topic
{ % endblock content %}topic.html
Title { % extends 'learning_logs/base.html' %}{ % block header %}{ { topic }}
{ % endblock header %}{ % block content %} { % for entry in entries %}{ % empty %} There are no entries for this topic yet. { % endfor %}{ % endblock content %}{ { entry.date_added|date:'M d,Y H:i' }} edit entry
{ { entry.text|linebreaks }}
new_topic.html
{ % endblock content %}Title { % extends "learning_logs/base.html" %}{ % load bootstrap3 %}{ % block header %}Add a new topic:
{ % endblock header %}{ % block content %}
new_entry.html
{ % endblock content %}Title { % extends "learning_logs/base.html" %}{ % block content %}Add a new entry:
edit_entry.html
{ % endblock content %}Title { % extends "learning_logs/base.html" %}{ % block content %}Edit entry:
users/urls.py
'''为应用程序users定义URL模式'''from django.conf.urls import urlfrom django.contrib.auth.views import loginfrom .import viewsurlpatterns=[ #登录页面 url(r'^login/$',login,{ 'template_name':'users/login.html'},name='login'), #注销 url(r'^logout/$',views.logout_view,name='logout'), # 注册页面 url(r'^register/$', views.register, name='register'),]
在users文件夹中创建一个名为templates的文件夹,在其中创建一个名为users的文件夹以下的几个模板都将存储在其中。
login.html
{ % endblock content %}Title { % extends "learning_logs/base.html" %}{ % load bootstrap3 %}{ % block header %}Log in to your account.
{ % endblock header %}{ % block content %}
register.html
{ % endblock content %}Title { % extends "learning_logs/base.html" %}{ % block content %}
我也只是一个门外汉,刚刚接触Django,所以表述可能会很不明确,只能自己个人理解。所以,下面是我自己做的这个项目,希望能对你们有一定的帮助
链接:https://pan.baidu.com/s/1lMV95bfdHzhBYpvRTOlufw 密码:th4s