I am trying to add in a manytomany an object but I have a problem because the user in not the request.user and I can't make a get because the info comes from a form..
My code (in the view):
editedcourse = Course.objects.get(id=Course_id)
# Use the model ChangeCourseOwnerForm.
form = ChangeCourseOwnerForm(instance=editedcourse)
# Test if its a POST request.
if request.method == 'POST':
# Assign to form all fields of the POST request.
form = ChangeCourseOwnerForm(request.POST, instance=editedcourse)
if form.is_valid():
# Save the course.
obj = form.save()
newusername = form['owner'] # Return an User
newusername.userprofile.courses_list.add(editecourse)
The problem is in last two lines because the form doesn't have a "userprofile"... All other code is for comprehension but it works.
The model of the form :
class ChangeCourseOwnerForm(forms.ModelForm):
class Meta:
model = Course
fields = ('owner',)
The model of a Course(I am not english, is it ok at singular the world Course?) :
class Course(models.Model):
name = models.CharField(max_length=30)
description = models.TextField(max_length=30)
owner = models.ForeignKey(User, limit_choices_to={'is_staff': True})
years = models.CharField(max_length=11, choices=YEARS_CHOICES,
default='%d - %d' % (date.year, date.year + 1))
# In Admin panel : object = username
def __unicode__(self):
return self.name
Thanks you for your help, hours of work over that make me foolish :D