Django使用表单+当前用户数据保存模型

时间:2018-12-12 14:27:28

标签: python django django-models django-forms django-views

我正在用django编写我的第一个应用程序,但是遇到了问题。我正在尝试建立一个预订系统。我正在尝试保存预订模型。当用户注销时,它可以正常工作。但是,一旦我在登录时单击提交,就什么也没有发生。该网站只是重新加载。谁能指出我做错了什么? 那是我的模型代码:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE)
    name = models.CharField(max_length = 100)
    surname = models.CharField(max_length = 100)
    phone = models.CharField(max_length = 9)

class Reservation(models.Model):
    reservationID = models.AutoField(primary_key = True)
    name = models.CharField(max_length = 100)
    surname = models.CharField(max_length = 100)
    phone = models.CharField(max_length = 9)
    email = models.EmailField()
    bookIn = models.DateField('Book in date', default = timezone.now)
    bookOut = models.DateField('Book out date', default = timezone.now)
    roomType = models.ForeignKey(Room_type, on_delete = models.CASCADE)

我的表单:

class Booking(forms.ModelForm):

class Meta:
    model = Reservation
    fields = ('name', 'surname', 'phone', 'email', 'roomType', 'bookIn', 'bookOut',)
    widgets = {
        'bookIn': forms.DateInput(attrs={'class': 'datepicker'}),
        'bookOut': forms.DateInput(attrs={'class': 'datepicker'})
        }

我的观点:

form = Booking()
if request.method == 'POST':
    form = Booking(request.POST)
    if form.is_valid():
        if request.user.is_authenticated:
            reservation = Reservation()
            guest = Profile.objects.get(user=request.user)
            reservation.name = guest.name
            reservation.surname = guest.surname
            reservation.phone = guest.phone
            reservation.email = guest.user.email
            reservation.bookIn = form.cleaned_data.get('bookIn')
            reservation.bookOut = form.cleaned_data.get('bookOut')
            reservation.roomType = form.cleaned_data.get('roomType')
            reservation.save()

        else:
            reservation = form.save()
            reservation.save()

        n = reservation.pk
        return redirect('bookSuccess', n)
return render(request, 'hotel/bookRoom.html', {'form' : form})

1 个答案:

答案 0 :(得分:0)

我假设您的表格由于某种原因未通过验证,因此您需要抓住它以查看可能出了什么问题。因此,您可以像这样更新视图:

form = Booking(request.POST or None)
if request.method == 'POST':
    if form.is_valid():
        if request.user.is_authenticated:
            reservation = form.save(commit=False)
            # optimized the code
            guest = Profile.objects.get(user=request.user)
            reservation.name = guest.name
            reservation.surname = guest.surname
            reservation.phone = guest.phone
            reservation.email = request.user.email
            reservation.save()
        else:
            reservation = form.save()  # removed duplicate save

        n = reservation.pk
        return redirect('bookSuccess', n)
return render(request, 'hotel/bookRoom.html', {'form' : form})

更新

您无需在模型字段中输入 true 空白 true 。您可以将user数据从视图传递到表单。如果该用户已通过身份验证,则弹出对于已认证用户而言不必要的字段。像这样:

class Booking(forms.ModelForm):

      def __init__(self, *args, **kwargs):
           user = kwargs.pop('user')
           super(Booking, self).__init__(*args, **kwargs)
           if user.is_authenticated:
               self.fields.pop('name')  # or make them required false like this:  self.fields['name'].required = False
               self.fields.pop('surname')
               # other fields unnecessary for authenticated user
      # rest of the code

并在这样的视图中使用此表单:

form = Booking(request.POST or None, user=request.user)