django表单验证不起作用,为什么?

时间:2017-03-02 19:56:03

标签: django django-forms

这是我在django的第一个项目,我找不到问题, 问题:即使表单无效,也要提交按钮 另一种形式.is_valid()工作得非常好,

也许不行,因为一个POST发送2个不同的模型,可以是真的吗?

来自:http://www.joshuakehn.com/2013/7/18/multiple-django-forms-in-one-form.html的想法 有什么想法来解决问题吗?

views.py

[...]
def reservation_view(request, pk):
    bus = get_object_or_404(Bus, pk=pk)

    form_client = ClientForm(prefix='cl')
    form_var = ReservationForm(prefix='res')

    if request.method == "POST":

        form_client = ClientForm(request.POST,prefix='cl')
        form_var = ReservationForm(request.POST,prefix='res')

        if form_var.is_valid() and form_client.is_valid():
            newreservation = form_var.save(commit=False)
            newreservation.reBusID = bus
            newreservation.reClientID = form_client.save()       #can be changed i future if the same client
            newreservation.reDate = timezone.now() #not in use right now
            newreservation.save()
        buses = Bus.objects.filter(available_for_cutomers=True)    #to dispaly next site if form is valid
        return render(request, 'busreserv/client.html', {'buses' : buses})
    else:
        form_var = ReservationForm()
        form_client = ClientForm()
        return render(request, 'busreserv/newreservation.html', {'formReservation' : form_var, 'bus':bus , 'form_client':form_client})

models.py

class Bus(models.Model): # Base model of Bus

    description = models.CharField(max_length=200)
    brand = models.CharField(max_length=150)
    plate_nr = models.CharField(max_length=10)
    people_capacity = models.IntegerField()
    price_per_km = models.DecimalField(max_digits=5, decimal_places=2)
    available_for_cutomers = models.BooleanField(default=True)

    def __str__(self):
        return self.plate_nr


class Client(models.Model):
    firstName = models.CharField(max_length=15)
    lastName = models.CharField(max_length=15)
    clientEmail = models.CharField(max_length=15)
    clientPhone = models.CharField(max_length=15)

    def __str__(self):
        return self.lastName



class Reservation(models.Model):
    reBusID = models.ForeignKey( 'Bus',blank=True, null=True)
    reClientID = models.ForeignKey( 'Client',blank=True, null=True)
    reDate = models.DateTimeField(blank=True, null=True) #not used yet
    km = models.IntegerField()
    details = models.CharField(max_length=200)

    def __str__(self):
        return self.details

html的

<form method="POST" class="post-form">{% csrf_token %}

    {{ form_client.as_p }}
    {{ formReservation.as_p }}

    <button type="submit" class="btn btn-primary btn-md">Book it</button>
</form>

0 个答案:

没有答案