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