1

I want the user to upload the profile picture on the profile page but it is not storing it in the media/documents folder, and yes, I have put enctype="multipart/form-data" in the html form and the method is post. I'm new to django so please provide a simple solution

models.py

class User(models.Model):
first_name=models.CharField(max_length=20)
last_name=models.CharField(max_length=20)
username=models.CharField(max_length=25, primary_key=True)
password=models.CharField(max_length=15)
email_id=models.CharField(max_length=30, default='NULL')
profile_pic=models.ImageField(upload_to='profilepics/%Y/%m/%d/',height_field=200,width_field=200,default='')

forms.py

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

views.py

def upload(request):
if request.method == 'POST':
    username=request.POST['username']
    m=User(username=username)
    m.profile_pic=request.FILES['profile_pic']
    m.save()
    return render(request,'LoginPage/done.html')
else:
    pic=ProfilePicForm()
    return render(request,'AfterLogin/profile.html')

html file

    <form method="POST" enctype="multipart/form-data" action="{% url 'LoginPage:upload' %}">
        {% csrf_token %}
        <p>Upload your profile photo</p><br>
        <input id="id_image" type="file" class="" name="image">
        <input type="hidden" name="username" value="{{ username }}">
        <input type="submit" value="Submit"/>
    </form>
  • It's a good idea to post the error code, when something in ones code doesn't work. – Jonatan Feb 20 '17 at 22:38
  • How is you settings file configured? – Jonatan Feb 20 '17 at 22:39
  • There isn't any error. It just doesn't save the photos – Samarth Juneja Feb 21 '17 at 05:57
  • MEDIA_URL='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') – Samarth Juneja Feb 21 '17 at 05:58
  • Even if i remove the try and except statement, there isn't any error related to it. All I get is this Internal Server Error: /favicon.ico Traceback (most recent call last): "returned None instead." % (callback.__module__, view_name) ValueError: The view LoginPage.views.upload didn't return an HttpResponse object but I don't think that it is related – Samarth Juneja Feb 21 '17 at 06:02

3 Answers3

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.

Community
  • 1
  • 1
sprksh
  • 2,204
  • 2
  • 26
  • 43
  • Thanks for this, but I just have one doubt after this. When the file is uploaded, how does django know for which user the photo is? It is not mentioned anywhere. For which tuple will it save the photo? – Samarth Juneja Feb 21 '17 at 06:10
  • you have ImageField in user model. That field stores the location and name of the image like '/home/user/project/media/your_pic.jpg' or so. And while uploading, django always knows which user has sent the http request. – sprksh Feb 21 '17 at 06:26
  • When a user is authenticated on login page, he is redirected to the profile page where he has to upload the profile picture. Will django still know in reference to which user it is? – Samarth Juneja Feb 21 '17 at 06:40
  • Nope. Still does not save the image. Tried the code – Samarth Juneja Feb 21 '17 at 06:44
  • if a user is already authenticated, every request and response contains user instance in request.user. Try printing request.user in views. Also, you are trying to use a User model other than the one present in django by default. Plus, your upload view is not returning any response. remove the try except loop and tell the actual error. there are multiple errors. in upload view you have not defined username before using it. – sprksh Feb 21 '17 at 06:52
  • I removed the the try statement and there's still no error. I don't want to use the build in User model by django. I haven't created a session yet. Just plain validation as of now. – Samarth Juneja Feb 21 '17 at 07:03
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()

    ...
Jonatan
  • 1,182
  • 8
  • 20
  • I have added this part to the code. How do I use the User model provided by django and that OnetoOne thing? Also, if possible, please tell what changes can I make in my code to make it work? – Samarth Juneja Feb 21 '17 at 10:56
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.