无法保存Django表单:'UserProfile'对象没有属性'save_m2m'

时间:2014-06-22 14:55:50

标签: python django

我有一个Django表单,我试图保存用户个人资料详细信息。我的UserProfile有多个字段,我很难保存。这是我尝试过的视图代码:

@login_required
def updateProfile(request, uid):
    import pdb; pdb.set_trace()

    """
    First, grab the existing user data out of the db.
    If it's not there, we'll create it, then fill in the blanks from user input on post.
    """
    requested_user = get_object_or_404(User, pk=uid)
    user_profile = None
    try:
        user_profile = UserProfile.objects.get(user = requested_user)
    except UserProfile.DoesNotExist:
        default_skill_level = SkillLevel.objects.all()[0] # default value.
        user_profile = UserProfile(user = requested_user, skill_level = default_skill_level)
        user_profile.save()

    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance = user_profile)

        if form.is_valid() and (request.user.id == uid or request.user.is_superuser):
            obj = form.save(commit=False) # get just the object but don't commit it yet.
            obj.save() # finally save it.
            obj.save_m2m() # this is failing. UserProfile has no attribute save_m2m
            return index(request)
        else:
            print "Not authorized to do that! Implement real authorization someday."
            return index(request)

    else:
        profile_form = UserProfileForm(instance=user_profile)
        context = {
            'user' : request.user,
            'form' : profile_form
        }
        return render(request, 'booker/profile.html', context)

在POST上,一旦表单被验证,我就可以保存基本对象,但之后保存了多个到多个字段,但是出现了给定的异常。什么是正确的方法?

2 个答案:

答案 0 :(得分:7)

示例:

...
if formset.is_valid():
   items = formset.save(commit=False)
      for item in items:
          item.save()
      formset.save_m2m()

E:

试试这个:

if form.is_valid() and (request.user.id == uid or request.user.is_superuser):
   obj = form.save(commit=False) # get just the object but don't commit it yet.
   obj.save() # finally save it.
   form.save_m2m()

答案 1 :(得分:2)

只有先前使用commit = False保存时才需要save_m2m()。在您的示例中,似乎没有必要提交commit = False。

E.g。你可以替换

obj = form.save(commit=False) # get just the object but don't commit it yet.
obj.save() # finally save it.
obj.save_m2m() # this is failing. UserProfile has no attribute save_m2m

使用:

form.save()