我正在使用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
Models.py:
class BackgroundModel(models.Model):
user = models.OneToOneField(User)
background = models.ImageField(upload_to='backgrounds')
class BackgroundModelForm(ModelForm):
class Meta:
model = BackgroundModel
exclude = ('user',)
Views.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))
Urls.py:
url(r'^cover/$', 'cover.views.backgroundview'),
答案 0 :(得分:2)
而不是else分支中的g.background = form
,请尝试
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接受