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

8fq7wneg  于 2023-02-10  发布在  Go
关注(0)|答案(1)|浏览(146)

我想在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)
ogq8wdun

ogq8wdun1#

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

代码示例

def profile_update(request):
    profile = Profile.objects.get(user=request.user)
    if request.method == "POST":
        form = ProfileForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            new_form = form.save(commit=False)
            new_form.user = request.user
            new_form.save()
            messages.success(request, "Profile Updated Successfully.")
            return redirect("core:dashboard")
    else:
        form = ProfileForm(instance=profile)

    context = {
        "form": form,
        "profile": profile,
    }

    return render(request, "userauths/profile-edit.html", context)

首先获取您要尝试更新的模型的示例,然后在request.POST将传递到输入字段的数据的行中添加instance=model_instance_you_are_trying_to_update在我的示例中,它是配置文件,所以我使用了instance=Profile,假设您的是一篇博客文章
1.获取博客文章

post = Posts.object.get(id=id)
postUpdateForm(request.POST, instance=post) # the instance=post would the existing fields

相关问题