📜  Django – 创建一个多页网站

📅  最后修改于: 2022-05-13 01:54:41.467000             🧑  作者: Mango

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
{% load static %}


    




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

          
        
        
            

Email

            

xyz@example.com

          
        
        
            

Address

            

City, State, Country

          
        
      
    
       


现在,导航到 Profile/Profile 目录中的 urls.py 文件。

from django.urls import include
path('', include('base.urls')),

这就是您的 urls.py 文件的样子:

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')),
]

现在,导航到 Profile/base 目录中的 views.py 文件:

在这里,我们创建不同的页面并分配相应的 HTML 文件(稍后我们将创建)。

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")

在 Profile\base 目录中创建一个名为 urls.py 的新文件

此文件创建指向 views.py 文件中提到的相应网址的 URL

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 文件和图像的文件)。

在主 Profile 项目文件中创建一个名为 static 的新目录。静态文件应与 manage.py 文件处于同一层级。

在此文件中创建另外 2 个目录,称为样式和图像

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;
}

将您自己的图像添加到图像目录并将其重命名为“Profile_img”。

对于 HTML 文件,在名为 templates 的主 Profile 项目文件中创建一个新目录。模板文件应与 manage.py 文件处于同一层次。

HTML

{% load static %}


    


上述代码中的前两行是从静态目录加载 CSS 代码并将 CSS 文件中的代码链接到 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

          
        
        
            

Email

            

xyz@example.com

          
        
        
            

Address

            

City, State, Country

          
        
      
            

现在,对于最后一步,打开一个新终端并运行以下命令:

cd profile
python manage.py runserver

输出: