4
class Data(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()

class Photo(models.Model):
    photo = models.ImageField(upload_to='img')
    data = models.ForeignKey(Data)

表格.py:

class DataForm(ModelForm):
    class Meta:
        model = Data

如何添加到此表单照片上传?

4

2 回答 2

3

至少有两种可能的答案:

A. 使用两个表单并将它们发布到同一个视图。首先持久化Data对象,然后创建Photo对象而不将其提交到数据库,将数据属性分配给data实例,然后调用.save()实例photo(下面提供示例)。

B. 使用内联模型表单集:https ://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets

[编辑]

class Data(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()

class Photo(models.Model):
    photo = models.ImageField(upload_to='img')
    data = models.ForeignKey(Data)

class DataForm(forms.ModelForm):
    class Meta:
        model = Data

class PhotoForm(forms.ModelForm):
    class Meta:
        model = Photo
        exclude = ('data',)

def your_view(request):
    data_form = DataForm(request.POST or None)
    photo_form = PhotoForm(request.POST or None, request.FILES or None)

    if request.method == 'POST':
        if data_form.is_valid() and photo_form.is_valid():
            data = data_form.save()
            photo = photo_form.save(commit=False)
            photo.data = data
            photo.save()
            # do something else here, like a redirect to another view.
    return render(request, 'your-template.html',
        {'data_form': data_form, 'photo_form': photo_form})

确保您的表单使用:multipart/form-data作为编码类型,否则request.FILES将为空。

于 2013-02-21T16:07:02.700 回答
1

手动添加ImageField到 Form 并覆盖save方法以创建照片:

class DataForm(ModelForm):
    class Meta:
        model = Data
    photo = forms.ImageField()

    def save(self, *arg, **kwargs):
        data = super(DataForm, self).save(*arg, **kwargs)
        if 'photo' in self.data :
           Photo.objects.create(
              photo=self.data['photo'],
              data=data
           )
        return data
于 2013-02-21T16:08:21.483 回答