models.py

class Location(models.Model): name = models.CharField(max_length=100, verbose_name=u"Локация", default=u'') country = models.CharField(max_length=100, verbose_name=u"Страна", default=u'') 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 %} 

I need to get in the browse_locations.html list of countries without repeating. For example, I add a location object with a US country, then I add another object, also a US country. But in the view I need to see not all the Country objects (which are duplicated), but only one by one.

Thank!!!

  • According to your code, it is not clear how the Country model is generally associated with the Location, maybe there is a ForeignKey? Where do records come from in Country? - Pavel Karateev

1 answer 1

In browse_locations.html you have it all right, there should be no duplicates. You need in the Location model, the country field to make a ForeignKey on the Country model.

 class Location(models.Model): name = models.CharField(max_length=100, verbose_name=u"Локация", default=u'') country = models.ForeignKey(Country, verbose_name=u"Страна") class Country(models.Model): name = models.CharField(max_length=50, verbose_name=u"Страна") 

Also, you will need a separate form to add countries, well, either add through admin panel or sql through them - there are not so many of them.

  • did ... when creating a location, the Country form field gives an error - Select a valid choice. That choice is not one of the available choices. ... Of course, this is no Choice yet because I am just creating a location and creating a country for the first time - Dennis
  • @Denis, I wrote to you above that you will need to create a separate form to fill in the countries. Or through sql fill. - betonimig
  • @Denis, sql insert country: INSERT INTO country (name) VALUES ('Russia'); - betonimig 1:16 pm