Django Photo Gallary | Django Project
Tags: django, python, programming
Published: 2021-05-23 15:53:14

Hello Friends, Whatsup? I hope you will fine.
In this blog, I am showing you a amazing project - Photo Gallary in Django Framework.

###Demo Video
{% youtube O_-ZyY8Nxh8 %}

##Source Code
1.) settings.py(Add Code)
```python
#Media Files
MEDIA_ROOT = 'D:\\django_projects\\dj_gallary\\main\\static\\media'
MEDIA_URL = 'media/'
```

2.) project/urls.py
```python
from django.contrib import admin
from django.urls import path, include

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('main.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```

3.) views.py
```python
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.generic import TemplateView
from .models import Post
from django.contrib import messages

# Create your views here.
class IndexView(TemplateView):
    template_name = 'index.html'
    def get(self, request):
        all_posts = Post.objects.all().order_by('-id')
        params = {"posts": all_posts}
        return render(request, self.template_name, params)


class UploadView(TemplateView):
    template_name = 'upload.html'
    def get(self, request):
        return render(request, self.template_name)
    def post(self, request):
        img_title = request.POST['title']
        imgName = request.FILES['img_name']
        add_img = Post(title=img_title, img_field=imgName)
        add_img.save()
        messages.success(request, 'Image Added Succefully.')
        # print(imgName, title)
        return render(request, self.template_name)


class DeleteView(TemplateView):
    def get(self, request, id):
        delete_post = Post.objects.get(id=id)
        delete_post.delete()
        messages.success(request, 'Image Deleted Succefully.')
        return redirect('/')
```

4.) app/urls.py
```python
from django.urls import path
from . import views



urlpatterns = [
	path('', views.IndexView.as_view(), name='index'),
	path('upload/', views.UploadView.as_view(), name='upload'),
	path('delete/<int:id>/', views.DeleteView.as_view(), name='delete_img')
]
```

5.) models.py
```python
from django.db import models

# Create your models here.
class Post(models.Model):
	title = models.CharField(max_length=200)
	img_field = models.ImageField(upload_to='uploads/')
	date = models.DateField(auto_now_add=True)

	def __str__(self):
		return self.title
```

6.) admin.py
```python
from django.contrib import admin
from .models import Post

# Register your models here.
admin.site.register(Post)
```

7.) templates/index.html
```html
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {% load static %}
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

    <title>Django Photo Gallary</title>
  </head>
  <body style="background-color: black; color: white;">
    <div class="container w-75 text-center py-5">
      <h2>Django Photo Gallary</h2>
      <div class="container">
        <a href="{% url 'upload' %}" class="btn btn-outline-primary">Upload Image</a>
      </div>
    </div>



    <div class="container">
        {% if messages %}
               <div class="container">
                   {% for message in messages %}
                   <div class="alert alert-{{ message.tags }}" role="alert">
                        {{ message }}
                   </div>
                   {% endfor%}
               </div>
            {% endif %}
        <div class="row">
            {% for post in posts %}
                <div class="col">
                    <img src="{% static post.img_field.url %}" id="image{{forloop.counter}}" alt="{% static post.img_field.url %}"
                        style="width: 300px; height: 300px;">
                    <h3>{{post.title}} <a href="{% url 'delete_img' post.id %}" class="btn btn-danger">Delete</a></h3>
                    <p class="text-muted">{{post.date}}</p>

                </div>
            {% endfor %}

        </div>

    </div>

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
  </body>
</html>

```

8.) templates/upload.html
```html
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {% load static %}
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

    <title>Django Photo Gallary</title>
  </head>
  <body style="background-color: black; color: white;">

    <div class="container w-75 text-center py-5">
      <h2>Django Photo Gallary</h2>
    </div>

    <div class="mb-3 container w-50">
        <div class="row">

            {% if messages %}
               <div class="container">
                   {% for message in messages %}
                   <div class="alert alert-{{ message.tags }}" role="alert">
                        {{ message }}
                   </div>
                   {% endfor%}
               </div>
            {% endif %}

            <form action="{% url 'upload' %}" method="post" enctype="multipart/form-data">
                {% csrf_token %}
                <input type="text" class="form-control my-4" name="title" placeholder="Title for Image">
            <div class="col">
                <input type="file" class="form-control" name="img_name" id="exampleFormControlInput1">
            </div>
            <div class="col">
                <input type="submit" value="Upload" class="btn btn-success my-4">
            </div>
            </form>
        </div>
        <div class="container text-center w-25 my-5">
            <a href="{% url 'index' %}" class="btn btn-outline-primary">Back</a>
        </div>
    </div>



    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>

  </body>
</html>
```