Detect if a directory exists or not in Django

This tutorial is all about detecting if a directory exists or not in Django. This tutorial will definitely help you to resolve the given task. By the end of this tutorial, hopefully, you will be able to detect if a directory exists or not. This task will be accomplished using the path and exists function which returns True when it exists and False when not.

Why do we need to do so?

Suppose you are working on a project and you need a particular directory, but you are a little confused that you created the directory with that name or not, you might have created it in some other folder or directory. When you need to detect whether it exists in the working directory or not, here is a solution to your problem in just a few lines, not even a few lines just 3 lines of code. This tutorial is special as it will demonstrate two methods to do this task. So without any further delay, let’s move to the code.

Before moving on towards the methods, make sure you have followed the below steps to start project and app-

  1. Open your IDE and navigate into the directory where you want to create project.
  2. Start a project
  3. Start an app

Method-1 To Detect directory by creating a view

Using this method you can see if a directory exists or not after executing python manage.py runserver

Open urls.py in your project and add URL to navigate in your urlpatterns as-

path("check/",views.check_path),

urls.py file-

from django.contrib import admin
from django.urls import path
from app import views as views

urlpatterns = [
    path('admin/', admin.site.urls),
    path("",views.check_path),
]

Now, its time to create a function in view.py to respond to this URL. It will return HttpResponse with True or False. import os.path and the from os.path import path, also import HtttpResponse from django.http

def check_path(request):
    return HttpResponse("Directory exists:" + str(path.exists("project")))

views.py file-

from django.shortcuts import render
from django.http import HttpResponse
import os.path
from os import path

# Create your views here.
def check_path(request):
    return HttpResponse("Directory exists:" + str(path.exists("project")))

 

Run your server in the terminal, you will be able to see something like-

Detect if a directory exists or not in Django

This is how you could detect if a directory exists or not.

Method-2 To detect directory with the help of shell

Using your terminal, run your shell-

python manage.py shell

You will enter into the shell.

  1. import os.
  2. from os import path.
  3. Check if a directory exists or not using exists() function.

import os

from os import path

path.exists("project")

Run these three codes of lines, it will return True or False, True if directory exists, False if not.

Leave a Reply

Your email address will not be published.