Django,python.MySQL 完成学生信息管理系统,怎么做?
时间: 2024-06-14 16:05:24 浏览: 200
要使用Django、Python和MySQL完成学生信息管理系统,可以按照以下步骤进行:
1. 安装Django和MySQL驱动:
```shell
pip install django
pip install mysqlclient
```
2. 创建Django项目:
```shell
django-admin startproject student_management
```
3. 进入项目目录并创建Django应用:
```shell
cd student_management
python manage.py startapp student
```
4. 配置数据库连接:
在`student_management/settings.py`文件中,找到`DATABASES`配置项,将其修改为:
```python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'your_database_name',
'USER': 'your_username',
'PASSWORD': 'your_password',
'HOST': 'your_host',
'PORT': 'your_port',
}
}
```
5. 创建学生模型:
在`student/models.py`文件中,定义学生模型:
```python
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
grade = models.CharField(max_length=100)
```
6. 迁移数据库:
```shell
python manage.py makemigrations
python manage.py migrate
```
7. 创建视图和URL:
在`student/views.py`文件中,编写视图函数:
```python
from django.shortcuts import render
from .models import Student
def student_list(request):
students = Student.objects.all()
return render(request, 'student_list.html', {'students': students})
```
在`student/urls.py`文件中,添加URL配置:
```python
from django.urls import path
from . import views
urlpatterns = [
path('student_list/', views.student_list, name='student_list'), ]
```
8. 创建模板:
在`student/templates/student_list.html`文件中,编写模板代码:
```html
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>
{% for student in students %}
<tr>
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
<td>{{ student.grade }}</td>
</tr>
{% endfor %}
</table>
```
9. 运行开发服务器:
```shell
python manage.py runserver
```
然后在浏览器中访问`http://localhost:8000/student_list/`,即可查看学生信息列表。
阅读全文