【问题标题】:How can I update the details of current user using forms and views如何使用表单和视图更新当前用户的详细信息
【发布时间】:2023-03-27 17:42:01
【问题描述】:

我是 django 新手,我正在使用表单和视图更新我的用户配置文件模型,我需要获取当前登录的用户,我需要更新该用户的详细信息

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

【问题讨论】:

标签: python django django-forms django-views


【解决方案1】:

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

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

【讨论】:

  • OP 说“用户名”,但这不是他们想要的。他们想要实际的 UserProfile,他们可以从 request.user.userprofile 获得,假设它与 User 具有一对一的关系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多