我有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)
我怎么能这样做?