有人可以帮我解决这个问题。我对此很陌生,现在我有点空白。我知道也许这只是一个愚蠢的问题但老实说我被卡住了。
我收到此错误:
异常类型:/ building /
中的IntegrityError异常值:solution_building.ID_CUSTOMER_id可能不是NULL
我在这里做错了什么
views.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,
需要帮助。非常感谢你。
model.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)
答案 0 :(得分: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)