0

I am trying to render a form which will upload image. But I am not getting it.

Here models.py:

profile_picture = models.ImageField(_('profile picture'),upload_to="profile_pictures" , blank=True, null=True,default="static/images/person.jpg")

in forms.py:

class UploadProfilePictureForm(forms.Form):
    profile_picture=forms.ImageField(label='Select an Image')

in views.py:

def add_profile_picture(request):
if request.method=='POST':
    form=UploadProfilePictureForm(request.POST,request.FILES)
    p=FearUser(profile_picture=request.FILES['profile_picture'])
    p.save()
    return HttpResponseRedirect(reverse('profile:my_profile'))
else:
    form=UploadProfilePictureForm
return render_to_response('partials/_add_profile_picture.html',{'form':form},context_instance=RequestContext(request))

in urls.py:

url(r'^profile/update-pp/$','profiles.views.add_profile_picture',name='pp_update')

finally in _add_profile_picture.html:

            <form action="{% url 'profile:pp_update' %}" role="form" method="post" enctype="multipart/form-data">
                {% csrf_token %}

                <p>{{ form.profile_picture.label_suffix }}</p>
                <p>
                    {{ form.profile_picture.error_messages }}
                    {{ form.profile_picture }}
                </p>
                <div class="text-right">
                    <button type="button" class="btn btn-default custom_btn cancel_btn"
                            style="padding:5px 20px" data-dismiss="modal">Cancel
                    </button>
                    <button type="submit" class="btn btn-default custom_btn submit_btn"
                            style="padding:5px 20px">Submit
                    </button>
                </div>
            </form>

Can anyone explain me what I have done wrong?

5 Answers5

2

Without some more specific debugging info from you I cannot be entirely sure what you mean by "not getting it".

Some things you might try:

1) Actually validate the form (good practice).

2) Pull the image from the validated form. (also good practice).

if form.is_valid():
    form = UploadProfilePictureForm(request.POST, request.FILES)
    p = FearUser(profile_picture=form.cleaned_data['profile_picture'])
    p.save()

To help debug any actual image uploading issues, put in a print statement after the save like so:

print p.profile_picture.url and see what that outputs. If it's None, or not what you expect, than something is not right with your saving.

You can also print request.FILES and make sure the actual upload is working.

If you comment with the results I can try to help narrow it down.

Peter M. Elias
  • 1,204
  • 10
  • 22
  • Actullay I am not getting Upload for which should be rendered in template; After rendering the form I can try with cleaned_data or form.is_valid(). –  Mar 01 '16 at 09:11
1

Most likely your problems belong to wrong settings inside your settings.py. This is what I have in my project, which is working, try to replicate it, and try in the admin first if it's working. At least we will know if the problem is in your settings/model or in your view.

Create the path appdirectory/static/images, cause not sure if Django is creating it in case doesn't exists.

settings.py

PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__)))
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = path.join(PROJECT_ROOT, 'static').replace('\\', '/')
STATIC_URL = '/static/'
STATICFILES_DIRS = ()

add in 'django.contrib.staticfiles' in your installed apps.

models.py

   Pic = models.ImageField(upload_to='images/WaterMeterPictures/', blank=False, null=False) 

Once you get the admin working fine, the form generation should be straight forward.

Community
  • 1
  • 1
Madthew
  • 686
  • 6
  • 15
0

Dou you have Pillow installed?

0

Because you haven't used form.is_valid() your form is unbound and form.cleaned_data does not exist. Once you run form.is_valid() only then will you have access to cleaned_data.

somecallitblues
  • 680
  • 4
  • 9
0
@login_required
def createPost(request):
if request.method == 'POST':
        form = PostForm(request.POST,request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user

            post.save()
            return HttpResponseRedirect(reverse('Posts:post_detail', kwargs={'slug': post.slug}))

    form = PostForm()
    return render(request,'Posts/post_form.html',context={'key': form})

models.py

class Post(models.Model):
    user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=True)
    message = models.TextField()
    img = models.ImageField(upload_to="photo/%Y/%m/%d", blank=True)
    post_title = models.CharField(max_length=80, blank=False)
    slug = models.SlugField(allow_unicode=True, unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.post_title)
        super().save(*args, **kwargs)

    def __str__(self):
        return self.post_title

    # def get_absolute_url(self):
    #     return reverse('home')
    def get_absolute_url(self):
        return reverse('Posts:post_detail', kwargs={'slug': self.slug})

    class Meta:
        ordering = ['-created_at']