Skip to content

yunji0387/django-commands

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 

Repository files navigation

django-commands (For Git Bash in Windows)

Django 101

  • Django is web framework provides a generic functionality needed for building:
    • web applications
    • APIs
    • web services
  • Django used MVT Architecture mvtArchitecture
    • URL dispatcher
      • equivalent to the controller in the MVC architecture.
      • The URL patterns defined in each app under the project are also included, urls.py:
        from django.urls import path 
        from . import views 
        
        urlpatterns = [ 
            path('', views.index, name='index'), 
        ] 
    • View
      • view function reads the path, query, and body parameters included in the client's request If required.
        • It uses this data to interact with the models to perform CRUD operations.
      • A view can be a user-defined function or a class, You create View definitions in the views.pyfile of the respective app package folder.
      • The following code in the view.py file defines the index() view function.
        from django.shortcuts import render 
        # Create your views here. 
        from django.http import HttpResponse 
        
        def index(request): 
            return HttpResponse("Hello, world.") 
    • Model
      • a Python class, An app may have one or more model classes, conventionally put in the models.py file.
      • Django migrates the attributes of the model class to construct a database table of a matching structure.
      • Django's Object Relational Mapper helps perform CRUD operations in an object-oriented way instead of invoking SQL queries.
      • The view uses the client's and the model's data and renders its response using a template.
    • Template
      • a web page containing a mix of static HTML and Django Template Language code blocks.
      • You place Template web pages in the templates folder with the .html extension.
      • Django's template processor uses any context data from the view inserted in these blocks to formulate a dynamic response.
      • The view, in turn, returns the response to the user.
    • Django Documentation

create python venv

  1. Make sure to have python installed, and update pip version
    py -m pip install --upgrade pip
  2. Create a directory and in the directory create a python venv:
    mkdir <directory_name>
    cd <directory_name>
    py -m venv <env_name>
  3. To activate venv
    source ./<env_name>/Scripts/activate
  4. To deactivate venv
    deactivate

Install django library

  1. In the directory, install django with pip
    pip install django
  2. To check installed django version
    python -m django version
    or
    pip list

Create a django project

  • In the directory, while venv has activated, run:
      django-admin startproject <project_name>

Create a django app

  • In the directory, while venv has activated, run:
  •   cd <project_name>
      python manage.py startapp <app_name>

Launch development server

  1. In the directory while venv has activated, run:
  cd <project_name> 
   python manage.py runserver 
  1. If the bash responded with:
Watching for file changes with StatReloader
  1. To stop development server, just hit ctrl+c in bash.

Creating a view and URL configuration

  1. make sure to have django installed
  2. in the views.py
      from django.shortcuts import render
      from django.http import HttpResponse
      def home(request):
          return HttpResponse("Hello World!")
  3. in the App-level urls.py(If not exists please create one.)
     from django.urls import path
     from . import views
     urlpatterns = [
             path('', views.home, name="home"),
     ] 
  4. in the Project-level urls.py
      from django.contrib import admin
      from django.urls import path, include
      
      urlpatterns = [
          path('admin/', admin.site.urls),
          path('', include('myapp.urls')),
      ] 
  5. in the setting.py
    • add "'myapp.apps.MyappConfig'," to the INSTALLED_APPS list.
      INSTALLED_APPS = [        
          'django.contrib.admin',
          'django.contrib.auth',
          'django.contrib.contenttypes',
          'django.contrib.sessions',
          'django.contrib.messages',
          'django.contrib.staticfiles',
          'myapp.apps.MyappConfig', 
     ]

Create URL path with views HttpResponse

  1. make sure to have django installed
  2. in the views.py
      from django.shortcuts import render
      from http.client import HTTPResponse
      from django.http import HttpResponse
      
      def drinks(request, drink_name):
          drink = {
              'mocha' : 'type of coffee',
              'tea' : 'type of hot beverage',
              'lemonade': 'type of refreshment'
          }
          choice_of_drink = drink[drink_name]
          return HttpResponse(f"<h2>{drink_name}</h2> " + choice_of_drink)
  3. in the App-level urls.py (If not exists please create one)
      from django.urls import path
      from . import views
      
      urlpatterns = [
          path('drinks/<str:drink_name>', views.drinks, name="drink_name"), 
      ]

App-level urls.py namespace

  1. using instance namespace (If use this please skip step 2 - 4)
    • in Project-level urls.py
        #in demoproject/urls.py 
        urlpatterns=[ 
            # ... 
            path('demo/', include('demoapp.urls', namespace='demoapp')), 
            # ... 
        ] 
  2. adding "app_name = <app_name>" to App-level urls.py
  #demoapp/urls.py
  from django.urls import path  
  from . import views    
  app_name='demoapp' 
  urlpatterns = [  
      path('', views.index, name='index'),      
  ] 
  1. we can also use namespace with more than one app
  #newapp/urls.py 
 from django.urls import path 
 from . import views 
 app_name='newapp' 
 urlpatterns = [ 
     path('', views.index, name='index'), 
 ] 
  1. In the Project-level urls.py
  from django.contrib import admin 
  from django.urls import path, include 
  
  urlpatterns = [ 
      path('admin/', admin.site.urls), 
      path('demo/', include('demoapp.urls')), 
      path('newdemo/', include('newapp.urls')), 
  ] 
  1. To check the url path/route in django shell
  python manage.py shell 
  >>> reverse('demoapp:index') 
  '/demo/' 
  >>> reverse('newapp:index') 
  '/newdemo/' 
  1. In views.py
     from django.http import HttpResponsePermanentRedirect 
     from django.urls import reverse 
       
     def myview(request): 
         .... 
         return HttpResponsePermanentRedirect(reverse('demoapp:login'))
  2. Using namespace in the url tag
  • without using namespace
     <form action="/demoapp/login" method="post"> 
     #form attributes 
     <input type='submit'> 
     </form> 
     <form action="{% url 'login' %}" method="post"> 
     #form attributes 
     <input type='submit'> 
     </form> 
  • using namespace
     <form action="{% url 'demoapp:login' %}" method="post"> 
     #form attributes 
     <input type='submit'> 
     </form> 

views.py Http Error Handling

  • Basic error handling (in views.py)
    from django.http import HttpResponse, HttpResponseNotFound 
    def my_view(request): 
        # ... 
        if condition==True: 
            return HttpResponseNotFound('<h1>Page not found</h1>') 
        else: 
            return HttpResponse('<h1>Page was found</h1>') 
    or
     from django.http import HttpResponse 
     def my_view(request): 
         # ... 
         if condition==True: 
             return HttpResponse('<h1>Page not found</h1>', status_code='404') 
         else: 
             return HttpResponse('<h1>Page was found</h1>') 
  • Raise error handling (in views.py)
    from django.http import Http404, HttpResponse 
    from .models import Product 
    
    def detail(request, id): 
        try: 
            p = Product.objects.get(pk=id) 
        except Product.DoesNotExist: 
            raise Http404("Product does not exist") 
        return HttpResponse("Product Found") 
    • Custom page error handling (in views.py)
      1. First in settings.py set DEBUG to FALSE and add '*' to the ALLOWED_HOSTS to include all possible hosts.
        #settings.py      
        # SECURITY WARNING: don't run with debug turned on in production!        
        DEBUG=FALSE
        ALLOWED_HOSTS = ['*']
      2. ...
    • Exception Classes
      • ObjectDoesNotExist: All the exceptions of the DoesNotExist are inherited from this base exception.
      • EmptyResultSet: This exception is raised if a query does not return any result.
      • FieldDoesNotExist: This exception is raised when the requested field does not exist.
        try: 
           field = model._meta.get_field(field_name) 
        except FieldDoesNotExist: 
           return HttpResponse("Field Does not exist") 
      • MultipleObjectsReturned: When you expect a certain query to return only a single object, however multiple objects are returned. This is when you need to raise this exception.
      • PermissionDenied: This exception is raised when a user does not have permission to perform the action requested.
        def myview(request): 
            if not request.user.has_perm('myapp.view_mymodel'): 
                raise PermissionDenied() 
            return HttpResponse() 
      • ViewDoesNotExist: This exception is raised by django.urls when a requested view does not exist, possibly because of incorrect mapping defined in the URLconf.
      • Django’s Form API
        def myview(request):   
            if request.method == "POST":   
                form = MyForm(request.POST)   
                if form.is_valid():   
                    #process the form data 
                else:   
                        return HttpResponse("Form submitted with invalid data") 

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published