图像无法保存在db中

时间:2017-12-31 08:19:25

标签: python html django

图像无法保存在db.I中的views.py

@csrf_exempt
def upload_save(request):
    form = UserImageForm(request.POST, request.FILES)
    if request.method == "POST" and form.is_valid():
            data = form.save(commit=False)
            data.user = request.user
            data.save()
            return render(request, 'registration/photo.html')

    else:
        form = UserImageForm()
        return render(request, 'registration/profile.html', {'form': form})

在models.py

class ImageAndUser(models.Model):
    user = models.ForeignKey("auth.User", verbose_name="imageforegin",on_delete=models.CASCADE)
    image1 = models.ImageField(upload_to='images', null=True, blank=True,)
    image2 = models.ImageField(upload_to='images/', null=True, blank=True, )
    image3 = models.ImageField(upload_to='images/', null=True, blank=True, )

在forms.py

class UserImageForm(forms.ModelForm):
    image = forms.ImageField()
    class Meta:
        model = ImageAndUser
        fields = ('image',)
profile.html中的

<form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data" role="form">
            {% csrf_token %}

                <label class="input-group-btn">
                  <span class="file_select btn-lg">
                    File Select1
                    <input id="file1" type="file" name="image" accept="image/*" style="display: none">
                  </span>
                </label>
              <input type="text" class="form-control" readonly="">

                <label class="input-group-btn">
                  <span class="btn-lg file_select">
                    File Select2
                    <input id="file2" type="file" name="image2" accept="image/*" style="display: none">
                  </span>
                </label>
              <input type="text" class="form-control" readonly="">
            
                <label class="input-group-btn">
                  <span class="btn-lg file_select">
                    File Select3
                    <input id="file3" type="file" name="image3" accept="image/*" style="display: none">
                  </span>
                </label>
              <input type="text" class="form-control" readonly="">

              <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">

              <input id="send" type="submit" value="SEND" class="form-control">
          </form>

当我从html和SEND按钮上传3张图片时,没有保存图片。但是在发送SEND按钮后,会显示photo.html,因此程序成功。我无法理解为什么3张图片无法保存。我写了数据.save()。我应该如何解决这个问题?我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

在表单中,您需要指定要更新的所有字段:

class UserImageForm(forms.ModelForm):
    class Meta:
        model = ImageAndUser
        fields = ('image1', ''image2', 'image3')