class City(models.Model):
city_name = models.CharField(max_length=100,null=True,blank=False)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
class Event(models.Model):
...
venue_city = models.ForeignKey('cities_light.City', on_delete=models.SET_NULL, null=True, blank=False)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
...
from django import forms
from django.forms import ModelForm
from cities_light.models import Country,City
from .models import Event
from django_select2 import forms as s2forms
from django_select2.forms import ModelSelect2TagWidget
from .models import City as CityModel
class CityWidget(s2forms.ModelSelect2TagWidget):
search_fields = [
'name__istartswith'
]
class EventForm(forms.ModelForm):
class Meta:
model = Event
exclude = ['creator','artist', 'id']
widgets = {
'venue_city':CityWidget,
...
}
....
def clean_venue_city(self):
city_input = self.cleaned_data['venue_city'].strip()
city = Event.objects.filter(venue_city__iexact=city_input).first()
if city:
return city
else:
city_not_match = CityModel.objects.filter(city_name__iexact=city_input).first()
if city_not_match:
return city_not_match
else:
new_city = CityModel.objects.create(city_name=city_input)
return new_city
def save(self, commit=True):
event = super().save(commit=False)
event.venue_city = self.cleaned_data['venue_city']
if commit:
event.save()
return event
i ommited some things related to styling which are not important for question. Long story short:
i have one input field venue city: first i want to check whether there exist this field in data base (django-cities-light), however, if that is not case, i want to have possibility to input my own data.
However, because one to many relationship in event model of city during validation of form, i get an error:
“Select a valid choice. That choice is not one of the available choices.”
which is expected. I tried to avoid this by simply trying to input in another table, but it is not possbile to for form to handle two tables (models) data. Does anyone have idea how i could handle this problem? Any reference to similar problem would be huge help. Thanks in advance.
Andrija.