django形式保存中的完整性错误

时间:2012-05-30 12:57:39

标签: django django-models django-forms

嘿伙计我有我的模特:

class Rule(models.Model):
    Ruleinfo = models.CharField(max_length=5,null=False)
    Ispname  = models.CharField(max_length=5,null=False)
    priority = models.ForeignKey('Priority',related_name ="priority1")
    From  =    models.IPAddressField(null=True)
    To = models.IPAddressField(null=True)
    def __unicode__(self):
        return u'%s %s %s %s %s %s %s %d' % (self.Ruleinfo, self.Ispname, self.priority,
                                      self.From, self.To)


class Priority(models.Model):  
    priority =  models.IntegerField(null = True)
    ispname = models.ForeignKey('Rule' ,related_name="ispname1")
    rule = models.ForeignKey('Rule',related_name="rule1")

这是我的表格

class RuleInfoForm(ModelForm):
     Ruleinfo = forms.CharField(max_length=5)   
     Ispname  = forms.CharField(max_length=5)
     priority = forms.IntegerField()
     From  =       forms.IPAddressField()   
     To    =       forms.IPAddressField()
     class Meta:
        model = Rule
        fields = ("Ruleinfo","Ispname","priority","From","To") 

我将此表单保存在我的视图中,如下所示

def multiwanrule_info(request):
    data = {}
    try:
       form = RuleInfoForm(request.POST)
    except:
        pass
    if form.is_valid():
        rl_frm = form.save(commit=False)
        rl_frm.save()
    else:

        form = RuleInfoForm() 
        data['form'] = form    
    return render_to_response('networking.html',data)

但我得到了完整性错误,即

networking_rule.priority_id may not be NULL

为什么我收到此错误?为什么它不会像其他表一样自动采取

1 个答案:

答案 0 :(得分:1)

你的问题在于:

 rl_frm = form.save(commit=False)
 rl_frm.save()

由于null=True中没有ForeignKey,因此需要有效的外键;你还没有通过这里。

因此,您应将ForeignKey设置为null=True,然后将其分配:

 r1_frm.priority.pk = 1 # some primary key to a valid Priority object
 r1_frm.save()