在请求后在列表中添加Manytomany项

时间:2012-07-13 10:00:32

标签: django many-to-many

我需要在ManyToMany字段中自动添加。我的班级:

class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='student')
courses_list = models.ManyToManyField(Course, blank=True)

保存新课程后,我想将其添加到用户的course_list中:

def newcourse(request):
if not request.user.is_authenticated():
    return render_to_response('login.html')
form = CourseForm()
if request.method == 'POST':
    form = CourseForm(request.POST)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.owner = request.user
        obj = form.save()
        course_list = request.user.userprofile.courses_list.all()
        course_list += form
        course_list.save()
        return render(request, 'mycourses.html')
return render(request, 'newcourse.html', locals())

但它不起作用:`+ =不支持的操作数类型:'ManyRelatedManager'和'CourseForm'``

也许我需要提出新的要求?

如果您有任何想法..:D

1 个答案:

答案 0 :(得分:2)

您需要执行以下操作:

request.user.userprofile.courses_list.add(obj)

有关更多详细信息,请参阅有关ManyToMany关系的文档:

https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

当然,您应该以“正确”的方式处理个人资料:

try:
    profile = request.user.get_profile()
    profile.courses_list.add(obj)
except UserProfile.DoesNotExist:
    messages.error(request, "Couldn't find profile")