Django – 创建一个多页网站
Django 是一个基于Python的开源框架,用于 Web 开发。 Django 允许使用 MTV(模型-模板-视图)架构模式来创建和部署功能性网站。
本文旨在使用 Django 创建一个多页个人资料网站,以解释 Django 框架的所有主要概念和方面。
注意:下面文章中的 HTML 和 CSS 代码是初级的。
执行:
首先在任何支持Python的 IDE 中创建一个新项目。
- 打开终端并开始使用以下命令安装 Django:
pip install django
- 使用以下命令创建一个 Django 项目(我们称之为profile ):
django-admin startproject Profile
- 项目创建完成后,导航到项目文件:
cd Profile
- 在项目中创建一个应用程序(我们称之为基础)(这对于大型多方面网站很方便):
django-admin startapp base
导航到 profile/profile 目录中的 settings.py 文件并查找列表名称 INSTALLED_APPS
- 将以下元素添加到列表的末尾:(这是项目作为要链接到 Profile 项目的基础应用程序所必需的)
'base.apps.BaseConfig',
向下滚动到 settings.py 文件中名为 TEMPLATED 的列表
- 将以下元素添加到“DIRS”列表中:(这是添加 HTML 代码所必需的)
BASE_DIR / 'templates',
进一步向下滚动,您会发现一个名为 STATIC_URL 的变量。
- 在 STATIC_URL 变量之后的行中添加以下列表
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
这是你的settings.py应该是这样的:
Python3
"""
Django settings for Profile project.
Generated by 'django-admin startproject' using Django 4.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
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/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-%y9#-d_f74fdq6t6qal(51b4-j1v7f)g+c&7cb1g_wuz_94xq%'
# 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',
'base.apps.BaseConfig',
]
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 = 'Profile.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
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 = 'Profile.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/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/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Python3
"""Profile URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('base.urls')),
]
Python3
from django.shortcuts import render
def home(request):
return render(request, "home.html")
def projects(request):
return render(request, "projects.html")
def contact(request):
return render(request, "contact.html")
Python3
from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home"),
path("projects/", views.projects, name="projects"),
path("contact/", views.contact, name="contact"),
]
CSS
navbar {
width: 100%;
margin:0px 0;
}
navbar ul{
width: 100%;
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
}
navbar ul li{
width: 33%;
float: left;
}
navbar ul li a{
text-decoration: none;
color: rgb(0, 0, 0);
text-align: center;
padding: 20px 0;
display: block;
width: 100%;
background-color: rgb(160, 236, 145);
}
navbar ul li a:hover {
background-color: rgb(11, 221, 29);
}
.home{
margin-right: 5%;
margin-top: 15px;
margin-left: 15px;
margin-bottom: 15px;
padding-top: 15px;
padding-left: 15px;
padding-right: 5px;
padding-bottom: 15px;
border-radius: 10px;
box-shadow: 15px 15px 15px black;
text-align: justify;
color: white;
background-image: linear-gradient(rgb(129, 196, 235), rgb(5, 44, 151));
}
.project-area {
background-repeat: no-repeat;
background-position: left;
box-sizing: border-box;
}
.project-item {
width: 75%;
margin-top:5px;
margin-bottom:15px;
margin-left: 5%;
margin-right: 5%;
padding-top:5px;
padding-bottom:5px;
padding-left: 30px;
padding-right: 30px;
border-radius: 10px;
box-shadow: 10px 10px 40px gray;
text-align: justify;
color: white;
background-color: black;
}
#project {
border-left: 15px solid;
border-image: linear-gradient(purple, tomato);
border-image-slice: 1;
}
#contact .contact-item {
background-color: aquamarine;
float: left;
width: 20%;
padding: 20px;
text-align: center;
border-radius: 10px;
padding: 30px;
margin: 30px;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
box-shadow: 15px 15px 15px black;
}
HTML
HTML
{% include 'navbar.html' %}
{% load static %}
Home
ABOUT ME
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
HTML
{% include 'navbar.html' %}
{% load static %}
Projects
PROJECTS
PROJECT 1 NAME
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vestibulum dignissim, sapien et efficitur vulputate,
felis blandit metus, vitae eleifend nisl justo sed nunc.
Sed ut nunc malesuada, scelerisque mauris sed, hendrerit neque.
Morbi eget nisl non tellus posuere iaculis.
Nunc ut tincidunt est, a tempus tortor. Mauris lobortis felis elit,
quis euismod urna lacinia vitae. Morbi interdum diam in faucibus finibus.
Sed pellentesque sem a diam rhoncus, eu semper neque efficitur.
PROJECT 2 NAME
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vestibulum dignissim, sapien et efficitur vulputate,
felis blandit metus, vitae eleifend nisl justo sed nunc.
Sed ut nunc malesuada, scelerisque mauris sed, hendrerit neque.
Morbi eget nisl non tellus posuere iaculis.
Nunc ut tincidunt est, a tempus tortor. Mauris lobortis felis elit,
quis euismod urna lacinia vitae. Morbi interdum diam in faucibus finibus.
Sed pellentesque sem a diam rhoncus, eu semper neque efficitur.
HTML
{% include 'navbar.html' %}
{% load static %}
Contact
CONTACT INFO
Phone Number
+xx-xxxxxxxxxx