如何从CharField获取表单字符串值并转换为Django中的对象实例?

时间:2016-06-17 15:43:46

标签: python django django-forms

我一直遇到这个错误:

无法指定“u'Foo群组”:“Team.membership_group”必须是“群组”实例。

在我的Django应用程序中,我为用户提供了创建团队的选项。该团队有一个memebership_group ForeignKey属性,该属性映射到'Group'(django.contrib.auth.models.Group)。在表单中,我已将小部件更改为CharField,以便如果用户键入的组实际上不是组,则我的代码应该创建它。这是我的表格:

class TeamForm(ModelForm):
   """Form to create and modify systems"""

    membership_group = CharField()

    manager = ModelChoiceField(queryset=Manager.objects.all(), required=True)

    class Meta:
        model = Team
        fields = ['name', 'manager', 'membership_group']

在我的视图中(或者我可能需要在其他地方编写代码?),我想获取字符串值并运行get_or_create以返回现有组或创建新组。以下是我的视图中的代码无效:

class TeamCreateView(AutoEventLogMixin, SuccessMessageMixin, PermissionRequiredMixin, CreateView):
    """View to create Teams"""

    form_class = TeamForm
    model = Team
    permission_required = 'teams.add_team'
    success_message = "Team '%(name)s' created successfully."
    template_name = 'teams/team_form.html'

    def form_valid(self, form):

        team_created = super(TeamCreateView, self).form_valid(form)

        team = self.object

        group_name = form.instance.membership_group

        group_name.encode('utf-8')

        membership_group = Group.objects.get_or_create(name=group_name)[0]

        team.membership_group = membership_group

        team.save()

        return team_created

我做错了什么?我需要添加什么代码(以及在哪里)才能将成员资格组值从字符串序列化/反序列化,反之亦然

1 个答案:

答案 0 :(得分:0)

我认为无论如何在form_valid中进行类型翻译并不是一个好主意。如果您使用django1.9,请考虑创建自定义FormField

from django import forms

class MyGroupField(forms.Field):
    def to_python(self, group_name):
        return Group.objects.get_or_create(name=group_name)[0]

class TeamForm(ModelForm):
    membership_group = MyGroupField()