Question:
Creating a form in Django to upload a picture from website

Problem

I was trying to build a form that make the user able to upload a picture from the website to Media\Images folder.

I try this but it doesn't work


models.py

from django.db import models


# Create your models here.



class imgUpscalling(models.Model):

    Image = models.ImageField(upload_to='images/')


forms.py

from django import forms

from .models import imgUpscalling


class ImageForm(forms.ModelForm):

    class Meta: 

        model = imgUpscalling

        fields = ('Image',) 


views.py

def img_upscaler(request):

    context = {'from': ImageForm()}

    return render(request, "upsc_main.html",context)


template.html

<h1>Image Upscaler & Enhanced Resolution</h1>

    <h2>Select the Image</h2>

     <form method = "post" enctype="multipart/form-data">

        {% csrf_token %}

        {{ form.as_p }}

        <button type="submit">Upload</button>

    </form>


Notify me of the mistakes I made in the code. because the form is not shown in the template. thanks a lot in advance


Solution:

Couple of things here:


  1. Configure your settings.py correctly. When working with media, you need to configure your project to handle media files, as so:

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')


  1. You also need to configure your urls.py on the project level, it will look something like the following:


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


if settings.DEBUG:

    static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


  1. Views.py

Your views should look something like this:


def upload_image(request):

    if request.method == 'POST':

        form = ImageForm(request.POST, request.FILES) # ensure you include request.files

        if form.is_valid():

            form.save()

            return redirect('upsc_main.html')  # Redirect to a success page

    else:

        form = ImageUploadForm()

    return render(request, 'yoururl.html', {'form': form})


Then obviously configure your apps urls.py, html templates etc.


Suggested blogs:

>How to configure transfers for different accounts in stripe with laravel?

>Laravel Query Solved: Laravel withOnly not restricting the query

>Laravel installation problem: Fix failed to download laravel/laravel from dist- Laravel (v10.2.6)

>How to fix when Postgres connection refused while running laravel tests on gitlab CI?



Ritu Singh

Ritu Singh

Submit
0 Answers