GithubHelp home page GithubHelp logo

app-generator / django-learn-by-coding Goto Github PK

View Code? Open in Web Editor NEW
3.0 3.0 2.0 19 KB

Django Web Framework - Learn by Coding | AppSeed

Home Page: https://appseed.us

License: Other

Python 96.28% HTML 3.72%
django appseed-sample learn-by-coding

django-learn-by-coding's Introduction

Learn Django by Coding

Open-source project provided by AppSeed to help beginners accommodate and learn Django faster. For newcomers, Django is a popular web framework designed and actively supported by Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel.

For support and more Django Samples join AppSeed.


Create Django project

Create a virtual environment

$ # Linux-based systems
    $ virtualenv env
    $ source env/bin/activate  

For Windows systems, the syntax is different

$ virtualenv env
$ .\env\Scripts\activate

Install Django using PIP, the official package manager for Python

$ pip install django

Create project directory

$ mkdir learn-django
$ cd learn-django

Create project core

$ django-admin startproject config .

Set up the database

$ python manage.py makemigrations
$ python manage.py migrate

Start the project

$ python manage.py runserver 
$
$ # Access the web app in browser: http://127.0.0.1:8000/

Generate PDF Files

Install dependencies

$ pip install reportlab

Generate PDF file using Django Shell

$ python ./manage.py shell
>>>
>>> import reportlab
>>> from reportlab.pdfgen import canvas 
>>> p = canvas.Canvas('1.pdf')
>>> p.drawString(200, 200, "Hello world.") 
>>> p.showPage() 
>>> p.save()

The above code should create in the root of the project a new PDF file. To open the file, from the Django console, please type:

>>> import os,sys
>>> os.startfile('1.pdf', 'open')

The startfile helper should open the PDF file using the default handler registered in the operating system.


PDF creation with dynamic content - app_pdf/pdf_dw

# File Content: app_pdf/pdf_dw (partial content)
def pdf_dw(request):                                  

    # Create the HttpResponse object with the appropriate PDF headers. 
    response = HttpResponse(content_type='application/pdf') 

    # Comment the line to see the PDF in the browser 
    response['Content-Disposition'] = 'attachment; filename="1.pdf"' 
 
    # Create the PDF object, using the response object as its "file." 
    p = canvas.Canvas(response)     

    # READ Optional GET param
    get_param = request.GET.get('name', 'World')
    
    # Generate unique timestamp
    ts = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')

    # Write content on the PDF 
    p.drawString(100, 500, "Hello " + get_param + " (Dynamic PDF) - " + ts ) 
 
    # Close the PDF object. 
    p.showPage() 
    p.save() 

    # Show the result to the user    
    return response

PDF creation with image - app_pdf/pdf_img

def pdf_img(request):                                  

    # Create the HttpResponse object with the appropriate PDF headers. 
    response = HttpResponse(content_type='application/pdf') 
 
    # Create the PDF object, using the response object as its "file." 
    p = canvas.Canvas(response)     

    my_image = ImageReader('https://www.google.com/images/srpr/logo11w.png')
    
    p.drawImage(my_image, 10, 500, mask='auto')

    # Close the PDF object. 
    p.showPage() 
    p.save() 

    # Show the result to the user    
    return response

Create Custom Commands

Create the new app

python manage.py startapp app_customcmd

Inside the new app directory create a structure as shown below:

< PROJECT ROOT >                          <-- project directory
 |
 |-- app_customcmd/                                <-- app directory
 |    |-- management/
 |    |	   +-- __init__.py
 |    |    +-- commands/
 |    |         +-- __init__.py
 |    |         +-- cmd_....py  <-- module where all commands are saved

Update configuration to enable the new app

# File content: config/settings.py (partial content)
...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app_forms',
    'app_pdf',
    'app_customcmd',                     # <-- NEW
    'app',
]
...

Code a new dummy command - new file app_customcmd/management/commands/cmd_time.py

# File content: cmd_time.py

from django.core.management.base import BaseCommand
from django.utils import timezone

class Command(BaseCommand):
    help = 'Displays current time'

    def handle(self, *args, **kwargs):
        time = timezone.now().strftime('%X')
        self.stdout.write("It's %s" % time)

Registered Commands:

  • cmd_time.py - show current timestamp
  • cmd_apps - list all registered apps
  • cmd_models - list all apps and associated models
  • cmd_showcfg - list all CFG keys and values

Command Usage sample

$ python manage.py cmd_models 

Sample output

APP -> Administration
         |- (model) -> <class 'django.contrib.admin.models.LogEntry'>
 APP -> Authentication and Authorization
         |- (model) -> <class 'django.contrib.auth.models.Permission'>
         |- (model) -> <class 'django.contrib.auth.models.Group'>
         |- (model) -> <class 'django.contrib.auth.models.User'>
 APP -> Content Types
         |- (model) -> <class 'django.contrib.contenttypes.models.ContentType'>
 APP -> Sessions
         |- (model) -> <class 'django.contrib.sessions.models.Session'>
 APP -> Messages
 APP -> Static Files
 APP -> App_Forms
 APP -> App_Pdf
 APP -> App_Customcmd
 APP -> App
         |- (model) -> <class 'app.models.Book'>


Learn Django by Coding - Provided and actively supported by AppSeed App Generator

django-learn-by-coding's People

Contributors

app-generator avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

technologysoft

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.