gpt4 book ai didi

django IntegrityError(1048, "Column ' hotel_id'不能为空”)

转载 作者:行者123 更新时间:2023-12-02 05:41:03 24 4
gpt4 key购买 nike

我是新人,这是我在这个平台上的第一个问题。我尝试使用 modelform 添加新房间,但收到 IntegrityError(1048,“Column 'hotel_id' 不能为空”)。我的代码如下。我很感谢您的帮助

模型.py

class Hotel(models.Model):
name = models.CharField("Hotel Name", max_length=100)
owner = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)

class Meta:
verbose_name_plural = "Hotels"

def __str__(self):
return self.name

class Rooms(models.Model):
room_type = models.CharField(max_length=100)
price = MoneyField(max_digits=65, decimal_places=2, default_currency='USD')
number_available = models.IntegerField()
hotel = models.ForeignKey(Hotel,on_delete=models.CASCADE)
# hotel = models.ForeignKey("Hotel", on_delete=models.CASCADE)

class Meta:
verbose_name_plural = "Rooms"

def __str__(self):
return self.room_type

views.py

这是处理表单的 View 部分

def new_room(request):

if request.method=='POST':
# hotel = get_object_or_404(Hotel,id =hotel_id)
user = request.user
if user:
form=RoomsForm(request.POST or None)
if form.is_valid():
newroom = form.save(commit=False)
newroom.owner = request.user
newroom.save()
return HttpResponseRedirect('/')
else:
form = RoomsForm(request.POST or None)
return render(request,'newroom_form.html', {"form":form})

forms.py

class RoomsForm(forms.ModelForm):
class Meta:
model = Rooms
fields =['room_type','price','number_available']

提前谢谢

最佳答案

RoomsForm 不包含 hotel 字段,因此 newroom.hotel 未填充。当您 save() 实例 Postgres 提示缺少值 (ForeignKey defaults to null=False )。

由于您可能不想允许未知酒店的房间,因此您需要在表单中包含酒店选择或在网址中包含酒店 ID(例如 /hotel/123/new-room/) 并手动设置 newroom.hotel

关于django IntegrityError(1048, "Column ' hotel_id'不能为空”),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50150292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com