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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With