ModelForm没有指定模型类如何连接模型和形式?

时间:2017-10-01 05:35:42

标签: python html django

我在/ accounts / upload_save /收到错误,ValueError ModelForm没有指定模型类。 我在forms.py中写道

class UserImageForm(forms.ModelForm):
    owner = forms.CharField(max_length=20)
    image = forms.FileField()

在models.py

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

@csrf_exempt
def upload_save(request):
    if request.method == "POST":
        form = UserImageForm(request.POST, request.FILES)
        if form.is_valid():
            data = UserImageForm()
            data.owner = forms.cleaned_data['user']
            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 %}

        <div class="input-group">
          <label class="input-group-btn">
            <span class="btn btn-primary btn-lg">
            <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模型中。我的代码出了什么问题?如何连接模型和表格?

1 个答案:

答案 0 :(得分:0)

class UserImageForm(forms.ModelForm):
    owner = forms.CharField(max_length=20)
    image = forms.FileField()

这不是以正确方式引用模型的方式:

class UserImageForm(forms.ModelForm):
    class Meta:
        model = ImageAndUser

并在视图中:

form = UserImageForm(request.POST, request.FILES)
        if form.is_valid():
            data = form.save(commit=False)#or just save if you dont need modify anything
            data.owner = forms.cleaned_data['user']
            data.image = request.FILES['image']
            data.save()

有关详细信息,请阅读此https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/