如何使用表单和视图更新当前用户的详细信息

时间:2015-09-09 08:46:23

标签: python django django-forms django-views

我是django的新手,我使用表单和视图更新了我的userprofile模型,我需要获取当前登录的用户,我需要更新该用户的详细信息

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})

1 个答案:

答案 0 :(得分:0)

您可以创建实例并获取用户名

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})