So here is my form:
class AvatarUploadForm(forms.Form):
avatar = forms.ImageField(label='Image', help_text='Maximum size: 100x100px')
# Validation stuff down here.
And model:
class UserProfile(models.Model):
user = models.OneToOneField(User)
post_count = models.IntegerField(default=0)
avatar = models.ImageField(null=True, blank=True, upload_to='images/avatars')
# ...
And the currently unfinished and potentially buggy view:
@login_required
def user(request, username):
user = get_object_or_404(User, username=username)
profile = user.profile
if request.user == user:
if request.method == 'POST':
form = AvatarUploadForm(request.POST, request.FILES)
if form.is_valid():
profile.avatar = request.FILES['avatar']
profile.save()
return render_to_response('forum/user.html', {'profile_user': user, 'profile': profile},
context_instance=RequestContext(request))
else:
form = AvatarUploadForm()
return render_to_response('forum/user.html', { 'profile_user': user, 'profile': profile, 'form': form },
context_instance=RequestContext(request))
return render_to_response('forum/user.html', { 'profile_user': user, 'profile': profile })
What I want is to keep the original file extension, .png, .gif or whatever, but change the filename to be the user_id or username of the user.
Since when registering, users don’t upload an avatar and profiles are created when you view the page the avatar upload form is one, we can assume that the user profile already exists.
I’m thinking the solution lies somewhere in making upload_to a callable, but I’m not entirely sure.
Thanks.
You are correct. upload_to can be a callable. Here is an excerpt from a project of mine that you can adapt to your specifications. This does more than what you asked for, but I think it shows what kind of flexibility you can have.