简体   繁体   中英

How can I upload profile picture in user extended model in Django

I am not getting any error while uploading cover image to the Django's User extended model but I cannot see what is wrong I'm doing because it's not giving any error and not even updating my model. However I can change the bio by using this concept but i can't update the cover image to my User extended model. Here I am giving the source code

models.py

class Memer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    mobile = models.CharField(max_length=16, blank=True, null=True)
    bio = models.CharField(max_length=150, blank=False, null=False, default="Hey! I'm new here.")
    cover = models.ImageField(upload_to='cover-images/%y/%m/%d/', default='cover-images/default/memerrank-bg.jpg', blank=False, null=False)
    profile = models.ImageField(upload_to='profile-images/%y/%m/%d/', default='profile-images/default/memerrank-no-dp.jpg', blank=False, null=False)
    def __str__(self):
        return str(self.user)

forms.py

class UpdateCoverImageForm(forms.ModelForm):
    class Meta:
        model = Memer
        fields = ['cover']

views.py

def profile(request, username):
    try:
        user = User.objects.get(username=username)
        user_ = User.objects.filter(username=username)
        memer = Memer.objects.filter(user=user_[0].id)
    except User.DoesNotExist:
        raise Http404("Memer does not exist.")

    context = {
        'user_': user_,
        'memer': memer,
    }
    if request.method == "POST":
        bioForm = EditBioForm(data=request.POST, instance=request.user.memer)
        coverImageForm = UpdateCoverImageForm(data=request.FILES, instance=request.user.memer)
        if bioForm.is_valid():
            memer_ = bioForm.save(commit=False)
            memer_.save()
            messages.success(request, "Bio successfully updated your profile")
            return redirect('/profile/'+user_[0].username)
        elif coverImageForm.is_valid():
            memer_ = coverImageForm.save(commit=False)
            memer_.save()
            messages.success(request, "Cover Image has been updated successfully!")
            # print(coverImageForm)
            return redirect('/profile/'+user_[0].username)
        else:
            messages.error(request, "Something wrong happend")
            return redirect('/profile/'+user_[0].username)
    return render(request, 'profile.html', context)

profile.html

<form method="post" enctype="multipart/form-data">
 {% csrf_token %}
 {{ UpdateCoverImageForm }}
 <input type="submit" value="save">
</form>

So I have gone through many possibilities and found the answer of this problem in which https://stackoverflow.com/users/764182/dmitry-belaventsev helped me.

So, the problem here is in views.py .

1.First two positional arguments in the constructor of ModelForm are data and files. You should pass data to first one and files to second one.

2.If you don't have file fields here, then make no changes

bioForm = EditBioForm(data=request.POST, instance=request.user.memer)

3.But here make the change

coverImageForm = UpdateCoverImageForm(data=request.FILES, instance=request.user.memer)

to

coverImageForm = UpdateCoverImageForm(request.POST, request.FILES, instance=request.user.memer)

And Boom your files will gets updated.

You're not getting any errors simply because the code is doing exactly as you instructed it. The code will never enter into the elif statement, and this is because the "if bioForm.is_valid():" statement will always return True. I suggest you do something like this

if request.method == "POST":
        bioForm = EditBioForm(data=request.POST, instance=request.user.memer)
        coverImageForm = UpdateCoverImageForm(data=request.FILES, instance=request.user.memer)
        if bioForm.is_valid() and coverImageForm.is_valid():
            memer_ = bioForm.save(commit=False)
            memer_ = coverImageForm.save(commit=False)
            memer_.save()
            memer_.save()
            messages.success(request, "Profile successfully updated your profile")
            return redirect('/profile/'+user_[0].username)
        else:
            messages.error(request, "Something wrong happend")
            return redirect('/profile/'+user_[0].username)
    return render(request, 'profile.html', context)

If you wish to update one field at a time then i suggest you make different views for each one of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM