Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Creating Django App
Django: Django is a high-level Python Web framework that encourages rapid development. Install django in virtualenv to keep it safe from messing around with the other versions you may have. $ virtualenv env $ env/bin/activate $ pip install django If Django is installed, you can see the version of our installation by running following command $ python -c "import django; print(django.get_version())" otherwise you get an error “No module named django” Creating a Project: If this is your first time using Django, you’ll need to auto-generate code that establishes a Django Project A collection of settings, Including database configuration, Django-specific options and application-specific settings. With the following command: $ django-admin.py startproject myproject This will Create "myproject" directory in your current directory.The above command(startproject) creates myproject/ |- manage.py |- myproject/ |- __init__.py |- settings.py |- urls.py |- wsgi.py The outer "myproject/" root directory is where your project is stored. manage.py: It is automatically created in each Django project. manage.py is a thin wrapper around django-admin.py before delegating to django-admin.py.It puts your project’s package on sys.path,Sets the DJANGO_SETTINGS_MODULE … -
django Payu Payment gateway Integration
In this blog, we will see how to integrate Django and PayU Payment Gateway. To integrate with PayU, we have package called "django-payu" - a pluggable Django application. GitHub Repository: django-payu Documentaion: django-payu.readthedocs.org Install: $ pip install django-payu Integration Process: 1. To start the integartion process, you need test merchant account and test credit card credentials to have the experience of overall transaction flow. Once you create the account with PayU, they will provide SALT and KEY, we need this two credentials for the integration. NOTE: Here, you need to make the transaction request to the test-server and not on the production-server. Once you are ready and understood the entire payment flow, you can move to the production server. 2. To initialise the transaction, you need to generate a post request to the below urls with the parameters mentioned below For PayU Test Server: POST URL: https://test.payu.in/_payment For PayU Production (LIVE) Server: POST URL: https://secure.payu.in/_payment Parameters to be posted by Merchant to PayU in transaction request are: key (Mandatory), txnid (Mandatory), amount(Mandatory), productinfo(Mandatory), firstname(Mandatory), email (Mandatory), phone (Mandatory), lastname, udf1-udf5, address1, address2, city, state, country, zipcode, surl(Mandatory), furl(Mandatory), curl(Mandatory), hash(Checksum)(Mandatory): sha512(key|txnid|amount|productinfo|firstname|email| udf1|udf2|udf3|udf4|udf5||||||SALT) NOTE: udf : User defined field … -
Using jsPDF in Django templates to export as PDF
Using jsPDF in Django templates to export as PDF jsPDF is used to generate pdf files in client-side Javascript. You can find the links for jsPDF here and also you can find the link to project homepage. You've to include the scripting files/links in head section to work properly. Tip: We have to download the newest version of the library and include it in the HEAD or at the end of the BODY section. Example to run the script from local storage: In the HEAD section: <head> <script src="js/jspdf.js">script> head> (or) In the BODY section: <body> <script src="js/jspdf.js">script> <script src="js/main.js">script> body> After loading the scripts in HEAD/BODY section, now we can start using the jsPDF library. Lets start with some of basics of jsPDF to get the idea of using it in our applications: First let us discuss how to create a new document? It's simple as below mentioned: var doc = new jsPDF(orientation, unit, format, compress); The constructor can take several parameters. orientation - The default value of orientation is "portrait". We can set it to "landscape" if we want a different page orientation. unit - We can tell jsPDF in which units we want to work. Use on of the following: "pt" (points), … -
Django Haystack and Elasticsearch- part two
Second part of tutorial about django haystack with elasticsearch. -
Django Haystack and Elasticsearch- part two
Hello! This is the second part of Django Haystack and Elasticsearch series. First you can find here. Now it's time to install and elasticsearch. On ubuntu you can do it as follows: 1.First install java-8 $ sudo apt-get install python-software-properties -y $ sudo add-apt-repository ppa:webupd8team/java -y $ sudo apt-get update $ sudo apt-get install oracle-java8-installer -y 2.Verify if it's properly installed $ java -version java version "1.8.0_72" Java(TM) SE Runtime Environment (build 1.8.0_72-b15) Java HotSpot(TM) 64-Bit Server VM (build 25.72-b15, mixed mode) 3.Now install elasticsearch itself $ wget -qO - https://packages.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add - $ echo "deb http://packages.elastic.co/elasticsearch/1.7.5/debian stable main" | sudo tee -a /etc/apt/sources.list.d/elk.list $ sudo apt-get update && sudo apt-get install elasticsearch -y $ sudo service elasticsearch start 4.Verify if elasticsearch is running $ curl http://localhost:9200 { "status" : 200, "name" : "May \"Mayday\" Parker", "cluster_name" : "elasticsearch", "version" : { "number" : "1.7.5", "build_hash" : "00f95f4ffca6de89d68b7ccaf80d148f1f70e4d4", "build_timestamp" : "2016-02-02T09:55:30Z", "build_snapshot" : false, "lucene_version" : "4.10.4" }, "tagline" : "You Know, for Search" } Now it's time to install to more python packages: $ pip install django-haystack==2.4.1 $ pip install elasticsearch After adding them to INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'haystack', … -
Django Haystack and Elasticsearch- part two
Hello! This is the second part of Django Haystack and Elasticsearch series. First you can find here. Now it's time to install and elasticsearch. On ubuntu you can do it as follows: 1.First install java-8 $ sudo apt-get install python-software-properties -y $ sudo add-apt-repository ppa:webupd8team/java -y $ sudo apt-get update $ sudo apt-get install oracle-java8-installer -y 2.Verify if it's properly installed $ java -version java version "1.8.0_72" Java(TM) SE Runtime Environment (build 1.8.0_72-b15) Java HotSpot(TM) 64-Bit Server VM (build 25.72-b15, mixed mode) 3.Now install elasticsearch itself $ wget -qO - https://packages.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add - $ echo "deb http://packages.elastic.co/elasticsearch/1.7.5/debian stable main" | sudo tee -a /etc/apt/sources.list.d/elk.list $ sudo apt-get update && sudo apt-get install elasticsearch -y $ sudo service elasticsearch start 4.Verify if elasticsearch is running $ curl http://localhost:9200 { "status" : 200, "name" : "May \"Mayday\" Parker", "cluster_name" : "elasticsearch", "version" : { "number" : "1.7.5", "build_hash" : "00f95f4ffca6de89d68b7ccaf80d148f1f70e4d4", "build_timestamp" : "2016-02-02T09:55:30Z", "build_snapshot" : false, "lucene_version" : "4.10.4" }, "tagline" : "You Know, for Search" } Now it's time to install to more python packages: $ pip install django-haystack==2.4.1 $ pip install elasticsearch After adding them to INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'haystack', … -
CSV Files - Read and Create
CSV files seem to be what some companies live by. Because of that we need to know how to work with them. In this video learn the basics of using csv reader, writer, DictReader, and DictWriterWatch Now... -
Special Offer for the Readers of DjangoTricks Blog
Packt Publishing, the company that published my Django book, has a special offer for enthusiast and professional developers reading this blog. For two weeks you can get the eBook "Web Development with Django Cookbook - Second Edition" for half price. The eBook is available in PDF, ePub, Mobi, and Kindle formats. Also you will get access to download the related code files. Use the discount code DJGTRK50 at the Packt Publishing bookstore.The discount is valid until the 24th of February, 2016. -
Just one comma
In Django, if you say managed = False in a model's Meta, you tell Django not to touch the database table. So: no automatic database migrations, for instance. Now, what is the problem if you have managed = False, and Django does do migrations? Some of you will have seen the error already. The comma after False is the problem: >>> a = False, >>> a (False,) >>> bool(a) True The comma turns it into a tuple. And a non-empty tuple evaluates to True! I found it quite funny. My colleague was torn between "extremely relieved" and "extremely annoyed" :-) -
Wagtail and Streamfields
Django was always great for developers out of the box, but creating friendly admin interfaces was always a little too much work. This post explains why I now consider using Wagtail to make this task easier. -
Wagtail and Streamfields
Django was always great for developers out of the box, but creating friendly admin interfaces was always a little too much work. This post explains why I now consider using Wagtail to make this task easier. -
Wagtail and Streamfields
Django was always great for developers out of the box, but creating friendly admin interfaces was always a little too much work. This post explains why I now consider using Wagtail to make this task easier. -
Fresh Book for Developers Working with Django 1.8
This week the post office delivered a package that made me very satisfied. It was a box with three paper versions of my "Web Development with Django Cookbook - Second Edition". The book was published at the end of January after months of hard, but fulfilling work in the late evenings and on weekends. The first Django Cookbook was dealing with Django 1.6. Unfortunately, the support for that version is over. So it made sense to write an update for a newer Django version. The second edition was adapted for Django 1.8 which has a long-term support until April 2018 or later. This edition introduces new features added to Django 1.7 and Django 1.8, such as database migrations, QuerySet expressions, or System Check Framework. Most concepts in this new book should also be working with Django 1.9. My top 5 favourite new recipes are these: Configuring settings for development, testing, staging, and production environments Using database query expressions Implementing a multilingual search with Haystack Testing pages with Selenium Releasing a reusable Django app The book is worth reading for any Django developer, but will be best understood by those who already know the basics of web development with Django. You … -
Django Haystack and Elasticsearch- part one
Hello! Today blog post is about Django Haystack and how to integrate it quickly with Elasticsearch. First after creating django project (At beginning of 2016 django-haystack don't work properly with django 1.9 so I used 1.8.9 version) and making new app let's add models: from django.db import models GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female') ) class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) email = models.CharField(max_length=100) ip_address = models.CharField(max_length=100) def __str__(self): return '{first_name} {last_name}'.format(first_name=self.first_name, last_name=self.last_name) And register model to the admin site. Don't forget about adding created app to settings.py and making manage.py makemigrations and manage.py migrate after it: from django.contrib import admin from .models import Person admin.site.register(Person) Then create simple script wich will load a data from JSON to the database. This JSON data is randomly generated data from this webpage. Call it load.py and place in your django application folder. # coding=utf-8 import os import json from .models import Person DATA_FILE = os.path.join( os.path.dirname( os.path.dirname( os.path.dirname(__file__))), 'MOCK_DATA.json' ) def run(verbose=True): with open(DATA_FILE) as data_file: data = json.load(data_file) for record in data: Person.objects.create( first_name=record['first_name'], last_name=record['last_name'], gender=record['gender'], email=record['email'], ip_address=record['ip_address']) print(record) This script looks for file MOCK_DATA.json. Then based on fields on this JSON loads data … -
Django Haystack and Elasticsearch- part one
Hello! Today blog post is about Django Haystack and how to integrate it quickly with Elasticsearch. First after creating django project (At beginning of 2016 django-haystack don't work properly with django 1.9 so I used 1.8.9 version) and making new app let's add models: from django.db import models GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female') ) class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) email = models.CharField(max_length=100) ip_address = models.CharField(max_length=100) def __str__(self): return '{first_name} {last_name}'.format(first_name=self.first_name, last_name=self.last_name) And register model to the admin site. Don't forget about adding created app to settings.py and making manage.py makemigrations and manage.py migrate after it: from django.contrib import admin from .models import Person admin.site.register(Person) Then create simple script wich will load a data from JSON to the database. This JSON data is randomly generated data from this webpage. Call it load.py and place in your django application folder. # coding=utf-8 import os import json from .models import Person DATA_FILE = os.path.join( os.path.dirname( os.path.dirname( os.path.dirname(__file__))), 'MOCK_DATA.json' ) def run(verbose=True): with open(DATA_FILE) as data_file: data = json.load(data_file) for record in data: Person.objects.create( first_name=record['first_name'], last_name=record['last_name'], gender=record['gender'], email=record['email'], ip_address=record['ip_address']) print(record) This script looks for file MOCK_DATA.json. Then based on fields on this JSON loads data … -
Django Haystack and Elasticsearch- part one
First part of tutorial about django haystack with elasticsearch. -
How to no-mincss links with django-pipeline
This might be the kind of problem only I have, but I thought I'd share in case others are in a similar pickle. Warming Up First of all, the way my personal site works is that every rendered page gets cached as rendered HTML. Midway, storing the rendered page in the cache, an optimization transformation happens. It basically takes HTML like this: <html> <link rel="stylesheet" href="vendor.css"> <link rel="stylesheet" href="stuff.css"> <body>...</body> </html> into this: <html> <style> /* optimized contents of vendor.css and stuff.css minified */ </style> <body>...</body> </html> Just right-click and "View Page Source" and you'll see. When it does this it also filters out CSS selectors in those .css files that aren't actually used in the rendered HTML. This makes the inlined CSS much smaller. Especially since so much of the CSS comes from a CSS framework. However, there are certain .css files that have references to selectors that aren't in the generated HTML but are needed later when some JavaScript changes the DOM based on AJAX or user actions. For example, the CSS used by the Autocompeter widget. The program that does this CSS optimization transformation is called mincss and it has a feature where you can tell it … -
How to no-mincss links with django-pipeline
This might be the kind of problem only I have, but I thought I'd share in case others are in a similar pickle. Warming Up First of all, the way my personal site works is that every rendered page gets cached as rendered HTML. Midway, storing the rendered page in the cache, an optimization transformation happens. It basically takes HTML like this: <html> <link rel="stylesheet" href="vendor.css"> <link rel="stylesheet" href="stuff.css"> <body>...</body> </html> into this: <html> <style> /* optimized contents of vendor.css and stuff.css minified */ </style> <body>...</body> </html> Just right-click and "View Page Source" and you'll see. When it does this it also filters out CSS selectors in those .css files that aren't actually used in the rendered HTML. This makes the inlined CSS much smaller. Especially since so much of the CSS comes from a CSS framework. However, there are certain .css files that have references to selectors that aren't in the generated HTML but are needed later when some JavaScript changes the DOM based on AJAX or user actions. For example, the CSS used by the Autocompeter widget. The program that does this CSS optimization transformation is called mincss and it has a feature where you can tell it … -
Writing Unit Tests for Django Migrations
Editor's note: This post was originally published in February 2016 and was updated in August 2017 to incorporate improvements suggested by our readers. It has also been tested for compatibility as of the Django 1.11 release. -
Django Trees via Closure View
After writing up a method of using a Postgres View that generates a materialised path within the context of a Django model, I came across some queries of my data that were getting rather troublesome to write. It occurred to me that having a closure table would be useful. Specifically, I needed all of the descendants of a given set of nodes. I couldn't find an existing Postgres extension that will manage the closure table, and didn't feel like writing my own implemention using triggers just yet. However, it occurred to me that I could use a similar trick to the recursive materialised path view. Thus, we have a Closure View. We will start with the Django models: {% highlight python %} class Node(models.Model): node_id = models.AutoField(primary_key=True) parent = models.ForeignKey('tree.Node', related_name='children', null=True, blank=True) descendants = models.ManyToManyField('tree.Node', related_name='ancestors', through='tree.Closure') class Meta: app_label = 'tree' class Closure(models.Model): path = ArrayField(base_field=models.IntegerField(), primary_key=True) ancestor = models.ForeignKey('tree.Node', related_name='+') descendant = models.ForeignKey('tree.Node', related_name='+') depth = models.IntegerField() class Meta: app_label = 'tree' managed = False {% endhighlight %} You may notice I have a `path` column. I'm using this for the primary key, and it may turn out to be useful later. Let's have a look at … -
Django Model Inheritance - Multi-Table Inheritance
In the last post we talked about Model Inheritance with regards to Abstract Model Classes, it was a great introduction into using OOP with your models to keep your code slim and tidy. You can read it at: Django Abstract Base Class - Model Inheritance In this post we are going to discuss Multi-Table Inheritance. We will create a base model, that is not an abstract model, and inherit from the model. Then we are going to show you how to get and reference data from that models inheritance. Multi Table Inheritance When we talk about multi-table inheritance we are referring to having a top level table with all the fields that are core to that context. Then we are going to have other tables with the more specific fields. You select from the table you want, and then do a join on a relationship to get the parent table data. Since Django does this through models and code, we will talk about it in those terms. In our example we are going to have a Ticket Model. class Ticket(models.Model): title = models.CharField(max_length=255, blank=True) description = models.TextField(blank=True) name = models.CharField(max_length=255, blank=True) This model is a good piece of code because … -
ShipIt Day Recap: Q1 2016
Last Friday, the Cakti set aside regular client projects for our quarterly ShipIt Day, a chance for personal development and independent projects. People work individually or in groups to flex their creativity, tackle interesting problems, or expand their personal knowledge. This quarter’s ShipIt Day saw everything from cat animations to improvements on our Taylor Swift lyric generator app. Read about the various ShipIt Day projects for Q1 of 2016 below. -
10 Popular Websites Built With Django
What is the framework Regardless of the sphere you work in, one of your most important tasks is to create a fast, good-looking website. Today, almost every business needs a website, which acts as a sort of business card for a company or online service. It helps you engage with customers, promote your business, increase sales and so on. In every case, the website should be fast, scalable and dynamic. When creating a website, you typically need to work with roughly the same set of basic components: ways to manage user authorizations (account creation, login); a user dashboard; file downloading and uploading, etc. If the tasks are the same, why not make them easier, and thereby reduce the cost of development? With this in mind, web frameworks appeared on the scene as a set of components designed to facilitate and simplify website creation. Django Advantages This web framework is intended to create highly scalable web applications or websites with a constantly growing audience (e.g. content-based or news sites). Django perfectly works as is and provides users with a range of options to create Python-based web-applications including a user dashboard, various database supports (SQLite, PostgresSQL, MySQL), admin functions, and more. Famous … -
hasattr() Considered Harmful
Don’t use Python hasattr() unless you want its quirks or are writing Python 3-only code. -
Django CMS Plugin Authenticated User Variations
Django CMS Plugin Authenticated User Variations