我想编辑一个包含外键的对象。我面临的问题是,不是编辑当前对象,而是创建一个新对象。我认为问题是由外键引起的,因为在没有外键的模型中,我可以编辑它们的对象,而不会出现任何问题。
models.py
class Room(models.Model):
class Meta:
ordering = ['room_number']
room_number = models.PositiveSmallIntegerField(
validators=[MaxValueValidator(1000), MinValueValidator(1)],
primary_key=True
)
ROOM_CATEGORIES = (
('Regular', 'Regular'),
('Executive', 'Executive'),
('Deluxe', 'Deluxe'),
('King', 'King'),
('Queen', 'Queen'),
)
category = models.CharField(max_length=9, choices=ROOM_CATEGORIES)
ROOM_CAPACITY = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
)
capacity = models.PositiveSmallIntegerField(
choices=ROOM_CAPACITY, default=2
)
advance = models.PositiveSmallIntegerField()
room_manager = models.CharField(max_length=30)
class TimeSlot(models.Model):
room = models.ForeignKey(Room, on_delete=models.CASCADE)
available_from = models.TimeField()
available_till = models.TimeField()
views.py
def edit_time_slots(request, pk):
if pk:
try:
time_slot_obj = TimeSlot.objects.get(pk=pk)
except Exception:
return HttpResponse("Bad request.")
else:
return HttpResponse("Bad request.")
if request.method == 'POST':
form = AddTimeSlotForm(request.POST, instance=time_slot_obj)
if form.is_valid():
try:
Room.objects.get(room_number=time_slot_obj.room.room_number, room_manager=request.user.username)
except Exception:
return HttpResponse("Bad request.")
time_slot = TimeSlot(room=time_slot_obj.room,
available_from=request.POST['available_from'],
available_till=request.POST['available_till'])
time_slot.save()
# Implemented Post/Redirect/Get.
return redirect(f'../../view_time_slots/{time_slot_obj.room.room_number}/')
else:
context = {
'form': form,
'username': request.user.username
}
return render(request, 'add_time_slots.html', context)
context = {
'form': AddTimeSlotForm(instance=time_slot_obj),
'username': request.user.username
}
return render(request, 'edit_time_slots.html', context)
1条答案
按热度按时间dfty9e191#
您正在创建新的TimeSlot示例:
请修改现有示例,而不要执行此操作: