Search code examples
pythondjangodjango-modelsdjango-viewsdjango-uploads

(Django) By updating the UserProfile, the image is not saving correctly


I made a view, to update a userprofile. When uploading an image the image is saved correctly, but when updating the profile again, the image is not saved anymore, how can I solve that problem? I am glad for any help!

my class UserProfile looks like this:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    bio = models.TextField(max_length=500, blank = True, default=('keine Angabe'), null=True)
    image = models.FileField(null=True, blank=True)
    facebook = models.CharField(max_length=200, null=True,default=('keine Angabe'))

    def get_absolute_url(self):
        return reverse('gaestebuch:result', args=[str(self.id)])

    def __unicode__(self):
        return self.user.username

    @property
    def get_content_type(self):
        instance = self
        content_type =   ContentType.objects.get_for_models(instance.__class__)
        return content_type

I use two views:

def update_profile(request):
    userProfile = UserProfile.objects.get(user=request.user)
    form = UserProfileForm(initial={'bio': userProfile.bio, 'image' : userProfile.image, 'facebook': userProfile.facebook})
    return render_to_response('gaestebuch/update_profile.html', {'form':form}, RequestContext(request))


@login_required
def send_update_profile(request):
    if request.method == 'POST':
        #form = UserProfileForm(request.POST)
        form = UserProfileForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            userProfile = UserProfile.objects.get(user=request.user)
            bio = form.cleaned_data['bio']
            userProfile.bio = bio
            image = form.cleaned_data['image']
            userProfile.image = image
            facebook = form.cleaned_data['facebook']
            userProfile.facebook = facebook
        userProfile.save()
        return redirect('the url' + str(userProfile.id))
    else:
        form = UserProfileForm()
    return redirect('/user/send_update_profile')

This is my form:

class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('bio','image','facebook',)

If there is anything else necessary to ad, I am happy to add that.

I am glad for any help!


Solution

  • Since you are using a ModelForm subclass instead of a Form subclass you should make use of it's functionality, particularly the save method.

    Every ModelForm also has a save() method. This method creates and saves a database object from the data bound to the form. A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, save() will update that instance. If it’s not supplied, save() will create a new instance of the specified model

    Thus your code ca be simplified as

    form = UserProfileForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
        return redirect('the url' + str(userProfile.id))
    
     else:
        return render_to_response(
            'gaestebuch/update_profile.html', {'form':form}, RequestContext(request))
    

    On a side note, when writing new django code use render instead of render_to_response as render_to_response is planned to be deprecated in the future and eventually removed.