Django - 表单字段不通过验证

时间:2016-06-02 11:33:31

标签: django django-forms

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 %}

创建位置对象时,表单字段显示:“选择一个有效的选项。该选项不是可用选项之一。”

当然,我没有任何选择,因为设计是 - 如果DB中没有Country,则必须在Location创建期间创建,而在相反的情况下(Country在DB中,因为有人在之前创建它)他正在创建位置)它必须加入位置。

0 个答案:

没有答案