Last active
May 11, 2020 01:11
-
-
Save godfather68/434cfa3f2e9a0e4e4d0c855cbbcd73cf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.core.management.base import BaseCommand | |
import os | |
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
class Command(BaseCommand): | |
help = "Templates Generator" | |
template_dir = os.path.join(BASE_DIR, 'templates') | |
def add_arguments(self, parser): | |
parser.add_argument('template_name', type=str, help="Indicates the template name(e.g home.html)") | |
# Optional app directory | |
parser.add_argument('-a', '--app', type=str, help="Defines a parent dir with the name of the app") | |
def generate_file_or_dir(self, template_name, app_name, content, **kwargs): | |
# Creating an parent directory with app name | |
app_dir = os.path.join(self.template_dir, '{app_name}'.format(app_name=app_name)) | |
# check if the directory exists, otherwise creates it | |
if os.path.exists(app_dir): | |
# Join the parent path and creating the file | |
file_path = os.path.join(app_dir, '{template_name}'.format(template_name=template_name)) | |
if not os.path.isfile(file_path): | |
template = open(file_path, 'w') | |
template.write(content) | |
template.close() | |
else: | |
# create the directory | |
os.makedirs(app_dir) | |
# call the () recursively | |
self.generate_file_or_dir(template_name, app_name, content) | |
def handle(self, *args, **kwargs): | |
self.stdout.write("Generating templates ...") | |
template_name = kwargs['template_name'] | |
app = kwargs['app'] | |
content = """ | |
{% extends '_base.html' %} | |
{% load staticfiles %} | |
{% block title %} title Here {%endblock %} | |
{% block content %} | |
{% endblock %} | |
""" | |
# if app argument is parsed | |
if app: | |
self.generate_file_and_dir(template_name, app, content) | |
else: | |
# Create the template in the current directory | |
file_path = os.path.join(self.template_dir, '{template_name}'.format(template_name=template_name)) | |
if not os.path.isfile(file_path): | |
template = open(file_path, 'w') | |
template.write(content) | |
template.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment