DEV Community

SachinDas246
SachinDas246

Posted on

Django COPY PASTE !

If you are Beginner or an intermediate Django developer u know that starting a new project in Django project is easy, nothing more than just couple of commands right? But at least for me I have to Duck it or check the previous project every time to get it right. For instance I always get trouble if it is createapp or createproject or startproject to start a Django project.

So here are some of the commands and snippets which you might find help full!. Note that these are not the steps to create a project nor are in particular order. Also you might not need all these steps in your project , so use only what you need.

1. Installing Virtual Env wrapper:

# For Linux and OS X :
pip install virtualenvwrapper

# For windows:
pip install virtualenvwrapper-win
Enter fullscreen mode Exit fullscreen mode

2. Creating, Enabling and Disabling Virtual Environment using wrapper :

# To create virtual env
mkvirtualenv [virtual env name]
# To enable virtual env
workon [virtual env name]
# To disable virtual env
deactivate
Enter fullscreen mode Exit fullscreen mode

3. Installing Django

pip install Django
Enter fullscreen mode Exit fullscreen mode

4. Creating a Django Project:

Some may prefer giving project name as "config" at first so they get a project with settings.py and other core files inside "config app and afterwards renaming the project root directory to the project name.

django-admin startproject [project name]
Enter fullscreen mode Exit fullscreen mode

5. Running in development server

# running on 127.0.0.1:8000
python manage.py runserver
# running on a different port (eg. 127.0.0.1:7777)
python manage.py runserver 7777
# running on a different ip (eg. 192.168.1.5:7777)
python manage.py runserver 192.168.1.5:7777

Enter fullscreen mode Exit fullscreen mode

6. Access Database shell

python manage.py dbshell
Enter fullscreen mode Exit fullscreen mode

7. Access Django shell

python manage.py shell
Enter fullscreen mode Exit fullscreen mode

8. Make Database Migration and Migrate

# Make migration
python manage.py makemigrations
# Migrate
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

9. Adding new App to the project:

  • Run the following command to create an app
  • Add your app name to the INSTALLED_APPS variable in settings.py
# create new app
python manage.py startapp app_name
# add app to settings.py
INSTALLED_APPS = [
    'django...',
     .
     .
    'app_name'
]
Enter fullscreen mode Exit fullscreen mode

10. A simple view that return a web page

  • define a function inside your app_name/view.py
from django.shortcuts import render

def home(request):    
    return render(request,'home.html') # make sure you have home.html configured properly

Enter fullscreen mode Exit fullscreen mode

11. Configure urls for each app

  • You can have separate urls.py file in each app to efficiently route your project.For which: create a file named urls.py inside your corresponding app and add it to the main urls.py (that resides along with your settings.py file )

inside newly created urls.py

from os import name
from django.urls import path
from . import views
urlpatterns = [
    path('__page_location__', views.function_name,name="name for the page"),
# here it would be path('home', views.home,name="home"),"
]

Enter fullscreen mode Exit fullscreen mode

Add this url.py to the main urls.py (that resides along with settings.py)
main "urls.py"

from django.contrib import admin
from django.urls import path
from django.urls.conf import include

urlpatterns = [
  #  path('admin/', admin.site.urls),
  path('app_name', include('app_name.urls')),
]
# if you done properly you should see home page at http://127.0.0.1:8000/app_name/home
Enter fullscreen mode Exit fullscreen mode

12. Adding Templates

  • Create a Dir called templates(or anything you wish) inside project root Dir
  • Update your TEMPLATES variable inside settings.py
# add your templates dir to DIRS in TEMPLATES variable.
'DIRS': [os.path.join(BASE_DIR,'templates')],
Enter fullscreen mode Exit fullscreen mode

13. Configuring Static Dir

  • Create a dir called "static" (or anything you wish) in the project root dir .
  • Update setting.py by adding static dir to it.
# If you need a different name or location update it accordingly. you could add multiple dirs using ',' commas 
STATICFILES_DIRS = [
    BASE_DIR / "static",
]
Enter fullscreen mode Exit fullscreen mode
14. Loading static files inside html
  • whenever you need to static files in your template , you need to call {% load static %} before hand ( note you need to call in every html(template) file that require static content.)
{% load static %}
Enter fullscreen mode Exit fullscreen mode
  • After that , you could load static file like ( here logo.png is the file located in the static dir. )
<img src="{% static 'logo.png' %}" alt="logo">
Enter fullscreen mode Exit fullscreen mode
15. Similarly you could load your css file.
  • create style/style.css inside static dir
  • add this to your corresponding html template
{% load static %}
<link rel="stylesheet" href="{% static 'style/style.css' %}">
Enter fullscreen mode Exit fullscreen mode

16. Configuring Media files

  • As you might know Django don't like to serving its media file , so this config also allows only media file access in development
  • Create a dir called media in the project root dir
  • Add config to settings.py and urls.py (that resides along with your settings.py file )
# in settings.py add the following
MEDIA_ROOT =os.path.join(BASE_DIR,'media/')
MEDIA_URL = '/media/'

# in urls.py 
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

Enter fullscreen mode Exit fullscreen mode

17. A Simple Template Approach

  • A simple approach for the Django app is to create a base html template that includes the basic tags and extend it to the other pages.
    • here is a sample basic template
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PROJECT_NAME</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'style/style.css' %}">
</head>
<body>
    {% block content %}

    {% endblock %}    
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

And extent in another template for example home.html

{% extends 'base.html' %}
{% block content %}

<h1> this is home page </h1>

{% endblock %}

Enter fullscreen mode Exit fullscreen mode

18. Including templates

  • If wish, you could include other templates to your main template. For instance you could create a template named nav_bar.html and include in every other templates ( here I have included it in home.html ).

nav_bar.html

<p> this is a nav bar. </p>
Enter fullscreen mode Exit fullscreen mode

home.html

{% extends 'base.html' %}
{% block content %}
{% include 'navbar.html'%}

<h1> this is home page </h1>

{% endblock %}
Enter fullscreen mode Exit fullscreen mode

19. Simple regex verification

  • Warning: these are very basic regex. Do your own research before using regex.
import re

email_regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9&]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')
zip_regex = re.compile(r'^[A-Za-z0-9\.\-\s]{3,10}$')
password_regex = re.compile(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$ %^&*-])[a-zA-Z0-9!@#$&*]{8,15}$')

# To verify
email = "someone@somewhere.com"
if not re.fullmatch(email_regex,email):
        return "Invalid email"

Enter fullscreen mode Exit fullscreen mode

20. CSRF for Api

  • By default Django checks for csrf verification, so make sure you add {% csrf_token %} in your forms
  • And if you are manually send request using js you need to include the csrf token in your request.
# for forms:
<form ... >
{% csrf_token %}             
</form>

# For manual request 

# this function return csrf token from cookie 
function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }


# inside your request options add csrf token in header
var requestOptions = {
            method: 'POST',
            headers: {'X-CSRFToken': getCookie('csrftoken')},
            body: formdata,
            mode: 'same-origin',
            redirect: 'follow'
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)