Django使用ManyToMany Field创建有界形式

时间:2014-10-02 11:19:23

标签: python django django-models

我想用ManytoMany字段创建有界形式

我有像我这样的models.py

from django.db import models
from django.contrib.auth.models import User, Group

class Message(models.Model):
    sender = models.ForeignKey(User, related_name = 'message_sender')
    user_receiver = models.ManyToManyField(User, related_name = 'message_receiver', null = True, blank = True)
    group_receiver = models.ManyToManyField(Group, null = True, blank = True)
    message_content = models.TextField()
    send_time = models.DateTimeField('Scheduled Date & Time',null = True, blank = True)
    MESSAGE_STATUS = (('OUTBOX','Outbox'),('SEND','Send'),('SEEN','Received'))
    status=models.CharField(max_length = 6, choices = MESSAGE_STATUS)

my views.py

def edit_message(request, message_id):
e_message=Message.objects.get(id=message_id)
data={'user_receivers':e_message.user_receiver,
    'group_receivers':e_message.group_receiver,
    'message':e_message.message_content,
    'scheduled_time':e_message.send_time
}
form=ComposeMessageForm(data)
context = {'form':form}
return render(request,'msgin/compose_message.html',context)

我收到错误说

'ManyRelatedManager' object is not iterable

如何使用ManytoMany字段制作有界形式

我想做这样的事情,即替换e_message.user_receiver ...

def edit_message(request, message_id):
e_message=Message.objects.get(id=message_id)
data={'user_receivers':[u'1',u'2'],
    'group_receivers':e_message.group_receiver,
    'message':e_message.message_content,
    'scheduled_time':e_message.send_time
}
form=ComposeMessageForm(data)
context = {'form':form}
return render(request,'msgin/compose_message.html',context)

此处给定列表是该特定message_id的先前选定用户

1 个答案:

答案 0 :(得分:0)

您忘了all()

data = {
    'user_receivers': e_message.user_receiver,
    'group_receivers': e_message.group_receiver.all(),
    'message': e_message.message_content.all(),
    'scheduled_time': e_message.send_time
}