简体   繁体   中英

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

I want to auto populate my update form in django with the existing data, but instance=request.user and instance=request.user.profile seems not to be auto populating the form

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)

I finnaly figured it out, what you need to is make sure to pass in request.user and also request.user.profile in the else: that shows that the forms is a GET request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM