views:

103

answers:

0

Hi, I encounter a problem. In my user models there is an atrrbution: user.avatar = ImageField ('avatar', upload_to=AVATAR_TEMP_DIR, blank=True, null=True) then i use a modelform as an create user form. And the avatar is uploaded corrcet. Which upload to AVATAR_TEMP_DIR, then I move the avatar into AVATAR_ORIGINAL_PATH and make user.avatar._name as AVATAR_ORIGINAL_PATH % user.id After this, then I try to change an avatar. So I user another modelform to update. however, this time the avatar cannot be uploaded to AVATAR_TEMP_DIR, so I also cannot move the avatar to AVATAR_ORIGINAL_PATH. It seems that, after create the user. the AVATAR_TEMP_DIR set to upload_to is lost, so the program doesn't know where to upload the file. Can anyone help me to solve this problem? Thank you very much.

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('name', 'user_avatar', 'description')

class UserAvatarForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('user_avatar')

@login_required
def user_create(request):
    if request.method == 'POST':
        form = UserForm(request.POST, request.FILES)
        if form.is_valid():
            user = form.save(commit=False)
            user.save()
            user.handle_upload_user_avatar() # move image from AVATAR_TEMP_DIR to AVATAR_ORIGINAL_PATH
            user.save()
            return HttpResponseRedirect(user.url)
    else:
        form = UserForm()

    return render_to_response('user/user_create.html', locals())

@login_required
def settings_user_avatar(request, user_name):
    user = get_object_or_404(User, name=user_name)
    if request.method == 'POST':
        form = UserAvatarForm(request.POST, request.FILES,
instance=user)
        if form.is_valid():
            user = form.save()
            user.handle_upload_user_avatar() # move image from
AVATAR_TEMP_DIR to AVATAR_ORIGINAL_PATH
            user.save()
            return HttpResponseRedirect(user.url)
    else:
        form = UserAvatarForm(instance=user)

    return render_to_response('user/user_avatar.html', locals())