Django:从表单提交中保存ManyToManyField属性

时间:2017-07-24 19:07:27

标签: python django

我有这样的观点:

def view(request, ...):
    user = request.user
    company = get_object_or_404(Company, ...)
    group = get_object_or_404(Group, ...) 
    form = TaskCreateForm()
    if request.method == 'POST':
        print(company)
        print(group)
        form = TaskCreateForm(data=request.POST)
        if form.is_valid():
            form.save(commit=False)
            form.creator = user
            form.company = company
            form.group = group
            # So these above attributes aren't actually inputs in the form, but just data passed to the model from things like the user that's sending off the form and the group they're in for example
            form.save()

创作者(用户)和公司通过ForeignKey与此特定模型相关联(任务,用户填写表格)。

问题出在我写form.group = group的地方,我怀疑这可能是因为该组与任务模型有一个ManyToMany关系。

我想要'组'成为与此Task对象相关的众多Group对象之一。

尝试保存表单时发生错误,如下所示:

  

/ error / task / 625377380359841 /中的TypeError   强制转换为Unicode:需要   字符串或缓冲区,找到NoneType

这将是一个很好的帮助,谢谢!

编辑: 我还看了一下save_m2m()方法,我认为这可能是相关的,但不幸的是,这似乎没有帮助。

此外,这里有与TaskCreateForm()相关的表单和模型代码...... forms.py:

class TaskCreateForm(forms.ModelForm):
    task_name = forms.CharField(widget=forms.widgets.TextInput(attrs={
    'placeholder':'Activity name'}), label='Activity', required=True, min_length=3, max_length=60)
    task_priority = forms.ChoiceField(choices=PRIORITY, widget=forms.widgets.Select
    (attrs={'placeholder':'Priority'}), label='Importance', required=False)
    class Meta:
        model = Activity
        fields = ['task_name', 'task_priority']

models.py:

class Task(models.Model):
    company = models.ForeignKey(Company, related_name='company_activity',
        verbose_name='Parent Company', on_delete=models.CASCADE, null=True)
    group = models.ManyToManyField(Group, related_name='group_activity',
        verbose_name='Related Group', blank=True)
    creator = models.ForeignKey(AUTH_USER_MODEL, related_name='activity_creator',
        verbose_name='Created by User', null=True)
    task_name = models.CharField(max_length=40, verbose_name='Task')
    task priority = models.CharField(max_length=18, verbose_name='Priority',
        choices=PRIORITY, blank=True, null=True)
    task_slug = models.SlugField(verbose_name='Slug', unique=True, blank=True, null=True)
    class Meta:
        verbose_name = 'Task'

    def __unicode__(self):
        return self.task_slug

    def __str__(self):
        return self.task_slug

    def get_absolute_url(self):
        return reverse('task-detail', kwargs={'task_slug': self.task_slug, 'co_dom': self.company.domain})

    def save(self, *args, **kwargs):
        task_slug(self)
        super(Task, self).save(*args, **kwargs)

完整追溯:

  

905093298449 |公司625377380359841内部服务器错误:   /公司/ sourceup /机遇/ 625377380359841 /   Traceback(最近一次调用最后一次):文件   " /Library/Python/2.7/site-packages/Django-1.10.2-py2.7.egg/django/core/handlers/exception.py" ;,   第39行,在内部       response = get_response(request)File" /Library/Python/2.7/site-packages/Django-1.10.2-py2.7.egg/django/core/handlers/base.py",   第187行,在_get_response中       response = self.process_exception_by_middleware(e,request)File" /Library/Python/2.7/site-packages/Django-1.10.2-py2.7.egg/django/core/handlers/base.py" ,   第185行,在_get_response中       response = wrapped_callback(request,* callback_args,** callback_kwargs)file" /Users/jayt/grid/company/views.py" ;,第181行,在task_detail中       act.parent_op.add(opportunity)File" /Library/Python/2.7/site-packages/Django-1.10.2-py2.7.egg/django/db/models/fields/related_descriptors.py" ,   第476行,获取       return self.related_manager_cls(instance)File" /Library/Python/2.7/site-packages/Django-1.10.2-py2.7.egg/django/db/models/fields/related_descriptors.py",   第783行,在 init 中       (例如,self.source_field_name))文件" /Library/Python/2.7/site-packages/Django-1.10.2-py2.7.egg/django/db/models/base.py",   第572行, repr       u = six.text_type(self)TypeError:强制转换为Unicode:需要字符串或缓冲区,找到NoneType [25 / Jul / 2017 17:42:51]" POST   / company / task / 625377380359841 / HTTP / 1.1" 500 81361

2 个答案:

答案 0 :(得分:2)

当您尝试添加add字段数据时,应使用manytomany方法。

form.group.add(group)
form.save()

答案 1 :(得分:0)

form.save(commit=False)行中,它将返回未保存的Task对象(假设Task是基于表单名称的模型)。

然后,您可以在保存之前直接操作Task对象。现在你正在操纵表格,我不相信你想要的。

所以你最终得到:

task = form.save(commit=False)
task.creator = user
task.company = company
task.group.add(group)
task.save()