图像不在ImageAndUser模型中

时间:2017-09-30 04:04:50

标签: python html django

图片不在ImageAndUser模型中。我在views.py中写道,如

@csrf_exempt
def upload_save(request):

    if request.method == "POST":
        form = UserImageForm(request.POST, request.FILES)
        if form.is_valid():
            data = ImageAndUser()
            data.image = request.FILES['image']
            data.save()
        else:
            print(form.errors)
    else:
        form = UserImageForm()

    return render(request, 'registration/accounts/photo.html', {'form': form})

index.html是

<form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <h2>SEND PHOTO</h2>
        <div class="input-group">
          <label class="input-group-btn">
            <span class="btn btn-primary btn-lg">
              SELECT FILE
            <input type="file" style="display:none" name="files[]" multiple>
            </span>
          </label>
          <input type="text" class="form-control" readonly="">
        </div>

        <div class="form-group">
        <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
        </div>
        <div class="form-group">
        <input type="submit" value="SEND" class="form-control">
        </div>
      </form>

当我按下SEND按钮时,读取了upload_save方法。我的理想系统是image&amp;用户的数据放在ImageAndUser模型中。但是,现在ImageAndUser模型没有数据。我真的无法理解为什么。但终端说<ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required</li></ul></li></ul>所以我觉得我无法获取用户数据。但是,我认为用户登录网站后可以访问upload_save方法,所以我认为系统有用户数据。我不知道为什么图像和用户数据没有连接。 models.py是

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

我该如何解决这个问题?我该怎么写呢?

我的UserImageForm是

class UserImageForm(forms.ModelForm):
    class Meta:
        model = ImageAndUser
        fields = (
          'image',
          'user',
        )

1 个答案:

答案 0 :(得分:0)

@csrf_exempt
def upload_save(request):

    if request.method == "POST":
        form = UserImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        else:
            print(form.errors)
    else:
        form = UserImageForm()

    return render(request, 'registration/accounts/photo.html', {'form': form})