0

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

4

1 回答 1

0

It's ok, I have done that :

        newowner = form['owner'].value()
        new = User.objects.get(id=newowner)
        addcourse = new.userprofile.courses_list.add(obj)
于 2012-07-16T08:40:32.270 回答