Python Django

Django connecting with mysql database

step 1

we need to install mysql module

pip install PyMySQL

step 2

configure mysql in settings.py

eg:-1

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'pypaywheel',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': '192.168.1.174',
        'PORT': '',
        'OPTIONS': {'charset': 'utf8mb4'},
    }
}

eg:-2

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangoblog',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '',
        'OPTIONS': {'charset': 'utf8mb4'},
    }
}
By bm on July 8, 2014 | Python Django | A comment?
Tags:

Django createing common static folder

settings.py

STATICFILES_DIRS = [
    BASE_DIR+"/pypayw/static/",
]

templet

{% load staticfiles %}

<head>
   <title>{% block title %}My amazing site{% endblock %}</title>
   <link rel="stylesheet" href="{{ STATIC_URL }}css/style.css" type="text/css">
   <script src="{{ STATIC_URL }}js/jquery-2.1.1.min.js"></script>
   
</head>
By bm on | Python Django | A comment?

Django accessing request object in template

Settings.py

#for accessing request objext in templet

TEMPLATE_CONTEXT_PROCESSORS = (
#default settings 
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",

#custome settings for loding request in templet
"django.core.context_processors.request",
)



templet

{{ request.user.first_name }} {{request.user.last_name}}


eg

{% if request.user.username %}

Hi {{ request.user.first_name }} {{request.user.last_name}} (<a href="/logout">Logout</a>)

{% else %}
 
<a href="/login">Login</a> 

{% endif %}

By bm on | Python Django | 1 comment

Django Log configuration in settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        'null': {
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        },
        'logfile': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename':  BASE_DIR+"/debug.log",
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'standard',
        },
        'console':{
            'level':'INFO',
            'class':'logging.StreamHandler',
            'formatter': 'standard'
        },
    },
    'loggers': {
        'django': {
            'handlers':['console'],
            'propagate': True,
            'level':'WARN',
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },

        'appName': {
            'handlers': ['console', 'logfile'],
            'level': 'DEBUG',
        },



    }
}



-----------

import logging

# Get an instance of a logger
log = logging.getLogger(__name__)
    

    log.debug("Hey there it works!!")
    log.info("Hey there it works!!")
    log.warn("Hey there it works!!")
    log.error("Hey there it works!!")

By bm on | Python Django | A comment?

Django cookies

setting cookies


    from django.shortcuts import render
    
    response = HttpResponse()
    response = render(request, 'hr/index.html',{'leaveRequests': leaveRequests,})
    response.set_cookie(key='sampCookieKey', value=1)
    return response  


syx:-  set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)

max_age should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session. If expires is not specified, it will be calculated.

expires should either be a string in the format "Wdy, DD-Mon-YY HH:MM:SS GMT" or a datetime.datetime object in UTC. If expires is a datetime object, the max_age will be calculated.

Use domain if you want to set a cross-domain cookie. For example, domain=".lawrence.com" will set a cookie that is readable by the domains www.lawrence.com, blogs.lawrence.com and calendars.lawrence.com. Otherwise, a cookie will only be readable by the domain that set it.

Use httponly=True if you want to prevent client-side JavaScript from having access to the cookie.


======================================================

Signed cookie
set_signed_cookie(key, value, salt='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=True


=========================================================

getiing cookies value

request.COOKIES.get('sampCookieKey')

==========================================================
deleting cookies 

request.delete_cookie(key, path='/', domain=None)


By bm on | Python Django | A comment?

Django session

settings Session

request.session['foo'] = 'bar'



retrieving value from session

x = request.session['foo']



deleting session

del request.session['foo']

By bm on | Python Django | A comment?