0

有人可以帮我弄这个吗。我对此很陌生,现在我有点空白。我知道这可能只是一个愚蠢的问题,但老实说我被困住了。

我收到此错误:

异常类型:/building/ 处的 IntegrityError

异常值:solution_building.ID_CUSTOMER_id 可能不为 NULL

我在这里做错了什么

视图.py

class buildingView(UpdateView):
template_name="building.html"
model = building
form_class = buildingForm

def get_context_data(self, **kwargs):
    context = super(buildingView, self).get_context_data(**kwargs)  

    context['pk'] = 1
    context['numberOfObjects'] = building.objects.all().count()
   
    return context

def get_object(self, queryset = None):
    try: 
        obj = building.objects.get(id = 1)
    except: 
        obj = building.objects.create(id = 1)
    return obj

def form_valid(self, form):
    
    form.save()
    return HttpResponseRedirect(reverse("building_view", kwargs={'pk': self.kwargs['pk']}))

当我做 python manage.py sql 我得到了这个

CREATE TABLE "solution_building" (
"id" integer NOT NULL PRIMARY KEY,
"ID_CUSTOMER_id" integer NOT NULL REFERENCES "solution_customer" ("id"),
"BUILDING_USE" varchar(2) NOT NULL,
"BUILDING_FLOORSPACE" integer,

需要帮助。太感谢了。

模型.py

class building(models.Model):
id                   = models.AutoField(primary_key = True)
ID_CUSTOMER          = models.ForeignKey(customer)
BUILDING_USE         = models.CharField(max_length = 2, blank = True, choices = c.Anvendelse)
BUILDING_FLOORSPACE  = models.IntegerField(null = True, blank = True)
def __unicode__(self):
    return '%s' % (self.ID_CUSTOMER)
4

1 回答 1

4

错误来自这里:

def get_object(self, queryset = None):
    try: 
        obj = building.objects.get(id = 1)
    except: 
        obj = building.objects.create(id = 1) <---- here
    return obj

您尝试使用 id 创建新的建筑数据?

根据您的建筑表,ID_CUSTOMER、BUILDING_USE 和 BUILDING_FLOORSPACE 所需的值。因此,当您尝试创建新建筑物时,它会触发错误。

更新:

class building(models.Model):
    #id = models.AutoField(primary_key = True) --> you don't need this, the system automatically create id
    CUSTOMER = models.ForeignKey(customer, null=True, blank=True)
    BUILDING_USE = models.CharField(max_length=2, 
        blank=True, choices=c.Anvendelse, default="base on choices")
    BUILDING_FLOORSPACE  = models.IntegerField(default=0)

    def __unicode__(self):
        return '{0}' % (self)
于 2013-03-13T11:27:06.653 回答