在CreateView中保存另一个模型的对象

时间:2016-09-13 07:53:14

标签: django

我有3个型号:

class City(models.Model):
    name = models.CharField()


class State(models.Model):
    name = models.CharField()


class Role(models.Model):
    CITY = 1
    State = 2

    NOACCESS = 0
    VIEW = 1
    UPDATE = 2
    DELETE = 3

    TYPE_CHOICES = (
        (CITY, 'City'),
        (STATE, 'State'),
    )

    ROLE_CHOICES = (
        (NOACCESS, 'No access'),
        (VIEW, 'View'),
        (UPDATE, 'Update'),
        (DELETE, 'Delete'),
    )

    obj_type = models.IntegerField(choices=TYPE_CHOICES)
    obj_id = models.IntegerField(verbose_name="Object ID")
    obj_role = models.IntegerField(choices=ROLE_CHOICES, default=NOACCESS)
    obj_user = models.IntegerField()

我想在views.py中为每个用户保存一个角色:

class FormCreateView(CreateView):
    form_class = City

    def form_valid(self, form):
        users = self.request.POST.getlist('access-users')
        f.save()

        for i in users:
            role = RoleCreateView() # save a role for each user
            role.type = 'city'
            role.user = i
            role.city = f.id

            role.save()

        return super(FormCreateView, self).form_valid(form)

我怎么能这样做?

0 个答案:

没有答案