我正在尝试这样做,以便用户可以将头像上传到他们的 UserProfile,但我不断收到以下错误:
IntegrityError at /~csihar/userpic
null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (4, null, userpics/image.jpg).
...每次我尝试上传时,第一个值都会增加 1。我试图在保存之前使用用户的当前配置文件实例化表单,并从模型表单中排除不相关的字段,但它仍然无法正常工作,我不确定我忽略了什么。但是,图像确实MEDIA_ROOT
在错误发生之前保存到我的。
模型.py:
from django.contrib.auth.models import User
from django.forms import ModelForm
from django_resized import ResizedImageField
class UserProfile(models.Model):
user = models.OneToOneField(User)
userpic = ResizedImageField(max_width=100, max_height=100, upload_to='userpics/')
class UserpicUpload(ModelForm):
class Meta:
model = UserProfile
exclude = ('user','user_id')
视图.py:
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from items.models import User, UserProfile, UserpicUpload
from django.contrib.auth.decorators import login_required
@login_required
def userpic(request,list_owner):
current_user = User.objects.get(pk=request.user.id)
current_profile = current_user.get_profile()
if request.method == 'POST':
form = UserpicUpload(request.POST, request.FILES, instance=current_profile)
if form.is_valid():
newuserpic=UserProfile(userpic=request.FILES['userpic'])
newuserpic.save()
gohomeurl = "/~" + request.user.username
return HttpResponseRedirect(gohomeurl)
else:
form = UserpicUpload()
return render_to_response('userpic.html', {'listowner': list_owner, 'form':form}, RequestContext(request))
表格.py:
from django import forms
class UserpicUpload(forms.ModelForm):
userpic = forms.ImageField()
模板(userpic.html):
{% extends 'base.html' %}
{% block body %}
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.userpic.errors }}</p>
<p>{{ form.userpic }}</p>
<p><input name="submit" value="Upload" type="submit" />
</form>
{% endblock %}