我有两个模型,区域和房间。一个房间只能在一个区域,但一个区域可以有多个房间。当用户创建一个房间(createRoom视图)时,我希望他们输入一个区域,这既应该更新区域模型,也应该将该区域分配给房间。
models.py
class Region(models.Model):
region = models.CharField(max_length=200, unique=True)
etc....
class Room(models.Model):
region = models.ForeignKey(Region, on_delete=models.SET_NULL, null=True)
etc....
forms.py
class RoomForm(ModelForm):
class Meta:
model = Room
fields = ['region', etc....]
class RegionForm(ModelForm):
class Meta:
model=Region
fields = ['country', 'region']
views.py
def createRoom(request):
form_room = RoomForm()
form_region = RegionForm()
if request.method == 'POST':
form_room = RoomForm(request.POST)
form_region = RegionForm(request.POST)
if form_room.is_valid() and form_region.is_valid():
room = form_room.save(commit=False)
region = form_region.save(commit=False)
room.region = region.region
room.save()
region.save()
return redirect ('home')
template.html
<form class="form" action="" method="POST">
{% csrf_token %}
{{form_room.media}}
<div class="form__group">
<label for="region_name">Region</label>
{{form_region.region}}
</div>
</form>
行房间。region = region.region在views.py中,我希望将region模型的区域对象设置为Room模型的区域对象。我在提交表单时没有收到任何错误。但是Room模型的区域对象仍然为空。
我更新了我的视图来检查错误,错误似乎是表单无效:
def createRoom(request):
form_room = RoomForm()
form_region = RegionForm()
if request.method == 'POST':
form_room = RoomForm(request.POST)
form_region = RegionForm(request.POST)
if form_room.is_valid() and form_region.is_valid():
room = form_room.save(commit=False)
region = form_region.save(commit=False)
room.host = request.user
room.region = region.region.pk
region.save()
room.save()
#return redirect ('home')
else:
messages.error(request, 'form not valid')
我假设既然您在一个表单中创建了两个模型,那么顺序在这里起了很大的作用。当此模型实例不存在时,您正试图用ForeignKey
region
保存room
。尝试交换顺序:
region.save()
room.save()
这样,您首先保存Region
,然后Room
中的数据不是空的。还可以尝试使用try except:
来更好地处理错误。最后请记住,ForeignKey
需要key
所以你可能需要设置
room.region = region.pk