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

时间:2018-05-03 08:23:50

标签: django python-3.x django-forms modelform

我是新手,这是我在这个平台上的第一个问题。我正在尝试使用modelform添加新房间,但我收到了IntegrityError(1048," Column' hotel_id'不能为null")。我的代码如下。我很感激帮助

models.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

以下是处理表单

的视图部分
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']

提前谢谢

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

我可以使用以下代码获取酒店ID

def new_room(request):
if request.method == 'POST':
    form = RoomsForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        rooms = Rooms.objects.filter(hotel__owner=request.user)
        for r in rooms:
            instance.hotel_id = r.hotel_id
        instance.user = request.user
        instance.save()
        return HttpResponseRedirect('/dashboard')
else:
    form = RoomsForm()
return render(request, 'newroom_form.html', {"form": form})