Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Customize Object Names with __str__ Method
Next article icon

Prerequisite -Introduction to Django

Uploading and managing image files is a common feature in many web applications, such as user profile pictures, product images, or photo galleries. In Django, you can handle image uploads easily using the ImageField in models.

In this article, we’ll walk through a simple project namedimage_uploadand an app calledimage_app, where users can upload hotel images.

1. Configure settings.py

Add the following settings to handle media files:

Python
MEDIA_ROOT=os.path.join(BASE_DIR,'media')MEDIA_URL='/media/'
  • MEDIA_ROOTdefines the server-side file path for storing uploaded files.
  • MEDIA_URLprovides the browser-accessible URL to access those files.

2. Configure urls.py for Serving Media

Add this code to your project’surls.py:

Python
fromdjango.confimportsettingsfromdjango.conf.urls.staticimportstaticurlpatterns=[# your existing URL patterns]ifsettings.DEBUG:urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

This ensures that media files are served during development.

3. Create the Model

Create a modelHotelinmodels.py underimage_app:

Python
fromdjango.dbimportmodelsclassHotel(models.Model):name=models.CharField(max_length=50)hotel_Main_Img=models.ImageField(upload_to='images/')def__str__(self):returnself.name
  • ImageFieldis used for image uploads.
  • upload_to='images/' tells Django to store uploaded images inside the media/images/folder.

4. Create a Model Form

Create aforms.py file in your app and define the form:

Python
fromdjangoimportformsfrom.modelsimportHotelclassHotelForm(forms.ModelForm):classMeta:model=Hotelfields=['name','hotel_Main_Img']

Django’sModelFormautomatically generates form fields based on the model.

5. Create an HTML Template

Create a template namedhotel_image_form.html inside the templates directory:

html
<!DOCTYPE html><html><head><title>Upload Hotel Image</title></head><body><formmethod="POST"enctype="multipart/form-data">        {% csrf_token %}        {{ form.as_p }}<buttontype="submit">Upload</button></form></body></html>

Explanation:

  • enctype="multipart/form-data"is required for file uploads.
  • {% csrf_token %} is for security againstCSRFattacks.
  • {{ form.as_p }} renders each form field wrapped in <p> tags.

6. Create Views

In views.py, write the view to handle form submission:

Python
fromdjango.shortcutsimportrender,redirectfromdjango.httpimportHttpResponsefrom.formsimportHotelFormfrom.modelsimportHoteldefhotel_image_view(request):ifrequest.method=='POST':form=HotelForm(request.POST,request.FILES)ifform.is_valid():form.save()returnredirect('success')else:form=HotelForm()returnrender(request,'hotel_image_form.html',{'form':form})defsuccess(request):returnHttpResponse('Successfully uploaded!')

7. Add URL Patterns

Update urls.py to include paths for image upload and success page:

Python
fromdjango.urlsimportpathfrom.viewsimporthotel_image_view,successfromdjango.confimportsettingsfromdjango.conf.urls.staticimportstaticurlpatterns=[path('image_upload/',hotel_image_view,name='image_upload'),path('success/',success,name='success'),]ifsettings.DEBUG:urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

8. Run Migrations and Test

Run the following commands:

python manage.py makemigrations

python manage.py migrate

python manage.py runserver

Visit the development server URL-http://localhost:8000/image_upload/ in your browser. Upload an image, and you’ll be redirected to the success page.

Output: 

django03
Snapshot of /image_upload endpoint

After uploading the image it will show success.

django04
Snapshot of successful upload

Now in the project directory media directory will be created, an images directory will be created and the image will be stored under it. Here is the final result.

django_fs
Snapshot of media directory being created

Display Uploaded Images

We can write a view for accessing the uploaded images, for simplicity let's take example with one image and it is also applicable for many images:

Python
defdisplay_hotel_images(request):hotels=Hotel.objects.all()returnrender(request,'display_hotel_images.html',{'hotel_images':hotels})

Template: display_hotel_images.html

html
<!DOCTYPE html><html><head><title>Hotel Images</title><linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></head><body><divclass="container"><divclass="row">            {% for hotel in hotel_images %}<divclass="col-md-4"><h4>{{ hotel.name }}</h4><imgsrc="{{ hotel.hotel_Main_Img.url }}"class="img-responsive"style="width: 100%;"></div>            {% endfor %}</div></div></body></html>

Update urls.py:

path('hotel_images/', display_hotel_images, name='hotel_images'),

Below is the result when we try to access the uploaded images by visiting URL-http://127.0.0.1:8000/hotel_images/

django05
Snapshot of /hotel_images endpoint

Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp