我在创建由ManyToManyField创建的模型实例时遇到了困难。
这就是我在models.py中的内容:
class Attendee(models.Model):
student = models.ForeignKey(User, related_name="attendee")
class Activity(models.Model):
attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True)
我在views.py中尝试过这个功能,但它不起作用:
def registerAttende(request,pk):
act = Activity.objects.get(pk=pk)
act.save()
act.attendee.add(student=request.user.pk) # This is the line causing the error
return render(request, 'dashboard.html')
我收到以下错误:
“/ 5的TypeError” add()得到了一个意外的关键字参数'student'“
答案 0 :(得分:1)
许多人尝试它:
def registerAttende(request,pk):
act = Activity.objects.get(pk=pk)
act.save()
# Get Attendee or create it, in the '_' boolvalue created, don need now
attendee, _ = Attendee.objects.get_or_create(student=request.user)
act.attendee.add(attendee)
return render(request, 'dashboard.html')
有关详细信息,请参阅get-or-create和many2many
答案 1 :(得分:0)
你正在传递activity.id但是试图通过request.post检索
在表单中使用<input type='hidden' name='id' value='{{activity.id}}' />