Django表单在ManyToMany字段中保存request.user

时间:2018-06-28 12:25:06

标签: python django django-forms django-views django-class-based-views

我有一个简单的组模型,可以添加用户。

class Group(models.Model):
    name = models.CharField(max_length=50)
    users = models.ManyToManyField(settings.AUTH_USER_MODEL)
    created_by = models.ForeignKey(
             settings.AUTH_USER_MODEL, on_delete=models.CASCADE, 
             related_name='admin_on_group')

    date_created = models.DateTimeField(auto_now_add=True)
    date_modifies = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

我对该小组有一个基本的CreateView。创建组的登录用户将保存在字段created_by中。但是,我也想将相同的登录用户保存在字段users中,以便他可以作为组的普通成员参加。问题是视图最终只能保存已登录的用户,而不会保存从表单字段users传入的其他用户。

例如,如果名为“ george”的用户创建了一个组,则也应将其添加到created_byusers中。截至目前,当我在表单中选择其他用户时,两个字段中仅保存了乔治。

class GroupCreateView(CreateView):

    form_class = GroupForm
    template_name = "groups/group_create.html"

    def form_valid(self, form):
        form = form.save(commit=False)
        form.created_by = self.request.user

        form.save()

        # Apparently you can only add M2M relationships saves after first            
        # saving
        form.users.add(User.objects.get(pk = self.request.user.pk))
        return HttpResponseRedirect(reverse('group_list'))

    def get_form_kwargs(self):
        kwargs = super(GroupCreateView, self).get_form_kwargs()
        kwargs['user'] = self.request.user

        return kwargs

我有一个具有以下轮廓的modelForm。 注意:下面的self.fields['users']中传递的初始数据也不会显示。我还使用了具有phone_number作为USERNAME_FIELD的自定义模型。在self.fields['users']中传递的查询集有效。

class UserModelChoiceField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return obj.get_full_name()


class GroupForm(forms.ModelForm):

    class Meta:
        model = Group
        fields = ('name', 'users', )

    def __init__(self, *args, **kwargs):
        # popping the user from kwargs dictionary that has been 
        # passed in CreateView
        user = kwargs.pop('user', None)

        self.user = user  # setting self.user to be equal to user above

        super(GroupForm, self).__init__(*args, **kwargs)

        self.fields['users'] = UserModelChoiceField(
               queryset=User.objects.exclude(phone_number=str(user)),
               initial=User.objects.get(phone_number=str(user))
        )

1 个答案:

答案 0 :(得分:2)

saved the formcommit=False起,保存实例后,您需要调用表单的save_m2m()方法来保存多对多数据。

def form_valid(self, form):
    instance = form.save(commit=False)
    instance.created_by = self.request.user
    instance.save()
    form.save_m2m()
    # Apparently you can only add M2M relationships saves after first            
    # saving
    instance.users.add(self.request.user)
    return HttpResponseRedirect(reverse('group_list'))

请注意,我已将行更改为instance = form.save(commit=False),以便更清楚地save()返回一个实例,以便您仍然可以访问该表单。