2016-05-17 82 views
0

我需要你這樣的問題的幫助:Django的 - 當時上傳多張圖像

這是我的models.py:

class Location(models.Model): 
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) 
    name = models.CharField(max_length=100, verbose_name="Локация", default=u'') 
    photos = models.ImageField(upload_to='photos', null=True) 

這是我forms.py:

class LocationForm(forms.ModelForm): 

    class Meta: 
     model = Location 
     fields = ['name', 'photos'] 

這是我的views.py:

class AddLocationPageView(FormView): 
    template_name = 'add_location.html' 
    form_class = LocationForm 

    def form_valid(self, form): 
     form.save() 
     return super(AddLocationPageView, self).form_valid(form) 

I需要有可能在當時上傳幾張照片。 我該怎麼做? 謝謝!

+1

您需要了解[formsets](https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#django.forms.models.BaseModelFormSet) –

回答

1

由於我假設您使用的是關係數據庫,並且您的模型字段名稱是'照片',所以每個位置都需要多張照片。

你可以這樣做:

class Image(models.Model): 
    full_size = models.ImageField() 
    thumbnail = models.ImageField() 
    location = models.ForeignKey('app_label.Location', related_name='photos') 

,並從選址模型去除像場。

要上傳多張照片,您需要使用formset。根據您想要的界面,您可能會想要使用model formset,以便照片正確設置其location_id。

在窗體中,您只需使用可在視圖中調用的formset_factory函數(可能在get_context_data中)。

在你的視圖中處理formset涉及到一些邏輯上的爭議,但有一個名爲django-extra-views的項目用formset邏輯實現了窗體,這取決於你在這裏的接口。

如果您只想將照片添加到預先存在的位置,那就簡單多了:只需將model_formset包括在位置對象中即可。