How to Create an App using Django Framework -Tutorial

Django is an open-source and free web framework written in Python which supports re-usability, scalability, and rapid development. It is extremely developed and comes with high-quality documentation and excellent features incorporated by default.

Owing to the exact reason, Django is an excellent option to develop app as it is packed with robust functionalities.

But learning how to do it is a bit tricky. Let’s tackle that situation once and for all in the easiest way possible.

Prerequisites

First install Django then to set the foundation for our application. We need to create the project skeleton applying the django-admin command. This is as easy as utilizing its admin script. This generated project will be the groundwork of our blog app.

Django-admin startprojecthelloapp

Now cd over to the new folder:

cd ~/sites/dev/djangoblog

This is running to be our project folder in which we will include multiple apps. Some we’ll make and we’ll be downloading projects from Google Code. Keep your Python import statements clean and free of project-specific module names. Ensure your root project folder (in this tutorial, djangoblog) on the Python path. To do that, simply add the path to your PythonPath variable.

phython

We can record statements like:

import myapp

instead of

import myproject.myapp

It makes your code more manageable.

 

Fill out the project settings

Open your preferred text editor and fire up the settings.py file within the “djangoblog” directory.

The core of what we want to set up is found on the top of the file.

Be certain to add the entire pathname, as Django can’t know ~/ or $HOME in determining the database ie /Users/usrname/Sites/dev/djangoblog/djangoblog.db

The additional settings are properly documented in the settings.py file and we can leave most of them. However, there are a few of the settings we should take care of before going further. If you see at the base of the settings.py file you’ll see this piece of code:

INSTALLED_APPS = ( ‘django.contrib.auth’, ‘django.contrib.contenttypes’, ‘django.contrib.sessions’, ‘django.contrib.sites’, )

Here we will tell our Django project which apps to install. First, let’s add Django’s built-in admin tool. Paste this line just under the sites app:

‘django.contrib.admin’,

Here’s a convenient trick for the template directories. Rather than hard-coding the path to our templates directories this is effective – it makes it so easy to change Django utilizing Python. We simply import the os.path Python module and after that discover the way to the directory where settings.py is and afterward adds ‘templates’ to that way.

import os.path TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), ‘layouts’), )

Presently when we launch the site live, there’s no requirement to change the file- settings.py.

Now, how about we utilize one of the tools incorporated into manage.py, the syncdb device. Paste this line in the terminal:

probytes

python manage.pysyncdb

The syncdb tool advises Django to interpret all our installed applications’ models.py documents into a real database table.

Create your username and password, now it’s time to launch the Django’s built-in server.

Start the Sever

At the command prompt, Django starts the server:

/djangoblog/ $ python manage.pyrunserver Validating models… 0 errors found Django version 0.97-pre-SVN-6920, using settings ‘djangoblog.settings’ Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

Then open your browser and head to http://127.0.0.1:8000/.

It works! But then check out the admin interface. Nevertheless, before we do that, we require telling Django what the admin URL is.

Open your text editor and the file urls.py in your “djangoblog” folder. Copy-paste the below-given code, replace what’s already there in the file:

from django.conf.urls.defaults import * from django.contrib import admin # Uncomment the next two lines to enable the admin: # from django.contrib import admin admin.autodiscover() urlpatterns = patterns(”, (r’^admin/(.*)’, admin.site.root), )

Now we’ll head to http://127.0.0.1:8000/admin/. Log in with the user/pass combo you created before.

In any case, right now there isn’t much to find in the admin system, so we should begin developing our blog.

Developing the blog

Presently we could simply toss in some code that makes a title, date field, entry, and different nuts and bolts.

Let’s go onward and create first Django application.

To do this we’ll utilize Django’s app creating script, which is found inside manage.py in our project folder. Paste line below into your shell:

python manage.py startapp blog

If you see inside “djangoblog” you must see a new “blog” folder. Open that and locate the models.py file. Open models.py in your preferred text editor and paste in the below-given code:

from django.db import models from django.contrib.syndication.feeds import Feed from django.contrib.sitemaps import Sitemap import markdown from tagging.fields import TagField from tagging.models import Tag # Create your models here. class Entry(models.Model): title = models.CharField(max_length=200) slug = models.SlugField( unique_for_date=’pub_date’, help_text=’Automatically built from the title.’ ) body_html = models.TextField(blank=True) body_markdown = models.TextField() #note, if you’re using Markdown, include this field, otherwise just go with body_htmlpub_date = models.DateTimeField(‘Date published’) tags = TagField() enable_comments = models.BooleanField(default=True) PUB_STATUS = ( (0, ‘Draft’), (1, ‘Published’), ) status = models.IntegerField(choices=PUB_STATUS, default=0) class Meta: ordering = (‘-pub_date’,) get_latest_by = ‘pub_date’ verbose_name_plural = ‘entries’ def __unicode__(self): return u’%s’ %(self.title) def get_absolute_url(self): return “/%s/%s/” %(self.pub_date.strftime(“%Y/%b/%d”).lower(), self.slug) def save(self): self.body_html = markdown.markdown(self.body_markdown, safe_mode = False) super(Entry, self).save()

First, we import the basic things from django, such as the Feed class, model class, and Sitemap class.

After that, we can create our blog model.

Entry stretches Django’s built-in model.

The first part of our Entry class definition describes all our multiple blog entry elements. Django will utilize this data to build our database tables and structure, and further generate the Admin interface.

Another thing worth noticing is the body_html = models.TextField(blank=True) line. What’s up with that blank=True bit? This information is part of Django’s built-in Admin error checking.

Except you tell it contrarily, all fields in your model will produce NOT NULL columns in your database. To permit for null columns, we would add null=True. But with that Django’s Admin system would yet complain that it requires the information. For that, simply add the blank=True.

But, what we need to do is fill in the body_html field programmatically — after saving in the Admin and prior to Django really writes to the database. Therefore, we want the Admin division to allow body_html to be blank, but not null.

Presently we’ll inform Django about our new apps. Fire up settings.py again and add the below lines to your list of installed apps:

INSTALLED_APPS = ( ‘django.contrib.auth’, ‘django.contrib.contenttypes’, ‘django.contrib.sessions’, ‘django.contrib.sites’, ‘django.contrib.admin’, ‘djangoblog.blog’, )

After that, head to the terminal and run manage.pysyncdb.

Even if Django knows about blog app, we haven’t reported the app what to do in the Admin section.

So, go back to your text editor and make a new file. Name it admin.py and save it within the “blog” folder. And add these lines:

from django.contrib import admin from djangoblog.blog.models import Entry class EntryAdmin(admin.ModelAdmin): list_display = (‘title’, ‘pub_date’,’enable_comments’, ‘status’) search_fields = [‘title’, ‘body_markdown’] list_filter = (‘pub_date’, ‘enable_comments’, ‘status’) prepopulated_fields = {“slug” : (‘title’,)} fieldsets = ( (None, {‘fields’: ((‘title’, ‘status’), ‘body_markdown’, (‘pub_date’, ‘enable_comments’), ‘tags’, ‘slug’)}), ) admin.site.register(Entry, EntryAdmin)

So, what does all that do?

The initial thing to do is import Django’s admin class, as you might doubt, admin regulates how the admin interface seems. Those customizations are completely optional. You could just write pass and run with the default admin layout.

When you refresh your admin page you can now view the blog model with a link to create and write blog entries.

Click “Add new.” Now you’re ready to create some blog entries.

What Is Python? What Is It Useful For?

The world of technology has reached to an advanced level. With a number of innovations taking place frequently, it is certain to say that the day is not far when people would begin to find technology and its aspects much easier to understand. One such example from the present times is related to web development, a skill that enables the development of a website to present information related to a certain concept or related to a company’s products/services under one roof.

 

It is well-known that web development can be done in a number of languages such as C, C++, Java, .Net, etc. While all these languages are quite difficult to understand and gain knowledge even for the developers, Python is one such language that makes this tough task easier for them.

 

Understanding Python

 

Python is an object-oriented web programming language that was created by Guido van Rossum and released in the market in 1991. The language has an easy to understand and simple to use syntax, shorter codes as well as is fun to use, which, in turn, makes it a perfect language for the beginners in computer programming.

 

Python contains a number of third-party modules, which, in turn, makes it capable to interact with many other languages and platform. It also has an extensive support library as well as built-in list and dictionary data structure. With an increased speed and productivity, this language is preferred by the developers for building complex multi-protocol network applications.

phython

Uses of Python

 

An easy to use language, Python can be used in a number of domains and applications. Some of these include:

 

  1. Web and internet development

 

Python is an excellent programming language to develop web and internet-based applications. This is owing to its features such as simple code, ease of use and high speed. Using Python allows one to choose from varied frameworks such as Django, Pyramid; micro-frameworks such as Flask; and advanced content management systems (CMS) such as Plone. Apart from these, its standard library is also able to support several Internet protocols like HTML and XML, JSON and e-mail processing.

  1. Scientific and numeric computing

 

Python holds an important space in scientific and numeric computing. This is owing to its numerous features that support these applications. Some of the exclusive features that support this form of computing are SciPy, which is an assortment of packages for mathematics, science, and engineering; Pandas, a data analysis and modeling library; IPython, an interactive computing used in programming languages that permits one to edit with ease, record a work session as well as supports visualizations and parallel computing.

 

  1. Offering education

 

Since Python is easy to use and understand programming language, this can serve as an excellent option to render education to those at the beginner’s as well as advanced level of programming. Using it will not make programming easier for all but will also make it fun.

 

  1. Creating a multithreaded application

 

Python is an excellent choice to make when opting for a programming language to develop a multithreaded application. Using Python makes it easier to push updates to the devices in a way that allows one machine to serve multiple devices. The language also uses a new form of methodology that has helped in reducing the number of reboots to just one before installation of the new firmware.

 

  1. Gaming applications

 

Gaming software can be developed easily and conveniently using Python. Its libraries such as Tkinter, Pygame and PyOpenGlsimplifies the process of development to a much larger extent. Python’s GUI related features enable one to develop 3D games using 2D graphics, which, in turn, makes the language much more interesting.

 

  1. Documenting large systems

 

The usage of Python as a programming language is not just limited to web applications. It actually has a much wider scope and use. Python, as a programming language can be used to create a compliant environment between multiple applications that are being used to generate documentation for applications. This, in turn, helps in generating those reports that act as a documentation for the entire setup.

probytes

  1. Modifying search engine

 

Python is a versatile language that also allows one to easily modify the search engine to meet the specific goals of a client/customer. The results of the search engine can be altered and then, can be used for the exact needs of the client.

 

The uses of Python are not just limited to these. Instead, the language has established its strong role and presence in other domains as well. This, in turn, has led to a sharp rise in the number of Python based companies in Pune. Since the ultimate goal of every organization is to attain its goal without much hassle, Python must be the option for them.