0

我需要在 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

4

1 回答 1

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")
于 2012-07-13T10:04:41.883 回答