Django4全栈进阶之路18 项目实战(用户管理):user_edit.html用户编辑画面设计

1、模块

{% extends 'base.html' %}
{% block content %}
    <!-- 编辑用户表单 -->
    <div class="card mt-3">
        <div class="card-header">编辑用户</div>
        <div class="card-body">
            <form method="post">
                {% csrf_token %}
                <div class="form-group">
                    <label for="username">用户名:</label>
                    <input type="text" class="form-control" id="username" name="username" value="{{ user.username }}">
                </div>
                <div class="form-group">
                    <label for="password">密码:</label>
                    <input type="password" class="form-control" id="password" name="password"
                           value="{{ user.password }}">
                </div>
                <div class="form-group">
                    <label for="confirm_password">确认密码:</label>
                    <input type="password" class="form-control" id="confirm_password" name="confirm_password"
                           value="{{ user.password }}">
                </div>
                <div class="form-group">
                    <label for="email">Email:</label>
                    <input type="email" id="email" name="email" required class="form-control">
                </div>
                <button type="submit" class="btn btn-primary">保存</button>
                <a href="{% url 'user_list' %}?success=true" class="btn btn-secondary btn-sm">返回</a>
            </form>
        </div>
    </div>
{% endblock %}

 

2、视图

@login_required
def user_edit_view(request, pk):
    # 根据 user_id 获取对应的用户对象
    user = get_object_or_404(User, pk=pk)
    if request.method == 'POST':
        # 获取用户提交的表单数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        confirm_password = request.POST.get('confirm_password')

        # 判断密码和确认密码是否一致
        if password != confirm_password:
            error_msg = '两次输入的密码不一致'
            return render(request, 'account/user_edit.html', {'user': user, 'error_msg': error_msg})

        # 更新用户密码
        user.username = username
        user.set_password(password)
        user.save()

        # 跳转到用户列表页面
        return redirect('user_list')

    return render(request, 'account/user_edit.html', {'user': user})

3、路由:

urlpatterns = [
    # ... 其他 URL 模式 ...
    path('user/edit/<int:pk>/', views.user_edit_view, name='user_edit'),
]

4、user_list.html编辑按钮链接设置:

<td>
   <a class="btn btn-primary btn-xs" href="{% url 'user_edit' user.id %}">编辑</a>
</td>

 

5、效果:

 

posted @ 2023-04-26 13:26  侬侬发  阅读(16)  评论(0编辑  收藏  举报