在最后部署到服务器上的操作没有完成
"""
Django settings for learning_log project.
Generated by 'django-admin startproject' using Django 3.1.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '=c$2p@856395v59tghab)#g&zhd-lp)ujns3a#ysw16_9ow=)1'
# SECURITY WARNING: don't run with debug turned on in production!
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',
'learning_logs',
'hello',
'users',
#第三方应用程序
'bootstrap3'
]
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': [],
'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/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_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/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
#my settings
LOGIN_URL = '/users/login/'
#django-bootstrap3的设置
BOOTSTRAP3 = {
'include_jquery': True,
}
# Heroku 设置
cwd =os.getcwd()
if os.getcwd() == '/app':
import dj_database_url
DATABASES = {
'default': dj_database_url.config(default='postgres://localhost')
}
# 让request.is_secure承认X-Forwarded-Proto头
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# 支持所有的主机头(host header)
ALLOWED_HOSTS = ['*']
# 静态资产配置
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, 'staticfiles'))
STATICFILES_DIRS = {
os.path.join(BASE_DIR, 'static')
}
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('index/',include('learning_logs.urls',namespace='learning_logs')),
path('hello/',include('hello.urls',namespace='hello')),
path('users/',include('users.urls',namespace='users')),
]
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning_log.settings')
application = Cling(get_wsgi_application())
from django.contrib import admin
# Register your models here.
from learning_logs.models import Topic,Entry
admin.site.register(Topic)
admin.site.register(Entry)
"""
定义learning_logs的url模式
"""
from django.urls import path,re_path
from . import views
app_name = 'learning_logs'
urlpatterns = [
path('',views.index,name='index'),
path('topics/',views.topics,name='topics'),
re_path(r'topics/(?P<topic_id>\d+)/',views.topic,name='topic'),
path('new_topic/',views.new_topic,name='new_topic'),
re_path(r'new_entry/(?P<topic_id>\d+)/',views.new_entry,name='new_entry'),
re_path(r'edit_entry/(?P<entry_id>\d+)/',views.edit_entry,
name='edit_entry'),
]
from django import forms
from .models import Topic,Entry
class 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})}
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Topic(models.Model):
text = models.CharField(max_length=200)
date_add = models.DateTimeField(auto_now_add=True)
#添加一个返回值,不包含在返回值中的变量将不会被返回
owner = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return (self.text)
class Entry(models.Model):
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
#给模型换一个名字,如果不添加下面这一条,会在entry后面直接加上s
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
if len(self.text) > 50:
return self.text[:50]+'...'
else:
return self.text
from django.shortcuts import render
from . models import Topic,Entry
from django.http import HttpResponseRedirect,Http404
from django.urls import reverse
from . forms import TopicForm,EntryForm
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
"""学习笔记的主页"""
return render(request,'learning_logs/index.html')
@login_required
def topics(request):
""" 显示所有主题的页面"""
topics = Topic.objects.filter(owner=request.user).order_by('date_add')
context = {'topics':topics}
return render(request,'learning_logs/topics.html',context)
@login_required
def 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_required
def new_topic(request):
"""让用户添加新的主题"""
if request.method != 'POST':
"""未提交数据,创建一个空表单"""
form = TopicForm()
else:
form = TopicForm(request.POST)
"""POST提交的数据,对数据进行处理"""
if form.is_valid():
new_topic = form.save(commit=False)
new_topic.owner = request.user
new_topic.save()
return HttpResponseRedirect(reverse('learning_logs:topics'))
context = {'form':form}
return render(request,'learning_logs/new_topic.html',context)
@login_required
def new_entry(request,topic_id):
"""让用户添加新的条目"""
topic = Topic.objects.get(id=topic_id)
if request.method != 'POST':
form = EntryForm()
else:
form = EntryForm(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_required
def edit_entry(request,entry_id):
"""让用户编辑已有条目"""
entry = Entry.objects.get(id=entry_id)
topic = entry.topic
if request.method != 'POST':
#初次请求,使用当前条目填充表单
form = EntryForm(instance=entry)
else:
#post提交数据,对数据进行处理
form = EntryForm(instance=entry, data=request.POST)
if form.is_valid():
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)
{% load bootstrap3 %}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Learning Log</title>
{% bootstrap_css %}
{% bootstrap_javascript %}
</head>
<body>
<!-- Static navbar -->
<nav class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
</button>
<a class="navbar-brand" href="{% url 'learning_logs:index' %}">
Learnin Log</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="{% url 'learning_logs:topics' %}">Topic</a><li>
</ul>
<ul class="nav navbar-nav navbar-right">
{% if user.is_authenticated %}
<li><a>Hello, {{ user.username }}</a></li>
<li><a href="{% url 'users:logout' %}">log out</a></li>
{% else %}
<li><a href="{% url 'users:register' %}">register</a></li>
<li><a href="{% url 'users:login' %}">log in</a></li>
{% endif %}
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="page-header">
{% block header %}{% endblock header %}
</div>
<div>
{% block content %}{% endblock content %}
</div>
</div><!--/container -->
</body>
</html>
{% extends "learning_logs/base.html" %}
{% block header %}
<div class="jumbotron">
<h1>Track Your Learning</h1>
</div>
{% endblock header %}
{% block content %}
<h2>
<a href="{% url 'users:register' %}">Register an account</a>
to make your own Learning Log, and list the topics you're learning about.
</h2>
<h2>It's a good way to summarize your learning through Learning Log</h2>
<p>
Learning Log help you kepp track of your learning, for any topic you're
learning about.
</p>
{% endblock content %}
{% extends "learning_logs/base.html" %}
{% block header %}
<h1>Topics</h1>
{% endblock header%}
{% block content %}
<p>Topics</p>
<ul>
{% for topic in topics %}
<li>
<h3>
<a href="{% url 'learning_logs:topic' topic_id=topic.id %}">{{ topic }}</a>
</h3>
</li>
{% empty %}
<li>No topics bro<li>
{% endfor %}
</ul>
<h3>
<a href="{% url 'learning_logs:new_topic' %}">Add a new topic:</a>
</h3>
{% endblock content %}
{% extends "learning_logs/base.html" %}
{% block header %}
<h2>{{topic}}</h2>
{% endblock header %}
{% block content %}
<p>Topic: {{topic}}</p>
<p>Entries:<p/>
<ul>
{% for entry in entries %}
<div class="panel panel-default">
<div class="panel-heading">
<h3>{{ entry.date_added|date:'Y m d H:i:s' }}
<small>
<a href="{% url 'learning_logs:edit_entry' entry.id%}">
edit this entry</a>
</small>
</h3>
</div>
<div class="panel-body">
{{ entry.text|linebreaks }}
</div>
</div><!--/panel -->
{% empty %}
There are no enteies for this topic right now
{% endfor %}
</ul>
<h3>
<a href="{% url 'learning_logs:new_entry' topic.id %}">add new entry</a>
</h3>
{% endblock content %}
{% extends "learning_logs/base.html" %}
{% load bootstrap3 %}
{% block header %}
<h2>Add a new topic:</h2>
{% endblock header %}
{% block content %}
<form action="{% url 'learning_logs:new_topic' %}" method='post' class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button name="submit" class="btn btn-primary">add topic</button>
{% endbuttons %}
</form>
{% endblock content %}
{% extends "learning_logs/base.html" %}
{% block content %}
<p><a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p>
<p>Add a new entry:</p>
<form action="{% url 'learning_logs:new_entry' topic.id %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name='submit'>Add entry</button>
</form>
{% endblock content %}
{% extends "learning_logs/base.html" %}
{% block content %}
<p><a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p>
<p>Edit entry:</p>
<form action="{% url 'learning_logs:edit_entry' entry.id %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name='submit'>save change</button>
</form>
{% endblock content %}
from django.urls import path,include,re_path
from django.contrib.auth.views import LoginView
from django.contrib.auth import logout,login,authenticate
from . import views
app_name = 'users'
LoginView.template_name = 'users/login.html'
urlpatterns = [
path('login/',LoginView.as_view(),name='login'),
path('logout/',views.logout_view, name='logout'),
path('register/',views.register, name='register'),
]
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.views import LoginView
from django.contrib.auth import logout,login,authenticate
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def logout_view(request):
"""注销用户"""
logout(request)
return HttpResponseRedirect(reverse('learning_logs:index'))
def register(request):
"""注册新用户"""
if request.method != 'POST':
"""显示空的注册表单"""
form = UserCreationForm()
else:
"""处理填写好的表单"""
form = UserCreationForm(data=request.POST)
if form.is_valid():
new_user = form.save()
#让用户自动登录,再重定向到主页
authenticated_user = authenticate(username=new_user.username,
password=request.POST['password1'])
login(request,authenticated_user)
return HttpResponseRedirect(reverse('learning_logs:index'))
context = {'form':form}
return render(request,'users/register.html',context)
{% extends "learning_logs/base.html" %}
{% load bootstrap3 %}
{% block header %}
<h2>Log in to your account.</h2>
{% endblock header %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match.
<br>
Please try it again
</p>
{% endif %}
<form method="post" action="{% url 'users:login' %}" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button name="submit" class="btn btn-primary">login in</button>
{% endbuttons %}
<input type="hidden" name="next" value="{% url 'learning_logs:index' %}"/>
</form>
{% endblock content %}
{% extends "learning_logs/base.html" %}
{% block content %}
<form method="post" action="{% url 'users:register' %}">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">register</button>
<input type="hidden" name="next" value="{% url 'learning_logs:index' %}"/>
</form>
{% endblock content %}