models.py

class Location(models.Model): name = models.CharField(max_length=100, verbose_name=u"Локация", default=u'') country = models.ForeignKey("Country") class Country(models.Model): name = models.CharField(max_length=50, verbose_name=u"Страна") class Photo(models.Model): location = models.ForeignKey(Location, null=True, verbose_name=u'Фото') photo = models.ImageField(upload_to='photos', null=True) 

forms.py

 class LocationForm(forms.ModelForm): class Meta: model = Location fields = ['name', 'country'] photos = MultiFileField(min_num=1, max_num=10) def save(self, commit=True): instance = super(LocationForm, self).save(commit) for each in self.cleaned_data['photos']: Photo.objects.create(photo=each, location=instance) return instance 

views.py

 class AddLocationPageView(CreateView): model = Location form_class = LocationForm template_name = 'add_location.html' class BrowseLocationsPageView(ListView): model = Country context_object_name = 'countries' template_name = "browse_locations.html" 

add_location.html

 <form action="" method="POST">{% csrf_token %} {{ form|crispy }} <button class="btn btn-default" type="submit">Add</button> </form> 

browse_locations.html

 {% for country in countries %} {{ country }} {% endfor %} 

When creating a Location object, the Country form field scolds: "Select a valid choice. That choice is not available."

Of course, I don’t have any choices, since the plan is such that in the absence of a country in the database it should be created at the moment of creating the Location, and if there is (let’s say, someone has already created some location with such a country) - attach to the Location.

Thank!

1 answer 1

An example of a form that will do what you want:

 class LocationForm(forms.ModelForm): country = forms.CharField(max_length=50, label='Country') photos = forms.MultiFileField(min_num=1, max_num=10) class Meta: model = Location fields = ['name',] def save(self, commit=True): country_name = self.cleaned_data['country'] country, created = Country.objects.get_or_create(name=country_name) self.instance.country = country instance = super(LocationForm, self).save(commit) for each in self.cleaned_data['photos']: Photo.objects.create(photo=each, location=instance) return instance