[Answered ]-Cannot upload profile picture in django model

1👍

Have a look at this:

Need a minimal Django file upload example

Also, try sharing the error you are getting when trying to upload picture.

👤sprksh

1👍

I think it would be better for you to use the standard User model created by Django which already has the fields first_name, last_name, username, password and email. Then you create a new model with a OneToOneField with the model user.

If the image uploads and if you get a 404 when going directly to the image url when running the server, then you have forgotten to serve the image, which you have to do when you are in production phase.

urlpatterns = [
...patterns...
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Something like this should work:

modles.py

from django.contrib.auth.models import User    
class UserPicture(models.Model):
        user = models.OneToOneField(User, on_delete = models.CASCADE)
        picture = models.ImageField(upload_to='...')

forms.py

class ProfilePicForm(forms.ModelForm):
      class Meta:
            model = UserPicture
            fields=['profile_pic']

views.py

def your_view(request):
    ...
    if request.method == 'POST':
        form = UserPicture(request.POST, request.FILES)

        if form.is_valid():
            userprofile = form.save()
            userprofile.user = request.user
            userprofile.save()

    ...

0👍

You don’t have to define own User model since Django has it’s own: https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#user-model

And as Jonatan suggested – post error code. If there’s none, remove this try ... except: pass.

Leave a comment