Django:用户个人资料更新表单仅显示一个用户的数据

问题描述 投票:0回答:1

我正在使用 Django 构建一个电子商务网站,但在更新用户配置文件时遇到问题。我想显示用户列表并提供一种查看和更新每个用户的个人资料的方法。但是,我目前只能查看和更新已登录用户的个人资料。

这是我当前的实现:

views.py:

def user_list(request):
    users = CustomUser.objects.all()
    return render(request, 'useradmin/user_list.html', {'users': users})



@login_required
def user_profile_update(request):
    try:
        profile = Profile.objects.get(user_name=request.user)
    except Profile.DoesNotExist:
        return render(request, 'useradmin/error.html', {'message': 'Profile does not exist.'})

    if request.method == "POST":
        image = request.FILES.get("image")
        full_name = request.POST.get("full_name")
        phone = request.POST.get("phone")
        Address = request.POST.get("Address")
        diamond_user = request.POST.get("diamond_user")
        golden_user = request.POST.get("golden_user")

        if image:
            profile.image = image

        profile.full_name = full_name
        profile.phone = phone
        profile.Address = Address
        profile.diamond_user = diamond_user == 'on'  # Checkbox values need special handling
        profile.golden_user = golden_user == 'on'

        profile.save()
        messages.success(request, "Profile updated successfully")
        return redirect("useradmin:user_profile_update")

    context = {
        "profile": profile
    }
    return render(request, 'useradmin/userprofile.html', context)

urls.py:

path('user_profile_update/', views.user_profile_update, name='user_profile_update'),
path('user_list/', views.user_list, name='user_list'),

user_list.html:

{% extends 'useradmin/base.html' %}

{% block content %}
  <h1>User List</h1>
  <ul>
    {% for user in users %}
      <li>
        {{ user.email }} ({{ user.first_name }} {{ user.last_name }})
        <a href="{% url 'useradmin:user_profile_update' %}">View/Update</a>
      </li>
    {% empty %}
      <li>No users found.</li>
    {% endfor %}
  </ul>
{% endblock %}

userprofile.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Update Profile</title>
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    /* Optional custom styles */
    .preview-image {
      max-width: 150px;
      height: auto;
    }
  </style>
</head>
<body>
  <div class="container mt-5">
    <div class="card shadow-sm">
      <div class="card-header bg-primary text-white">
        <h2 class="mb-0">Update Profile</h2>
      </div>
      <div class="card-body">
        <form method="POST" enctype="multipart/form-data" id="profileForm">
          {% csrf_token %}
          <div class="mb-3">
            <label for="full_name" class="form-label">Full Name</label>
            <input type="text" class="form-control" id="full_name" name="full_name" value="{{ profile.full_name }}" required>
          </div>
          <div class="mb-3">
            <label for="phone" class="form-label">Phone Number</label>
            <input type="text" class="form-control" id="phone" name="phone" value="{{ profile.phone }}">
          </div>
          <div class="mb-3">
            <label for="Address" class="form-label">Address</label>
            <input type="text" class="form-control" id="Address" name="Address" value="{{ profile.Address }}">
          </div>
          <div class="form-check mb-3">
            <input type="checkbox" class="form-check-input" id="diamond_user" name="diamond_user" {% if profile.diamond_user %}checked{% endif %}>
            <label class="form-check-label" for="diamond_user">Diamond User</label>
          </div>
          <div class="form-check mb-3">
            <input type="checkbox" class="form-check-input" id="golden_user" name="golden_user" {% if profile.golden_user %}checked{% endif %}>
            <label class="form-check-label" for="golden_user">Golden User</label>
          </div>
          <div class="mb-3">
            <label for="profile_picture" class="form-label">Profile Picture</label>
            <input type="file" class="form-control" id="profile_picture" name="image" onchange="previewImage(event)">
            <img id="preview" class="img-thumbnail mt-3 preview-image" src="{% if profile.image %}{{ profile.image.url }}{% endif %}" {% if not profile.image %}style="display: none;"{% endif %} width="150">
          </div>
          <button type="submit" class="btn btn-primary w-100">Update</button>
        </form>
      </div>
    </div>
  </div>
  <!-- Bootstrap JS and dependencies -->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // JavaScript function to preview uploaded image
    function previewImage(event) {
      var preview = document.getElementById('preview');
      var file = event.target.files[0];
      var reader = new FileReader();

      reader.onloadend = function() {
        preview.src = reader.result;
        preview.style.display = 'block'; // Show the preview image
      }

      if (file) {
        reader.readAsDataURL(file); // Read the image file as a data URL
      } else {
        preview.src = "";
        preview.style.display = 'none'; // Hide the preview image if no file selected
      }
    }
  </script>
</body>
</html>

当我导航到

user_profile_update
URL 时,我只能查看和更新已登录用户的个人资料。我想显示用户列表并允许单独更新他们的个人资料。

我尝试过的: 1.更新了

user_profile_update
视图以接受
user_id
。 2.修改URL模式以通过
user_id
。 3.更新了用户列表模板,其中包含每个用户的个人资料更新页面的链接。

预期结果: 当我单击用户列表页面上的“查看”时,我应该被定向到该特定用户的更新表单。

实际结果: 仅显示登录用户的个人资料表单以进行更新。

附加信息: Django 版本:3.x Python版本:3.x 任何其他相关配置或设置

我错过了什么或做错了什么?任何帮助将不胜感激!

python html django django-views django-urls
1个回答
0
投票

问题是您正在 user_profile_update 中读取登录用户

profile = Profile.objects.get(user_name=request.user)

要解决此问题,您应该从 user_list 页面发送用户 id 并在 user_profile_update 中读取该 id。像这样更改您的代码。

在views.py中:

def user_profile_update(request, pk):
    try:
        profile = Profile.objects.get(user_id=pk)

在 urls.py 中:

path('user_profile_update/<int:pk>/', views.user_profile_update, name='user_profile_update'),

在 user_list.html 中:

{% extends 'useradmin/base.html' %}

{% block content %}
  <h1>User List</h1>
  <ul>
    {% for user in users %}
      <li>
        {{ user.email }} ({{ user.first_name }} {{ user.last_name }})
        <a href="{% url 'useradmin:user_profile_update' user.id %}">View/Update</a>
      </li>
    {% empty %}
      <li>No users found.</li>
    {% endfor %}
  </ul>
{% endblock %}
© www.soinside.com 2019 - 2024. All rights reserved.