2

我正在使用 jquery 表单插件http://jquery.malsup.com/form/#getting-started通过 ajax 上传图片。当我尝试上传时,它显示模型没有属性 _committed 这是我的 Html:

<form id="uploadform" method="post" enctype="multipart/form-data" action="/cover/">{% csrf_token %}
        {{ form.background }}
</form>

Javascript:

https://gist.github.com/2381406

模型.py:

class BackgroundModel(models.Model):
    user = models.OneToOneField(User)
    background = models.ImageField(upload_to='backgrounds')

class BackgroundModelForm(ModelForm):
    class Meta:
        model = BackgroundModel
        exclude = ('user',)

视图.py:

@login_required
def backgroundview(request):
    if request.is_ajax():
        form = BackgroundModelForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                g = BackgroundModel.objects.get(user=request.user)
            except BackgroundModel.DoesNotExist:
                data = form.save(commit=False)
                data.user = request.user
                data.save()
            else:
                g.background = form
                g.save()
            HttpResponse(" ")
    else:
        form = BackgroundModelForm()
    return render_to_response("cover.html", {'form': form}, context_instance=RequestContext(request))

网址.py:

url(r'^cover/$', 'cover.views.backgroundview'),
4

1 回答 1

2

而不是g.background = form在 else 分支中,尝试

try:
    g = BackgroundModel.objects.get(user=request.user)
except BackgroundModel.DoesNotExist:
    data = form.save(commit=False)
    data.user = request.user
    data.save()
else:
    g.background = form.save(commit=False).background
    g.save()
    # or
    BackgroundModelForm(request.POST, request.FILES, instance=g).save()

只有接受类型的值可以分配给模型实例的相应字段。
models.ImageField 这里接受

  • 文件路径字符串
  • django.db.models.fields.files.ImageFieldFile
  • django.core.files.images.ImageFile
于 2012-04-14T02:19:33.997 回答