Django结合Form组件实现curd功能

urls.py


from django.contrib import admin
from django.urls import path
from app import  views

urlpatterns = [
    path('admin/', admin.site.urls),

    path('class_list/',views.class_list ),
    path('add_class/',views.add_class ),
    path('edit_class/<id>/',views.edit_class ),

    path('student_list/',views.student_list ),
    path('add_student/',views.add_student ),
    path('edit_student/<id>/',views.edit_student ),
]

models.py

from django.db import models

class Classes(models.Model):
    title = models.CharField(max_length=32)


class Student(models.Model):
    name = models.CharField(max_length=32)
    email = models.CharField(max_length=32)
    age = models.IntegerField()
    cls = models.ForeignKey('Classes',on_delete=models.CASCADE)


class Teacher(models.Model):
    tname = models.CharField(max_length=32)
    c2t = models.ManyToManyField('Classes')

Remeber reg app,run app!

python manage.py makemigrations

python manage.py migrate

views.py

from django.shortcuts import render,redirect
from app import models
from django.forms import Form,fields,widgets

class ClassForm(Form):
    title=fields.CharField(min_length=2,error_messages={'min_length':'必须大于2'})


def class_list(request):
    cls_list=models.Classes.objects.all()
    return render(request,'class_list.html',{'cls_list':cls_list})

def add_class(request):
    if request.method=='GET':
        obj=ClassForm()
        return render(request,'add_class.html',{'obj':obj})
    else:
        obj=ClassForm(request.POST)
        if obj.is_valid():
            models.Classes.objects.create(**obj.cleaned_data)
            return redirect('/class_list')
        return render(request, 'add_class.html', {'obj': obj})

def edit_class(request,id):
    if request.method=='GET':
        row=models.Classes.objects.filter(id=id).first()
        obj=ClassForm(initial={'title':row.title})
        return render(request,'edit_class.html',{'id':id,'obj':obj})
    else:
        obj=ClassForm(request.POST)
        if obj.is_valid():
            models.Classes.objects.filter(id=id).update(**obj.cleaned_data)
            return redirect('/class_list/')
        return render(request, 'edit_class.html', {'id': id, 'obj': obj})

class StudentForm(Form):
    name=fields.CharField(
        min_length=2,
        max_length=8,
        widget=widgets.TextInput(attrs={'class': 'form-control'})
    )
    email=fields.EmailField(widget=widgets.TextInput(attrs={'class': 'form-control'}))
    age=fields.IntegerField(
        min_value=1,
        max_value=99,
        widget=widgets.TextInput(attrs={'class': 'form-control'})
    )
    cls_id=fields.IntegerField(
        widget=widgets.Select(choices=models.Classes.objects.values_list('id','title'),attrs={'class': 'form-control'})
    )


def student_list(request):
    stu_list=models.Student.objects.all()
    return render(request,'student_list.html',{'stu_list':stu_list})

def add_student(request):
    if request.method=='GET':
        obj=StudentForm()
        return render(request,'add_student.html',{'obj':obj})
    else:
        obj=StudentForm(request.POST)
        if obj.is_valid():
            models.Student.objects.create(**obj.cleaned_data)
            return redirect('/student_list/')
        return render(request, 'add_student.html', {'obj': obj})

def edit_student(request,id):
    if request.method=='GET':
        row=models.Student.objects.filter(id=id).values('name','email','age','cls_id').first()
        obj=StudentForm(initial=row)
        return render(request,'edit_student.html',{'id':id,'obj':obj})
    else:
        obj=StudentForm(request.POST)
        if obj.is_valid():
            models.Student.objects.filter(id=id).update(**obj.cleaned_data)
            return redirect('/student_list/')
        return render(request, 'edit_student.html', {'id': id, 'obj': obj})

class_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>class_list</title>
</head>
<body>
    <h1>Classes_list</h1>
    <div>
        <a href="/add_class/">Add</a>
    </div>
    <ul>
        {% for cls in cls_list %}
        <li>
            {{ cls.title }}<a href="/edit_class/{{ cls.id }}">Edit</a>
        </li>
        {% endfor %}
    </ul>
</body>
</html>

add_class.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add_class</title>
</head>
<body>
    <h1>Add_Class</h1>
    <form method="post" action="/add_class/" novalidate>
        {% csrf_token %}
        {{ obj.title }} {{ obj.errors.title.0 }}
        <input type="submit" value="Post">
    </form>
</body>
</html>

edit_class.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit_Class</title>
</head>
<body>
    <h1>Edit_Class</h1>
    <form method="post" action="/edit_class/{{ id }}/">
        {% csrf_token %}
        <p>
            {{ obj.title }} {{ obj.errors.title.0 }}
        </p>
        <input type="submit" value="Update">
    </form>
</body>
</html>

student_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>StudentList</title>
</head>
<body>
    <h1>Student_list</h1>
    <div>
        <a href="/add_student/">Add</a>
    </div>
    <ul>
        {% for stu in stu_list %}
            <li>
                {{ stu.name }}--{{ stu.email }}--{{ stu.age }}--{{ stu.cls.title }}
                <a href="/edit_student/{{ stu.id }}/">Edit</a>
            </li>
        {% endfor %}
    </ul>
</body>
</html>

add_student.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add_Student</title>
</head>
<body>
    <h1>Add_Student</h1>
    <form method="post" action="/add_student/" novalidate>
        {% csrf_token %}
        <p>{{ obj.name }}{{ obj.errors.name.0 }}</p>
        <p>{{ obj.email }}{{ obj.errors.email.0 }}</p>
        <p>{{ obj.age }}{{ obj.errors.age.0 }}</p>
        <p>{{ obj.cls_id }}{{ obj.errors.cls_id.0 }}</p>
        <input type="submit" value="Add">
    </form>
</body>
</html>

edit_student.html

样式自定义,组件绑定class

widget=widgets.TextInput(attrs={'class': 'form-control'})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit_Student</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
</head>
<body>
    <h1>Edit_Student</h1>
    <div style="width: 500px;margin: 0 auto;">

        <form class="form-horizontal" method="post" action="/edit_student/{{ id }}/">
        {% csrf_token %}
        <div class="form-group">
            <label class="col-sm-2 control-label">Name:</label>
            <div class="col-sm-10">
                {{ obj.name }} {{ obj.errors.name.0 }}
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">Email:</label>
            <div class="col-sm-10">
                {{ obj.email }} {{ obj.errors.email.0 }}
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">Age:</label>
            <div class="col-sm-10">
                {{ obj.age }} {{ obj.errors.age.0 }}
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">Class:</label>
            <div class="col-sm-10">
                {{ obj.cls_id }} {{ obj.errors.cls_id.0 }}
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" class="btn btn-default" value="Update" />
            </div>
        </div>
    </form>
    </div>
</body>
</html>
发布了26 篇原创文章 · 获赞 0 · 访问量 588

猜你喜欢

转载自blog.csdn.net/kkLeung/article/details/105037696