Wednesday 18 May 2016

How start your first django programing



This framework so easy and nice it just write little and get more

Django is an MVC framework. However, the controller is called the "view", and
the view is called the "template". The view in Django is the component which
retrieves and manipulates data, whereas the template is the component that presents data to the user. For this reason, Django is sometimes called an MTV framework (MTV stands for model template view). This different terminology not changes the fact that Django is an MVC framework, nor affects how applications are developed. But keep the terminology in mind to avoid possible confusion if you have worked with other MVC frameworks in the past

now i will create a empty project



create a empty folder like "django" just for collection

To create your first Django project, open a terminal type the following command, and hit enter:

$cd django
$ django-admin.py startproject store

 This command will make a folder named store in the current directory, and create the initial directory structure inside it. where you can see kinds of file created like:

store/
      __init__.py (django project is a python package so and this file create
                           current folder like a package)
      manage.py (use for manage project)
      settings.py (configuration file of django project)
      urls.py (this is another configuration file. You can think of it as a mapping
                   between URLs and Python functions)

next open setting.py file and find bellow section 

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

when you find this section then edit this section to

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "store",
        'USER': "root",
        'PASSWORD':"root",
    }
}

we will try to connect mysql thats why we have set database module name "django.db.backends.mysql" this is a class that are in django/db/backends and class name is mysql this will load when django server will run and also i have set database name ,username and password(this is password that you have given on mysql intalletion) this all mysql information

next you need to create database so open terminal and type

$mysql -uroot -p

next give your mysql password if you right password you will see mysql command prompt

next type this command

mysql>create database store

this command for create store database

Finally, we will tell Django to populate the configured database with tables.
Although we haven't created any tables for our data, Django requires several tables in the database for some of its features to function properly. Creating these tables is easy just follow and type this command in terminal and you will see your result:

first of all go to your django folder next store folder from your terminal

$cd django
$cd store

when you at store folder then type bellow command

$ python manage.py syncdb

this command for syncronized with database

If you have entered the above command and everything is correct, status messages will scroll on the screen indicating that the tables are being created. When prompted for the superuser account, enter your preferred username, email address and password. It is important to create a superuser account otherwise you won't be able to gain access to your initial webpage once you have created it. If, on the other hand, the database is mis-configured, an error message will be printed to help you troubleshoot the issue like bellow screenshot


and finally you can launching the development server
go to store folder from terminal and type this command:

$ python manage.py runserver

this command for run your django server 
Next, open your browser, and navigate to http://localhost:8000/. You should see a welcome message as in the image below:

Now Enjoyyyyy.........

Django: Using Caching to Track Online Users


Recently I wanted a simple solution to track whether a user is online on a given Django site.  The definition of "online" on a site is kind of ambiguous, so I'll define that a user is considered to be online if they have made any request to the site in the last five minutes. 

I found that one approach is to use Django's caching framework to track when a user last accessed the site.  For example, upon each request, I can have a middleware set the current time as a cache value associated with a given user.  This allows us to store some basic information about logged-in user's online state without having to hit the database on each request and easily retrieve it by accessing the cache.

My approach below.  Comments welcome.

In settings.py:

# add the middleware that you are about to create to settings

MIDDLEWARE_CLASSES = (
    ....
    'middleware.activeuser_middleware.ActiveUserMiddleware',
    ....
)

# Setup caching per Django docs. In actuality, you'd probably use memcached instead of local memory.

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'default-cache'
    }
}

# Number of seconds of inactivity before a user is marked offline

USER_ONLINE_TIMEOUT = 300

# Number of seconds that we will keep track of inactive users for before 
# their last seen is removed from the cache

USER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 7

In activeuser_middleware.py:

import datetime
from django.core.cache import cache
from django.conf import settings

class ActiveUserMiddleware:

    def process_request(self, request):
        current_user = request.user
        if request.user.is_authenticated():
            now = datetime.datetime.now()
            cache.set('seen_%s' % (current_user.username), now, 
                           settings.USER_LASTSEEN_TIMEOUT)

In your UserProfile module or some other model associated with the user:

class UserProfile(models.Model):
    ....
    ....

    def last_seen(self):
        return cache.get('seen_%s' % self.user.username)

    def online(self):
        if self.last_seen():
            now = datetime.datetime.now()
            if now > self.last_seen() + datetime.timedelta(
                         seconds=settings.USER_ONLINE_TIMEOUT):
                return False
            else:
                return True
        else:
            return False

Then in the template where you want to display whether the user is online or not:

{% with request.user.get_profile as profile %}

 <table>
   <tr><th>Last Seen</th><td>{% if profile.last_seen %}{{ profile.last_seen|timesince }}{% else %}awhile{% endif %} ago</td></tr>
   <tr><th>Online</th><td>{{ profile.online }}</td></tr>
 </table>

{% endwith %}

Pros:
 - Simple solution
 - Doesn't need to hit the database for saving the timestamp each request

Cons:
  - Last user access times are cleared if the server is rebooted or cache is reset
  - Last user access times are accessible only as long as they exist in the cache.

Django Admin Override Save for Model

Sometimes it's nice to be able to add custom code to the save method of objects in the Django Admin. So, when editing an object on the Admin object detail page (change form), adding the following method override to your ModelAdmin in admin.py will allow you to add custom code to the save function. 

In admin.py:

class MyModelAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        # custom stuff here
        obj.save()

This is documented in the Django Docs, but I found it particularly useful

Tuesday 10 May 2016

Google reCAPTCHA integration in Django



Introduction


reCAPTCHA is a free service to protect your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive captcha to keep automated software from engaging in absive activities on your site. it does this while letting your valid users pass through with ease.reCAPTCHA offers more than just spam protection. Every time our CAPTCHAs are solved. that

human effort helps digitize text,annotate images, and build machine learning datasets.This in turn helps preserve books,improve maps, and solve hard Al problems.

demo for reCAPTCHA in your website

How to integrate google reCAPTCHA with django ?


step 1 .Install django-nocaptcha-recaptcha in your Virtual Environment
        pip install django-nocaptcha-recaptcha
        
step 2 .Configuration
        Add  nocaptcha_recaptcha to your INSTALLED_APPS setting
        Add the following to settings.py

        NORECAPTCHA_SITE_KEY  (string) = the Google provided site_key
        NORECAPTCHA_SECRET_KEY (string) = the Google provided secret_key
        
        Reffer  this link : https://developers.google.com/recaptcha/intro
        Add the field to a form that you want to protect.
        
        from nocaptcha_recaptcha.fields import NoReCaptchaField

        class DemoForm(forms.Form):
            captcha = NoReCaptchaField()

        Add Google's JavaScript library to your base template or elsewhere, so it is available on the 
        page  containing the django form.

        <script src="https://www.google.com/recaptcha/api.js" async defer></script>
        (optional) You can customize the field.

        You can add attributes to the g-recaptcha div tag through the following
            captcha = NoReCaptchaField(gtag_attrs={'data-theme':'dark'}))    
        You can override the template for the widget like you would any other django template.

step 3 : Demo project
           
          demo project for google recaptcha integration

Friday 6 May 2016

Asynchronous Tasks With Django and Celery

Introduction


When i was working on projects in  Django ,  one of the most frustrating thing I faced was need to run a bit of code periodically, i wrote my own function is for sending newsletter on the Monday morning 10 am , this time i faced lots of problem because some times my function did not working properly don't mean's syntactically , so i may think to start where i done wrong , is right no ? then how the problem is occurring , after that finally i found a solution for do some task periodically we can use Celery.




What is Celery ?

Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well.” For this post, we will focus on the scheduling feature to periodically run a job/task.
Why is this useful?
  • Think of all the times you have had to run a certain task in the future. Perhaps you needed to access an API every hour. Or maybe you needed to send a batch of emails at the end of the day. Large or small, Celery makes scheduling such periodic tasks easy.
  • You never want end users to have to wait unnecessarily for pages to load or actions to complete. If a long process is part of your application’s workflow, you can use Celery to execute that process in the background, as resources become available, so that your application can continue to respond to client requests. This keeps the task out of the application’s context.
What you need ?

Celery requires a message transport to send and receive messages. The RabbitMQ and Redis broker transports are feature complete, but there’s also support for a myriad of other experimental solutions, including using SQLite for local development.
Celery can run on a single machine, on multiple machines, or even across data centers.

First Steps with Celery

Celery is a task queue with batteries included. It is easy to use so that you can get started without learning the full complexities of the problem it solves. It is designed around best practices so that your product can scale and integrate with other languages, and it comes with the tools and support you need to run such a system in production.

In this blog you will learn the absolute basics of using Celery. You will learn about;
  • Choosing and installing a message transport (broker).
  • Installing Celery and creating your first task.
  • Starting the worker and calling tasks.
  • Keeping track of tasks as they transition through different states, and inspecting return values.
     Choosing a Broker
         Celery requires a solution to send and receive messages; usually this comes in the form of                 a separate service called a message broker.
      There are several choices available, including: (please search google for more details )
  •        RabbitMQ
  •        Redis
  •        Using a database
  •        Other brokers

 Installing Celery

 Celery is on the Python Package Index (PyPI), so it can be installed with standard Python tools like  pip or easy_install:
$ pip install celery
Example :

Let’s create the file tasks.py
from celery import Celery

app = Celery('tasks', broker='amqp://guest@localhost//')

@app.task
def add(x, y):
    return x + y
Example Project :
Clone my project  url : git cloe https://github.com/renjithsraj/photogallery.git
Project Description :
This Project mainly looking for basic understand about the periodic task ( scheduling task ) in django. The scope of the project is collect the images from the flickr latest images and store in to data base in every two minute (change with your own time ) make it a gallery.

heroku url : https://flickercollection.herokuapp.com/
Configuration:
step 1 : Create Virtualenv using (virtualenv env)
step 2 : open terminal activate the env
step 3 : clone the project command ( git clone https://github.com/renjithsraj/photogallery.git )
step 4 : make the path to project ( cd photogallery in linux )
step 5 : install packages which we required for this project ( pip install -r requrements.txt )
step 6 : install broker here im used redis ( if install redis server also in your local machine )
step 7 : open new terminal start the redis server ( redis-server command )
step 8 : Running Locally
Ready to run this thing?
With your Django App and Redis running, open two new terminal windows/tabs. In each new window, navigate to your project directory, activate your virtualenv, and then run the following commands (one in each window):
 $ celery -A pincha worker -l info
 $ celery -A pincha beat -l info
    When you visit the site on http://127.0.0.1:8000/ you should now see one image. Our app gets one image from Flickr every 2 minutes: ( here i just take images frequent interval please make your intervel )

Packages that make you developing apps in django awesome that make developing django application awesome

Introduction

There are many reasons why I like developing web applications with Python and Django but the main one is the awesome community and projects around the language and framework. Every time I search for something there’s always a Django or Python project available to make my life easier.

Here’s an incomplete list of Python and django related packages that I have used or I’m planning to test. This might help someone starting out to get an idea of how awesome is to work with this packages.


Packages are

Django Debug Toolbar

https://github.com/dcramer/django-debug-toolbar
The Django Debug Toolbar is a configurable set of panels that display various debug information about the current request/response and when clicked, display more details about the panel’s content.

South

http://south.aeracode.org
South brings migrations to Django applications. Its main objectives are to provide a simple, stable and database-independent migration layer to prevent all the hassle schema changes over time bring to your Django applications.

Django Paypal

https://github.com/johnboxall/django-paypal
Django PayPal is a pluggable application that implements with PayPal Payments Standard and Payments Pro.

Django Avatar

https://github.com/ericflo/django-avatar
A reusable django application for handling Avatars.

Fabulous

https://github.com/gcollazo/Fabulous
Shameless plug. I made this. It deploys django apps to Amazon EC2 with ONE command.

Django Exceptional

https://github.com/zacharyvoase/django-exceptional
A Django client for Exceptional (www.getexceptional.com)

Django Easy Maps

https://bitbucket.org/kmike/django-easy-maps
This app makes it easy to display a map for given address in django templates. No API keys, manual geocoding, html/js copy-pasting or django model changes is needed.

Django Extensions

https://github.com/django-extensions/django-extensions
It provides a plethora of useful manage.py commands, and a couple other little goodies as well.

Pinax

https://github.com/pinax/pinax
Django-based platform for rapidly developing websites

Django CMS

https://github.com/divio/django-cms
A Django application for managing hierarchical pages of content, possibly in multiple languages and/or on multiple sites.

Django Sentry

https://github.com/dcramer/django-sentry
Sentry provides you with a generic interface to view and interact with your error logs. By default, it will catch any exception thrown by Django and store it in a database.

Django Haystack

https://github.com/toastdriven/django-haystack
Haystack provides modular search for Django. It features a unified, familiar API that allows you to plug in different search backends (such as Solr, Whoosh, Xapian, etc.) without having to modify your code.

Django Celery

https://github.com/ask/django-celery
Provides Celery integration for Django; Using the Django ORM and cache backend for storing results, autodiscovery of task modules for applications listed in INSTALLED_APPS, and more.


Django-tastypie

https://github.com/toastdriven/django-tastypie
Creating delicious APIs for Django apps since 2010.

python-social-auth 

https://github.com/omab/python-social-auth
Django social authentication made simple.

django-filter

https://github.com/alex/django-filter
Django-filter is a reusable Django application for allowing users to filter queryset dynamically.

django-mingus

https://github.com/montylounge/django-mingus
A Django blog engine leveraging reusable apps for all its features.

django-devserver

https://github.com/dcramer/django-devserver
A drop in replacement for Django’s built-in runserver command. Features include: An extendable interface for handling things such as real-time logging. Integration with the werkzeug interactive debugger. An improved runserver allowing you to process requests simultaneously.

FeinCMS

https://github.com/matthiask/feincms
FeinCMS is an extremely stupid content management system. It knows nothing about content — just enough to create an admin interface for your own page content types. It lets you reorder page content blocks using a drag-drop interface, and you can add as many content blocks to a region (f.e. the sidebar, the main content region or something else which I haven’t thought of yet). It provides helper functions, which provide ordered lists of page content blocks. That’s all.

django-schedule

https://github.com/thauber/django-schedule
A calendaring/scheduling application, featuring: one-time and recurring events, calendar exceptions (occurrences changed or cancelled), occurrences accessible through Event API and Period API, relations of events to generic objects, ready to use, nice user interface, view day, week, month, three months and year and project sample which can be launched immediately and reused in your project.

django-mailer

https://github.com/jtauber/django-mailer
A reusable Django app for queuing the sending of email

django-notification

https://github.com/jtauber/django-notification
Many sites need to notify users when certain events have occurred and to allow
configurable options as to how those notifications are to be received. The project aims to provide a Django app for this sort of functionality. This
includes: submission of notification messages by other apps, notification messages on signing in, notification messages via email (configurable by user) and notification messages via feed.

django-pagination

https://github.com/ericflo/django-pagination
A set of utilities for creating robust pagination tools throughout a django application.

Other not django specific projects that help me with web development

Flask

http://flask.pocoo.org/
Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.

Supervisor

http://supervisord.org/
Supervisor is a client/server system that allows its users to monitor and control a number of processes on UNIX-like operating systems.

Gunicorn

http://gunicorn.org/
Gunicorn ‘Green Unicorn’ is a Python WSGI HTTP Server for UNIX. It’s a pre-fork worker model ported from Ruby’s Unicorn project.

Fabric

http://docs.fabfile.org/en/1.1.1/index.html
Fabric is a Python (2.5 or higher) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.

Thursday 5 May 2016

Interview Questions For Django Developers

Django an open source framework written in Python, was designed to save Web developers time and money by promoting the idea of reusing code and avoiding replication. As with any language, programmers interviewing for a job involving Django are going to face a series of specialized questions. The questions based on my  interview experience 

Questions are:

  1. Tell about Django Framework and working of Django Framework ?
  2. What is ORM ?
  3. Why we call as Django Framework is MVT architecture ?
  4. What is Middleware ? what is Important ? How to write Custom middlewares in Django?
  5. What is role of ALLOWED_HOSTs in Django ?
  6. What is CSRF ?
  7. What is Decorator ? How to Write Custom Decorator ? 
  8. what are built in Decorators in Django ?
  9. What is Template Tags ? How to write custom template tags ? 
  10. what are the built in template tags?
  11. How to inherit the A template in B template ?( template inheritance )
  12. Tell about few packages which you used in your Django career?
  13. Difference between FBV and CBV ?
  14. Difference between Form and Model Form ?
  15. User authentication Django ? where you can find the User(importing) ?
  16. What is Hashing ? difference between hashing and encryption ?
  17. What is __init __ method ?
  18.  What is diff List,Dictionary and Tuple ?( Some times the lead will ask these questions in twice or thrice , they checking the whether you are good in your anwser ?
  19.   What is Message ?
  20. How to Handle Load Management in python ?
  21. What is Memcache ?  what is redis server ? 
  22. What is Scheduling ? the packages which we used ?
  23. what is caching ?
  24. What is South ?
  25. What is Unicode ?
  26. Built in data types in Python ?
  27. Why python is interpreter ?  
  28. Memory management in Python ?
  29. In python Call by reference or Call by value ?
  30. Which version you familiar with in Django ?
  31. What is generater function ?
  32. List comprehensions?
  33. Why we use lamda function ? real time example ?
  34. What is signals  ?
  35. Map function ?
  36. Database ( if PostgreSQL,Mysql study the package name ) ?
  37. NoSql Database ?
  38. Mongodb with django ?
  39. What query set and Instance ?
  40. Difference between value and value_list ?
  41. What is __set method ?
  42. what is __init__method ?
  43. Aggregate and Annotate  ?
  44. What is lambada, where we use lambda ?
  45. How to make a meta list to normal list ?