如何在Django中创建由ManyToManyField创建的Model的实例对象

时间:2017-11-19 20:31:02

标签: python html django html5

我在创建由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'“

enter image description here

2 个答案:

答案 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-createmany2many

答案 1 :(得分:0)

你正在传递activity.id但是试图通过request.post检索
在表单中使用<input type='hidden' name='id' value='{{activity.id}}' />