如何使用m2m字段,字符串+ manytomanyfield制作form.cleaned_data []?-Django

时间:2018-06-28 03:16:16

标签: django forms sendmessage manytomanyfield m2m

我将教师的CharField更改为ManyToManyField,现在我的UserMessage和EmailMessage已损坏,

模型如下:

class UserMessage(models.Model):
    user = models.ManyToManyField(User,related_name="recipent")
    send_user = models.ForeignKey(Use,null=True, blank=True, on_delete=models.SET_NULL, related_name="sender")
    message = models.CharField(max_length=500)
    test_name =models.CharField(max_length=800, default='', blank=True)
    test_date = models.DateField(default=datetime.now)
    test_time = models.TimeField(default=datetime.now)

    `# when teacher is not ManyToManyField, the EmailMessage of body works well with test.teacher.user`
    teacher = models.ManyToManyField(User, related_name="+") 

test.teacher.username用于CharField,如何定义ManyToManyField?

body="Name of test:" + test.name  + ",Date :" + str(test.date) + ",Time:" + str(test.time) + ", Teachers:" + test.teacher.username

以及如下所示的UserMessage的部分views.py(不是完整代码),UserMessage的功能运行良好,但是我想知道如何将form.cleaned_data['teacher'].username更改为ManyToManyFiled吗?我的意思是不是form.cleaned_data['teacher.set()']或其他任何东西,非常感谢您的任何建议。

user_message.test_name = form.cleaned_data['name']
user_message.teacher = form.cleaned_data['teacher'].username
user_message.test_time = form.cleaned_data['time']
user_message.test_date = form.cleaned_data['date']

1 个答案:

答案 0 :(得分:0)

要设置外键而不是其字段之一时,必须分配User实例。假设老师是一个用户对象,您可以使用类似的

for user_teacher in form.cleaned_data['teacher']:
    user_message.teacher.add(user_teacher)

如果您没有传递用户实例(仅说一个用户名),您将不得不以某种方式选择相关的教师,然后添加m2m关系,例如

user_teacher = get_object_or_404(get_user_model(), username=form.cleaned_data['teacher'])
user_message.teacher.add(user_teacher)

在您的用户名唯一的情况下可以使用。