我正在尝试创建一个应用程序,其中我有组织和角色,它们具有多对多的关系,即许多组织中可以存在相同的角色,并且一个组织可以拥有许多角色。为了获得条目,我希望用户填写组织的表单,在那里他定义组织的名称,然后可以选择预先存在的角色,或者添加新的角色。
如果已经存在的那些组织已经不够,那么如何为Role添加新选项?
我有以下型号:
Class Organization(models.Model):
name = models.CharField(max_length=50)
roles = models.ManyToManyField('Role',blank=True)
owner_type = models.ForeignKey(ContentType)
owner_id = models.PositiveIntegerField()
owner = generic.GenericForeignKey('owner_type', 'owner_id')
Class Role(models.Model):
name = models.CharField(max_length=50)
以下是表格:
class OrganizationForm(forms.ModelForm):
class Meta :
model = Context
exclude = ('owner_type','owner_id','owner')
def __init__(self, user=None, *args, **kwargs):
self.user = user # get user here!
super(OrganizationForm, self).__init__(*args, **kwargs)
def save(self,commit = True):
new_org = super(OrganizationForm,self).save(commit=False)
new_org.owner = self.user
if commit:
new_org.save()
return new_org
这是我到目前为止的观点,
def add_organization(request,template_name = "home/editorg.html"):
if request.POST:
form = OrganizationForm(request.user,request.POST)
if form.is_valid():
org = form.save(commit=False)
org.save()
form.save_m2m()
return HttpResponse('Entry made')
else:
form = OrganizationForm()
return render_to_response(template_name,{"form": form })