废话少说了,开干。
一、新建一个容器,并进入
docker run -i -t --privileged -p 8089:8000 --name django-test cr.loongnix.cn/loongson/loongnix-server:8.4 /usr/sbin/init
二、安装python,看看loongnix-server有什么版本的python,当时给了几个选项,python2、python36、python38,python38后期不能成功安装django,所以我选择安装了python36
yum install python36
三、安装Django
pip3 install django
四、创建一个新的Django项目和应用
django-admin startproject myproject
cd myproject
python3 manage.py startapp myapp
五、配置项目以使用myapp
应用,并在myproject/settings.py
中的INSTALLED_APPS
列表中添加它:
INSTALLED_APPS = [
# ...
'myapp',
# ...
]
使用另外一个容器的Mysql数据库,在myproject/settings.py
中的IDATABASES
列表中添加它:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'your_database_name',
'USER': 'your_mysql_username',
'PASSWORD': 'your_mysql_password',
'HOST': 'localhost', # 或者是你的MySQL服务器的IP地址
'PORT': '3306', # MySQL的默认端口是3306
}
}
六、为了在Django项目中设置MySQL数据库,你需要按照以下步骤操作:
确保你已经安装了mysqlclient
这个Python库,这是连接MySQL数据库的官方驱动。如果还没有安装,可以通过以下方式安装:
-
更改pip3的源为国内、更新pip及工具
pip3 install --index-url https://pypi.tuna.tsinghua.edu.cn/simple some-package pip3 install --upgrade pip setuptools
-
安装mysqlclient的一些依赖库
-
yum install python3-dev default-libmysqlclient-dev yum install gcc pip3 install mysqlclient
七、使用一个登录页面验证环境是否成功,做法如下:
1、在myapp
应用中创建一个模型来存储用户(虽然Django自带了用户认证系统django.contrib.auth
,但为了简单起见,我们这里仍然创建一个简单的模型):
# myapp/models.py
from django.db import models
class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=100) # 在实际应用中,你应该使用django的PasswordField
def __str__(self):
return self.username
2、然后,创建一个表单来验证用户输入:
# myapp/forms.py
from django import forms
from .models import User
class LoginForm(forms.Form):
username = forms.CharField(label='Username')
password = forms.CharField(label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super().clean()
username = cleaned_data.get('username')
password = cleaned_data.get('password')
if User.objects.filter(username=username, password=password).exists():
return cleaned_data
raise forms.ValidationError("Invalid username or password.")
3、接着,在myapp/views.py
中创建视图来处理登录逻辑:
# myapp/views.py
from django.shortcuts import render, redirect
from .forms import LoginForm
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
# 登录逻辑处理,例如设置session等
return redirect('dashboard') # 重定向到dashboard视图
else:
form = LoginForm()
return render(request, '../templates/myapp/login.html', {'form': form})
def dashboard_view(request):
return render(request, '../templates/myapp/dashboard.html', {'title': 'Dashboard'})
4、在myproject/urls.py
中配置URL:
# myproject/urls.py
from django.urls import path
from myapp import views
urlpatterns = [
path('', views.login_view, name='login'),
path('dashboard/', views.dashboard_view, name='dashboard'),
]
5、创建登录页面模板login.html
在myapp/templates/myapp/
目录下:
<!-- myapp/templates/myapp/login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
</body>
</html>
6、同样,创建dashboard页面模板dashboard.html
:
<!-- myapp/templates/myapp/dashboard.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h1>Welcome to the Dashboard!</h1>
</body>
</html>
7、最后,运行Django开发服务器:
python3 manage.py runserver
出现红色字体
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
按ctrl+c退出,敲入命令
python3 manage.py migrate
再次运行python3 manage.py runserver
八、在浏览器输入地址http://x.x.x.x:8089,显示无法访问,需要放行ip,修改myproject/settings.py
中的ALLOWED_HOSTS
ALLOWED_HOSTS = ['*']
再次运行python3 manage.py runserver,情况依旧,修改命令
python3 manage.py runserver 0.0.0.0:8000
刷新网页,可以显示login.html网页
九、附上mysql数据库创建表格命令
create table myapp_user(id INT AUTO_INCREMENT PRIMARY KEY,
-> username VARCHAR(50) NOT NULL,
-> password VARCHAR(100) NOT NULL);