如何在模板中显示两种形式的对象

时间:2018-12-28 14:14:49

标签: django django-models django-forms django-templates django-views

我想使用{{ object.first_name }}显示用户名。我无法显示它。我还在使用User内置模块,其中UserProfile与OneToOneField链接。如果我正在使用{{ p_form.user_image }},则它是显示图像输入字段 profile.html

{% extends "base.html" %}
    {% load crispy_forms_tags %}
    {% block content %}
    <div class="col-md-6 grid-margin stretch-card">
        <div class="card">
          <div class="card-body">
                <h4 class="card-title">Profile Information - {{ object.first_name }}</h4>
            <form class="forms-sample" action="" method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                {{ u_form|crispy }}
                {{ p_form|crispy }}

                <button class="btn btn-success mr-2" type="submit">Update</button>
            </form>
          </div>
        </div>
    </div>
    <ul>
    {% for key, val in object %}
      <li>{{ key }}: {{ val }}</li>
    {% endfor %}
    </ul>
    {% endblock content %}

Views.py

def userProfileUpdate(request, pk):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=User.objects.get(id=pk))
        p_form = UserProfileForm(request.POST, 
                                 request.FILES,
                                 instance=UserProfile.objects.get(user_id=pk))
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, 'Profile Updated!!!')
            return redirect('users')
    else:
        u_form = UserUpdateForm(instance=User.objects.get(id=pk))
        p_form = UserProfileForm(instance=UserProfile.objects.get(user_id=pk))
    context ={
        'u_form': u_form,
        'p_form': p_form
    }

    return render(request, 'users/profile.html', context)

UserProfile模型

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

1 个答案:

答案 0 :(得分:1)

您需要传递object作为上下文。您可以尝试这样:

def userProfileUpdate(request, pk):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=User.objects.get(id=pk))
        p_form = UserProfileForm(request.POST, 
                                 request.FILES,
                                 instance=UserProfile.objects.get(user_id=pk))
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, 'Profile Updated!!!')
            return redirect('users')
    else:
        instance = User.objects.get(id=pk)
        u_form = UserUpdateForm(instance=instance)
        p_form = UserProfileForm(instance=UserProfile.objects.get(user_id=pk))
    context ={
        'object': instance, <-- here
        'u_form': u_form,
        'p_form': p_form
    }

    return render(request, 'users/profile.html', context)

或者,如果用户已登录,则使用{{ user.first_name }}显示名字。