Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble saving Django form: 'UserProfile' object has no attribute 'save_m2m'

Tags:

python

django

I have a Django form where I'm trying to save user profile details. My UserProfile has a many to many field, which I'm having trouble saving. Here is my attempted view code:

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

On a POST, once the form is validated I'm able to save the basic object but afterwards saving the many to many fields fails with the given exception. What is the right way to go about this?

like image 309
Jim Avatar asked Dec 07 '22 01:12

Jim


1 Answers

Example:

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

E:

Try this:

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()
like image 132
Silwest Avatar answered Dec 08 '22 14:12

Silwest