-2

I am new to django, I an updating my userprofile models using forms and view,I need to get the current user who is logged in and I need to update the details for that user

forms.py

class ProfileForm(forms.ModelForm):
    class Meta: 
        model = UserProfile
        fields = ('gender','email_id','mobile_number','date_of_birth')

View.py

def update_UserProfile_views(request):
    if request.method == "POST":
       form = ProfileForm(request.POST)
       if form.is_valid():
          profile = form.save(commit=False)
          profile.save()
    else:
        form = ProfileForm()
    return render(request, 'base.html', {'form': form})
sudeep Krishnan
  • 668
  • 1
  • 6
  • 23

1 Answers1

-1

You can create a instance and get user name

def update_UserProfile_views(request):
    try:
        current_user = request.user
        user = UserProfile.objects.get(user_name=current_user)
    except Exception:
        return render(request, 'base.html', {})
    else:
        if request.method == "POST":
            form = ProfileForm(request.POST,instance=user)
            if form.is_valid():
                profile = form.save(commit=False)
                profile.save()
        else:
            form = ProfileForm()
        return render(request, 'base.html', {'form': form})
sudeep Krishnan
  • 668
  • 1
  • 6
  • 23
  • 1
    OP said "user name", but that isn't what they want. They want the actual UserProfile, which they can just get from `request.user.userprofile` assuming it has a one-to-one relationship with User. – Daniel Roseman Sep 09 '15 at 08:59