overclock
overclock

Reputation: 625

Save empty form field as None in Django

I have a trip model, and the form asks for a outbound flight and an inbound flight, that are both ForeignKeys.

How can I save the inbound flight as None, if no flight is selected and actually allow this form field to be empty.

This is my form:

class NewTrip(ModelForm):

    def __init__(self, *args, **kwargs):
        super(NewTrip, self).__init__(*args, **kwargs)
        self.fields['trip_id'].widget = TextInput(attrs={'class': 'form-control'})
        self.fields['destination'].widget = TextInput(attrs={'class': 'form-control'})
        self.fields['client'].queryset = Clients.objects.all()

    class Meta:
        model = Trip
        fields = ('trip_id', 'destination', 'client', 'out_flight', 'hotel', 'in_flight')

And this is my model:

class Trip(models.Model):
    trip_id = models.CharField(max_length=20, verbose_name="Ref. Viagem")
    destination = models.CharField(max_length=200, null=True, verbose_name='Destino')
    client = models.ForeignKey(Clients, null=True, on_delete=models.CASCADE, verbose_name="Cliente")
    out_flight = models.ForeignKey(Flight, related_name="outbound_flight" ,null=True, on_delete=models.SET_NULL, verbose_name="Voo Ida")
    hotel = models.ForeignKey(Hotels, null=True, on_delete=models.SET_NULL, verbose_name="Hotel")
    in_flight = models.ForeignKey (Flight, related_name="inbound_flight", null=True, on_delete=models.SET_NULL, verbose_name="Voo Regresso")

And this is the view:

def newtrip(request):
    if request.method == 'POST':
        form = NewTrip(request.POST)
        if form.is_valid():
            form.save()
            return redirect('trips')
    else:
        form = NewTrip()
    return render(request, 'backend/new_trip.html', {'form': form})

Upvotes: 0

Views: 368

Answers (1)

Lothric
Lothric

Reputation: 1318

Add blank=True to your in_flight and out_flight

in_flight = models.ForeignKey(..., blank=True)
out_flight = models.ForeignKey(..., blank=True)

Upvotes: 2

Related Questions