skip to Main Content

I am trying to upload an image from input field but when I check from database (using Value in Editor), it shows a text which is a file name. I’m new to uploading image, so I’m not sure what’s missing in my code. I added media root on settings.py and urls.py. Here is my code.

models.py

class ImageUpload(models.Model):
    idupload = models.AutoField(db_column='idupload', primary_key=True)
    image = models.ImageField(db_column='image', upload_to="media/", null=True)
    description = models.CharField(db_column='description', max_length=50, null=True)

    class Meta:
        managed = True
        db_table = 'image_upload'

upload.html

<form method="post" action="" enctype="multipart/form-data" >
     {% csrf_token %}
     <div class="form-group">
         <label>Upload File</label>
         <input class="form-control" name="image" type="file" required>
     </div>
     <div class="form-group">
         <label>Description</label>
         <input class="form-control" name="description" required>
     </div>
     <button type="submit" name="upload" class="btn btn-gray-800 mt-2 animate-up-
                    
</form>

views.py

def uploadImage(request):
    if request.method == 'GET':
        return render(request, 'upload.html')
    if request.method == 'POST':
        image = request.FILES.get('image')
        description = request.POST.get('description')
        ImageUpload.objects.create(image=image, description=description)
        return redirect('/images/')

I tried above code but I kept on getting nothing.

2

Answers


  1. Chosen as BEST ANSWER

    So this is how I did it.

    def uploadImage(request):
        item = ImageUpload()
        item.description = request.POST.get('description')
        if len(request.FILES) != 0:
            item.image = request.FILES['image']
            item.save()
            return redirect('/images/')
    

    And here is how I view the images in html.

    {% for obj in item %}
    <div class="card-body">
        <div><img src="{{ obj.image.url }}" alt=""></div>
        <div>DESCRIPTION: {{ obj.description }}</div>
    {% endfor %}
    

  2. you can use CreateView this will save the Image into your media folder.

    from django.views.generic.edit import CreateView
    from .models import ImageUpload
    class UploadView(CreateView):
        model = ImageUpload
        fields = ['image','description' ]
        
    

    in urls.py

    urlpatterns = [
        ...<other url patterns>...
        path('', views.UploadView.as_view(), name='fileupload'),
    ]
    

    tempates myapp/imageupload_form.html:

    <form method="post" action="" enctype="multipart/form-data" >
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save">
    </form>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search