DJANGO表单使用model-manyTomany

时间:2018-07-12 10:41:22

标签: django

我有2张桌子:

  • Roles-idrole_name(值是-{GuestAdminUser
  • SignInView idusernamepasswordrole_id(其中role_id是m2m字段)

当我尝试登录页面时,角色会从数据库中填充到具有多个选择选项的选择框中:

输入用户名,密码并选择2个角色并提交后,提交将提交到“ SignInView”模型表中,但第三列role_id为空。

enter image description here

Forms.Py: 类SignInForm(forms.ModelForm):

role = forms.ModelMultipleChoiceField(queryset=Roles.objects.all(),widget=forms.SelectMultiple)
password=forms.CharField(widget=forms.PasswordInput)
class Meta:
        model=SignInView
        fields = '__all__'

Models.py

类角色(models.Model):

role_name=models.CharField(db_column='role_name', max_length=200) 

class Meta:
    db_table='Roles'

def __str__(self):
    return self.role_name       

SignInView类(models.Model):

username=models.CharField(db_column='username',max_length=200) 
password=models.CharField(db_column='password',max_length=200)
role=models.ManyToManyField(Roles,blank=True)


class Meta:
  db_table='signinview'

views.py

SignInView(TemplateView)类:
     template_name ='signin.html'

 def get(self,request):
    signform=SignInForm()
    return render(request, self.template_name, {'signform':signform})

 def post(self,request):
    if request.method == 'POST':

        signform=SignInForm(request.POST or None)
        if signform.is_valid():
          print(signform.cleaned_data['role'])#value is available

          instance=signform.save(commit=False)
          #instance.save() if this line is uncommented it inserts all values with role_id as null
          for roles in signform.cleaned_data['role']:
           instance.role.add(roles)
           #instance.save()if this line is uncommented getting error
           signform._save_m2m()
        return render(request, self.template_name, {'signform':signform})

    else:
         signform = SignInForm()
         return render(request, self.template_name, {'signform':signform})

请求:

如果我在下拉菜单中选择2个角色,例如[Guest(id = 10,Admin [id = 20]],我需要在SignInView模型中插入2条记录。任何人都可以帮忙。enter image description here

0 个答案:

没有答案