django - 如何在更新时自动填充 django 表单中的现有数据

django - How to auto-populate existing data in django form while updating

我想用现有数据在 Django 中自动填充我的更新表单,但是 instance=request.userinstance=request.user.profile 似乎不会自动填充表单

views.py

def UserProfile(request, username):
    # user_profiles = Profile.objects.all()
    user = get_object_or_404(User, username=username)
    profile = Profile.objects.get(user=user)
    url_name = resolve(request.path).url_name

    context = {
        'profile':profile,
        'url_name':url_name,
    }

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





@login_required
def profile_update(request):
    info = Announcements.objects.filter(active=True)
    categories = Category.objects.all()
    user = request.user
    profile = get_object_or_404(Profile, user=user)

    if request.method == "POST":
        u_form = UserUpdateForm(request.POST, instance=request)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile.user)
        if u_form.is_valid() and p_form.is_valid():

            u_form.save()
            p_form.save()
           
            messages.success(request, f'Acount Updated Successfully!')
            return redirect('profile', profile.user.username)
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)
    
    context = {
        'u_form': u_form,
        'p_form': p_form,
    }
    return render(request, 'userauths/profile_update.html', context)

我终于明白了,你需要的是确保在 request.user 中传递 request.user.profile 在 else 中:这表明表单是一个 GET 请求