无法在Django中编辑具有外键的对象

3pvhb19x  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(135)

我想编辑一个包含外键的对象。我面临的问题是,不是编辑当前对象,而是创建一个新对象。我认为问题是由外键引起的,因为在没有外键的模型中,我可以编辑它们的对象,而不会出现任何问题。
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)

Link to GitHub repo

dfty9e19

dfty9e191#

您正在创建新的TimeSlot示例:

time_slot = TimeSlot(room=time_slot_obj.room,
                    available_from=request.POST['available_from'],
                    available_till=request.POST['available_till'])

请修改现有示例,而不要执行此操作:

time_slot_obj.available_from = ...
time_slot_obj.available_till = ...
time_slot_obj.save()

相关问题