I’m trying to make it so a user can upload an avatar to their UserProfile, but I keep getting the following error:
IntegrityError at /~csihar/userpic
null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (4, null, userpics/image.jpg).
…with the first value incrementing by 1 each time I try to upload. I’ve attempted to instantiate the form with the user’s current profile before saving, as well as excluding irrelevant fields from the modelform, but it still isn’t working and I’m not sure what I’m overlooking. However, the image does get saved to my MEDIA_ROOT before the error occurs.
models.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')
views.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))
forms.py:
from django import forms
class UserpicUpload(forms.ModelForm):
userpic = forms.ImageField()
template (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 %}
Turns out I was going about it all wrong and was creating new profiles rather than adding to an existing one. The problem was fixed by replacing the following lines in views.py:
…with this:
Now I’m having issues getting the pic to display properly on the user’s home page, but that’s a whole separate issue that probably has to do with my MEDIA_URL – at least the pic is getting saved properly now!