Chained dropdown validation error. Form works

150 views Asked by At

Creating a chained drop down following a tutorial. Everything works fine but it is throwing an unnecessary validation error.

It is a basic 3 field form creating a person object with name, country and city.

Views.py

from django.shortcuts import render, redirect, get_object_or_404
from .forms import CustomerForm

from .forms import PersonCreationForm
from .models import Person, City



def store(request):
    form = CustomerForm()
    context = {'form': form}
    return render(request, 'store/store.html', context)

def cart(request):
    form = CustomerForm()
    context = {'form': form}
    return render (request, 'store/cart.html', context)    

def checkout(request):
    form = CustomerForm()
    context = {'form': form}
    return render(request, 'store/checkout.html', context)

def signup(request):
    context = {}
    return render(request, 'store/signup.html', context)  





def home(request):
    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            pass  # does nothing, just trigger the validation
    else:
        form = CustomerForm()
    return render(request, 'shop.html', {'form': form}) 


def person_create_view(request):
    form = PersonCreationForm()
    if request.method =='POST':
        form = PersonCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('person_add')
    return render(request, 'store/ho.html', {'form': form})      

def person_update_view(request, pk):
    person = get_object_or_404(Person, pk = pk)
    form = PersonCreationForm(instance = person)
    if request.method == 'POST':
        form = PersonCreationForm(request.POST, instance=person)
        if form.is_valid():
            form.save()
            return redirect('person_change', pk = pk)
        return render(request, 'store/ho.html', {'form': form})  


#ajax

def load_cities(request):
    country_id = request.GET.get('country_id')
    cities = City.objects.filter(country_id = country_id)
    return render(request, 'store/city_dropdown_list_options.html',{'cities':cities})

Forms.py

from django.forms import ModelForm
from .models import Customer, Person, City
from django import forms

class CustomerForm(ModelForm):
    class Meta:
        model = Customer
        fields = '__all__'


class PersonCreationForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['city'].queryset = City.objects.none()

        if 'country' in self.data:
            try:
                country_id = int(self.data.get('country'))
                self.fields['city'].queryset = City.objects.filter(country_id = country_id)
            except(ValueError, TypeError):
                pass
        elif self.instance.pk:
            self.fields['city'].queryset = self.instance.country.city_set.order_by('name')   

In forms.py line 14 where it says-

self.fields['city'].queryset = City.objects.none()

this line is throwing a validation error when I try to submit the form. In the tutorial they add the if/else argument and that solves the problem and error goes away.

error: "Select a valid choice. That choice is not one of the available choices"

In my case the error still shows up. If I ignore it and re select the city and submit, it works just fine.

It is almost like having a pause at that line and the system suddenly realizes that there is more code.

How do I fix this problem. Appreciate any help.

0

There are 0 answers