1

嘿伙计们,我有我的模型:

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

为什么我收到此错误?为什么它不像其他桌子那样自动采取

4

1 回答 1

1

你的问题出在这里:

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

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

所以你应该设置ForeignKeyto null=True,然后可能分配它:

 r1_frm.priority.pk = 1 # some primary key to a valid Priority object
 r1_frm.save()
于 2012-05-30T16:36:41.223 回答