作业,编辑

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>username</th>
                    <th>password</th>
                    <th>action</th>
                </tr>
                </thead>
                <tbody>
                {% for user_obj in user_list %}
                    <tr>
                    <td>{{ user_obj.id }}</td>
                    <td>{{ user_obj.username }}</td>
                    <td>{{ user_obj.password }}</td>
                    <td><a href="{% url 'edit_user' user_obj.id %}" class="btn btn-primary btn-xs">编辑</a>
                    <a href="{% url 'delete_user' user_obj.id %}" class="btn btn-danger btn-xs">删除</a></td>
                    </tr>

                {% endfor %}

                </tbody>
            </table>
         <a href="/create_user/" class="btn btn-danger btn-xs">增加</a>
        </div>
    </div>
</div>
def userlist(request):
    user_list = models.User.objects.all()
    return render(request,'userlist.html',locals())


def edit_user(request,user_id):
    # 先获取页面上它要操作的id值

    # 去models里面查询他们要编辑的对象数据
    edit_obj = models.User.objects.filter(id=user_id).first()

    if request.method == 'POST':
        # 在后端页面获取他们要修改的值
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 修改他们的值
        models.User.objects.filter(id=user_id).update(username=username,password=password)
        return redirect('/userlist/')

    return render(request,'edit_user.html',locals())



def delete_user(request,user_id):
    user_id = request.GET.get('user_id')
    models.User.objects.filter(id=user_id).delete()
    return redirect('/userlist/')


def create_user(request):
    if request.method == 'POST':
        # 获取用户名和密码
        username = request.POST.get('username')
        password = request.POST.get('password')
        user_obj = models.User.objects.filter(username=username).first()
        if not user_obj:

            user_obj = models.User(username=username,password=password)
            user_obj.save()
            return redirect('/userlist/')
        return HttpResponse('用户已存在')
    return render(request, 'create_user.html',locals())
  url(r'^edit_user/(\d+)/', views.edit_user,name='edit_user'),
    url(r'^delete_user/(\d+)/', views.delete_user,name='delete_user'),
    url(r'^create_user/', views.create_user)
posted @ 2020-05-27 22:24  清轩挽长风  阅读(121)  评论(0编辑  收藏  举报