如何从 Django 中的表单请求现有文件

How to request existing files from a form in django

我正在尝试为用户添加一个功能来更新他们的个人资料,但我希望能够获得他们现有的信息,这样他们就不必再次填写所有表格。我已在表单上尝试 request.POST 但它不起作用,它不会使用现有用户信息更新表单。

views.py

def profile_update(request):
    info = Announcements.objects.all()
    categories = Category.objects.all()

    Profile.objects.get_or_create(user=request.user)
    if request.method == "POST":
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        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('userauths:profile')
    else:
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
    
    context = {
        'u_form': u_form,
        'p_form': p_form,
        'info': info,
        'categories': categories
    }

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





# profile update function
def profile_update(request):
    info = Announcements.objects.all()
    categories = Category.objects.all()

    Profile.objects.get_or_create(user=request.user)
    if request.method == "POST":
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        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('userauths:profile')
    else:
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
    
    context = {
        'u_form': u_form,
        'p_form': p_form,
        'info': info,
        'categories': categories
    }

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


您可以使用 {{form.instance}} 访问与您的表单关联的模型实例。

{{p_form.instance.first_name}}</pre>

编辑:

这里在保存 ProfileUpdateForm 时您没有处理字段用户,因此您可以像这样在您的个人资料表单中处理用户。

 if u_form.is_valid() and p_form.is_valid():
     user = u_form.save()        
     profile = p_form.save(commit=False)
     profile.user = user
     profile.save()