Django Image upload to model imagefield

This is a simple snippet to make an image upload to your model in django. Assuming you need only the image field, making a modelform is futile, so instead I make a most simple form class:
class ImageUploadForm(forms.Form):
    """Image upload form."""
    image = forms.ImageField()
and my example of Model:
class ExampleModel(models.Model):
    model_pic = models.ImageField(upload_to = 'pic_folder/', default = 'pic_folder/None/no-img.jpg')
Given those, the html form within the template should be something like that:
            <form action="{% url upload_pic %}" method="post" enctype="multipart/form-data">{% csrf_token %}
                <p>
                    <input id="id_image" type="file" class="" name="image">
                </p>
                <input type="submit" value="Submit" />
            </form>
What is important to notice here is that the form has "enctype" of enctype="multipart/form-data" which is necessary for the file upload.
The view might look like that: (my view does not serve any template, since my implementation is via Ajax, on that in my next post
def upload_pic(request):
    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            m = ExampleModel.objects.get(pk=course_id)
            m.model_pic = form.cleaned_data['image']
            m.save()
            return HttpResponse('image upload success')
    return HttpResponseForbidden('allowed only via POST')
here again, one of the common pitfalls is forgetting about the "request.FILES" which most be given to the form class initializer when dealing with files.




Note:

      Syntax:-

       photo1=models.ImageField(upload_to='photo')



in model.py we declare these


so photo1 is column name , ImageField is datatype and upload_to argument is the folder where we need to upload the photo



No comments:

Post a Comment