Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django + Celery & Rabbit - part three
Third part of series about Django application with Celery and RabbitMQ. -
Recommended Django libraries
My two favorite things about Django are Python and the quality of the plugins (which reflects on the quality of Django itself and its community). Here is my personal top 5 of the most useful Django libraries. -
[Django Tips] Make Deleting Easy In Admin!
Lets say we have a model as shown in some project.from django.db import modelsclass Resource(models.Model): """ Model to hold resources for books. """ book = models.ForeignKey('Book') book_type = models.IntegerField() url = models.URLField()This model can be registered in admin as follows.from django.contrib import adminfrom . import modelsclass ResourceAdmin(admin.ModelAdmin): list_display = ('book', 'book_type', 'url')admin.site.register(models.Resource, ResourceAdmin)This will generate a nice admin interface to modify the data.Now if we want to delete a record, we need to follow these steps.First, we have to select that recordNext, we have to click on the action dropdownNext, we have to select delete actionNext, we have to click Go button.In the next page we have to confirm that we have to delete.Just to delete a single record, we have to click 5 times. That's too many clicks for a single action.To simplify the process, we can have simple delete button for the objects as shown. This can be achieved by writing a function which will insert delete button for every record.from django.contrib import adminfrom . import modelsclass ResourceAdmin(admin.ModelAdmin): def delete(self, obj): return '<input type="button" value="Delete" onclick="location.href=\'%s/delete/\'" />'.format(obj.pk) delete.allow_tags = True delete.short_description = 'Delete object' list_display = ('book', 'book_type', 'url', 'delete')admin.site.register(models.Book)Now we have an admin with delete button for the records.To delete an object, just … -
Django Class-Based Views: The Basics
Django Class-Based Views: The Basics -
Django Tips & Tricks #6 - Make Deleting Easy In Admin
Lets say we have a model as shown in some project.from django.db import modelsclass Resource(models.Model): """ Model to hold resources for books. """ book = models.ForeignKey('Book') book_type = models.IntegerField() url = models.URLField()This model can be registered in admin as follows.from django.contrib import adminfrom . import modelsclass ResourceAdmin(admin.ModelAdmin): list_display = ('book', 'book_type', 'url')admin.site.register(models.Resource, ResourceAdmin)This will generate a nice admin interface to modify the data.Now if we want to delete a record, we need to follow these steps.First, we have to select that recordNext, we have to click on the action dropdownNext, we have to select delete actionNext, we have to click Go button.In the next page we have to confirm that we have to delete.Just to delete a single record, we have to click 5 times. That's too many clicks for a single action.To simplify the process, we can have simple delete button for the objects as shown. This can be achieved by writing a function which will insert delete button for every record.from django.contrib import adminfrom . import modelsclass ResourceAdmin(admin.ModelAdmin): def delete(self, obj): return '<input type="button" value="Delete" onclick="location.href=\'%s/delete/\'" />'.format(obj.pk) delete.allow_tags = True delete.short_description = 'Delete object' list_display = ('book', 'book_type', 'url', 'delete')admin.site.register(models.Book)Now we have an admin with delete button for … -
Django + Celery & Rabbit - part two
Hello, today post is the second one in series about Celery in Django. Today I write about ffmpeg. In my application transcoding will be performed by ffmpeg. Why is that? First of all, it's free & open source. So I don't have to pay to use it and I like using the open source tools. Second thing is that ffmpeg is more than enough for my task. It has a lot of features including recording, streaming and transcoding both video and audio. So how to use it? For this project, the ffmpeg needs to be compiled with libmp3lame for mp3 files encoding, libvorbis for ogg format and enabled non-free for ac3. There is guide on ffmpeg site how to compile ffmpeg build. Also, make sure that you have cookies and tea with you while installation can take even 30 minutes. After everything is setup all you need to do is: $ ffmpeg -i mp3_file.mp3 wav_file.wav $ ffmpeg -i mp3_file.mp3 ogg_file.ogg $ ffmpeg -i mp3_file.mp3 ac3_file.ac3 The code above will transcode mp3 files into provided format. In my application one celery task will be called with subprocess, then another celery task will save the output of the first task to django … -
Django + Celery & Rabbit - part two
Hello, today post is the second one in series about Celery in Django. Today I write about ffmpeg. In my application transcoding will be performed by ffmpeg. Why is that? First of all, it's free & open source. So I don't have to pay to use it and I like using the open source tools. Second thing is that ffmpeg is more than enough for my task. It has a lot of features including recording, streaming and transcoding both video and audio. So how to use it? For this project, the ffmpeg needs to be compiled with libmp3lame for mp3 files encoding, libvorbis for ogg format and enabled non-free for ac3. There is guide on ffmpeg site how to compile ffmpeg build. Also, make sure that you have cookies and tea with you while installation can take even 30 minutes. After everything is setup all you need to do is: $ ffmpeg -i mp3_file.mp3 wav_file.wav $ ffmpeg -i mp3_file.mp3 ogg_file.ogg $ ffmpeg -i mp3_file.mp3 ac3_file.ac3 The code above will transcode mp3 files into provided format. In my application one celery task will be called with subprocess, then another celery task will save the output of the first task to django … -
Django + Celery & Rabbit - part two
Second part of series about Django application with Celery and RabbitMQ. -
Class Based Views: The Basics
Class Based Views: The Basics -
Google plus API integration with django
Using GPlus integration by Django, we can get the user verified email id, general information, friends in a less span of time, and user can also share articles. These Following steps are needed for GPlus integration: 1. creating google app 2. Authenticating user and getting access token. 3. Get user information using access token. 4. Get user friends list. 1. Creating Google App a. To create an app, click on click on create a project on top of a page. Here you can give application name, then the project will be created. b. In order to create client id, secret, we must enter our Application Details(app name, home page URL, logo URL, privacy url, terms and service URL), Application Type Redirected URLs. c. Now to get client id, secret click on menu icon on left side of the page, then select API Manager --> Credentials. d. Click on New credentials to create OAuth client ID to access users data. Here We can also create other keys like API key for using google maps. 2. Authenticating user and getting access token. a. Here We have to create a GET request for … -
Integrating Gitlab in django project with gitlab api to for gitlab authentication and access
This is a simple way to integrate gitlab authentication in your django apps. We can get user verified email id, general information, git lab URL and token from Gitlab API. These Following steps are needed for Gitlab integration: 1. creating git lab app 2. Authenticating user and getting an access token. 3. Get user information, git lab URL using an access token. 1. Creating Gitlab App a. To create an app, Go to your profile and click on applications then create an application on top of a page. Here you can give your application name, redirect URLs then the application will be created. b. Now you can get the client id, secret of an application 2. Authenticating user and getting an access token. a. Here We have to create a GET request for asking user permission. GET "http://{{Your GIT_LAB_DOMAIN }}/oauth/authorize?client_id={{ Your GIT_LAB_APP_ID }} &redirect_uri={{ redirect_uri }}&response_type=code" GIT_LAB_DOMAIN: your git lab domain, GIT_LAB_APP_ID: your application client id, REDIRECT_URI: The URL which … -
Sendgrid Inbound Email Parsing with django
Using the Inbound parse webhook, we can parse the contents, attachments of an incoming email. Inbound Parse API follows 3 steps: 1. sending an email to the mail id(URL_Name@your specified domain/sub domain.com) a Here the domain/ sub domain, where the emails will be sent, and the URL_Name, where we will handle the contents, attachments of an incoming email in our app. b. Here the domain/sub domain should point out the MX record to mx.sendgrid.net. Here http://mxtoolbox.com/ you can check weather your domain/ sub domain is having MX record or not. c. we should add domain/ sub domain, URL to our inbound parse webhook settings list. For ex: domain: reports.micropyramid.com url: https://micropyramid.com/reports/ mail id: reports@reports.micropyramid.com 2. Sendgrid parses the content and attachments of an email and sends the information to the specified URL of your application. 3. You can receive the JSON post response to your application envelope = request.POST.get('envelope') my_dict = literal_eval(envelope) You can get … -
How to index binary files in django haystack
Now we are going to index text content which is stored in structured files such as PDFs, Microsoft Office documents, images, etc using haystack and sorl's In order to read and store the data, we can use SearchBackend.extract_file_contents(self, file_obj) method. It takes the file object, returns a dictionary containing two keys: metadata and contents. The contents value will be a string containing all of the text which the backend managed to extract the file contents. Here we are overriding NewsIndex prepare method to include the extracted content along with information retrieved from the database: class NewsIndex(indexes.SearchIndex, indexes.Indexable): text = CharField(document=True, use_template=True, analyzer='synonym_analyzer') content = indexes.CharField(model_attr='content') def prepare(self, obj): data = super(NewsIndex, self).prepare(obj) file_data = self._get_backend(None).extract_file_contents(obj.new_file) template = loader.select_template( ("search/indexes/proj/new_text.txt", ), ) data["text"] = template.render(Context({ "object": obj, "file_data": var, })) return data This allows you to insert the extracted text at the appropriate place in your template, {{ file_data.contents|striptags|safe }} To … -
Extract data from PDF and all Microsoft Office files in python
We will see how to extract text from PDF and all Microsoft Office files. Generating OCR for PDF: The quick way to get/extract text from PDFs in Python is with the Python library "slate". Slate is a Python package that simplifies the process of extracting text. Installation: $ pip install slate $ pip install pdfminer Usage: import slate with open('sample.pdf', 'rb') as f: pdf_text = slate.PDF(f) print pdf_text Output: ['Sample text...', '......', '......'] * The PDF class, of slate, takes file-like object and extracts all the text from the PDF file. It provides the output as a list of strings(one for each page). * NOTE: If the PDF file has password, then pass the password as second parameter. Example: import slate with open('test_doc.pdf', 'rb') as f: pdf_text = slate.PDF(f, "pass the PDF file password here") print pdf_text Output: ['Sample text...', '......', '......'] -
Integration Of Linkedin API in python django
Using Linkedin integration by Django, we can get the user verified email id, general information, work history in a less span of time, and a user can also share articles. These Following steps are needed for Linkedin integration: 1. creating LinkedIn app 2. Authenticating user and getting an access token. 3. Get user information, work history using access token. 1. Creating Linkedin App a. To create an app, click on create an application on top of a page(https://www.linkedin.com/developer/apps). Here you can give application name, description, logo, email, website url, then the application will be created. b. Now you can get the client id, secret of an application and you can select application permission like basic profile, email address, company admin, can share an article. 2. Authenticating user and getting an access token. a. Here We have to create a GET request for asking user permission. GET "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=LN_API_KEY&scope=r_basicprofile r_emailaddress rw_company_adminw_share&state=8897239179ramya&redirect_uri=Redirect_URL" LN_API_KEY: your application client id, SCOPE: List of permissions to request from the person using your app REDIRECT_URI: The URL which you want to redirect after user login b. If a user accepts the permissions, then authorization code send to redirected url. c. Then … -
How to customize Django Oscar Models, Views and URL's
In order to customize models, views and urls, you need to fork an Oscar core app in which model/view resides. Then you should be able to override any model/view classes. Steps to fork/customize an app: 1. If you are forking an Oscar app for the first time, then you have to create a root apps-folder in which all your forked apps will exists: $ mkdir yourappsfolder $ touch yourappsfolder/__init__.py 2. Create a python module with the same 'app-label' as the Oscar app: Ex: Customising oscar.apps.catalogue app $ mkdir yourappsfolder/catalogue $ touch yourappsfolder/catalogue/__init__.py 3. If the Oscar app has a models.py, then you have to create a models.py file in your local app. # your custom models go here from oscar.apps.catalogue.models import * NOTE: To customise Oscar’s models, you must add your custom one before importing Oscar’s models. Then, your models file will have two models with the same name within an app, Django will only use the first one. Ex: To add a active field to the product model: # yourappsfolder/catalogue/models.py from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): active … -
Django Custom Template Tags And Filters
Django Template Tags are simple Python functions which accepts a 1 or more value, an optional argument, process those values and return a value to be displayed on the page. First, In your application folder, create a "templatetags" directory at the same level as the models and views. You want this directory to be recognized as a Python package, so make sure you create an empty "__init__.py" file. Next, create the Python file that will hold your tags and name it something like app_tags.py. Here is the folder structure should look like: Django Project -> my_app ---> models.py ---> views.py ---> templatetags -----> __init__.py -----> app_tags.py Tags: Tags look like this: {% tag %}. Tags can be used to create text in the output, control flow by performing loops or logic, and to load external information into the template. Tags require beginning and ending tags (i.e. {% tag %} ... tag contents ... {% endtag %}). Django provides about twenty built-in template tags. Here are some of the more commonly used tags for - Loop over each item in an array. if, elif, and else - Evaluates … -
Export html web page to pdf using jspdf
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: (or) In the BODY section: 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), "mm" (default), "cm", "in". format - It's default page format. We … -
Understanding django serializers with examples
Using Serializers, we can translate Django model objects into other formats like XML, JSON, YAML(YAML Ain’t a Markup Language) with a single command. from django.core import serializers data = serializers.serialize("xml", SomeModel.objects.all()) the first argument will be the format we want to serialize the data and second will be a QuerySet to serialize. we can also translate using a serializer object directly XMLSerializer = serializers.get_serializer("xml") xml_serializer = XMLSerializer() xml_serializer.serialize(queryset) data = xml_serializer.getvalue() this is useful when we want data directly be a file like object. we can also translate only subset of fields using fields argument from django.core import serializers data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size')) class Teacher(models.Model): name = models.CharField(max_length=50) qualification = models.CharField(max_length=50) class College(Teacher): name = models.models.CharField(max_length=50) for the inherited models,to translate child class objects we have to list all parent class objects and child class objects into single list,then translate. all_objects = list(Teacher.objects.all()) + list(College.objects.all()) data = serializers.serialize('xml', all_objects) Deserializing data: for obj in serializers.deserialize("xml", data): do_something_with(obj) it will take same arguments as serialize function and returns an iterator The objects returned by the deserialize iterator are unsavedobjects and Calling DeserializedObject.save() saves the object to the database. for deserialized_object in serializers.deserialize("xml", data): … -
Custom Decorators To Check User Roles And Permissions In Django
A decorator is a function that takes another function and returns a newer, prettier version of that function. To know more about decorators in python see here https://micropyramid.com/blog/programming-with-python-decorators/ The most common use of a decorator is the login_required, which is used in conjunction with a Django view that restricts access to authenticated users only. from django.contrib.auth.decorators import login_required @login_required(login_url='/dashboard/') def index(request): return render(request, 'index.html') This decorator is very useful because we don’t have to actually change anything about my view to restrict access to it. login required takes an optional argument login_url. If a user is authenticated, it successfully executes the function, if not it redirects the users to URL specified in the login_url option. If we don't mention login_url option, we must define login_url in settings.py But the login_required decorator does not check when the logged in user is active or not. We can use the "user_passes_test" decorator to write our own custom decorators from django.contrib.auth.decorators import login_required, user_passes_test user_login_required = user_passes_test(lambda user: user.is_active, login_url='/') def active_user_required(view_func): decorated_view_func = login_required(user_login_required(view_func)) return decorated_view_func @active_user_required def index(request): return render(request, 'index.html') Here user_passes_test decorator returns the value of is_active, which is a boolean that … -
Django Custom Management Command
In Django project, We could manage by executing some commands which could be invoked through the manage.py. For example: # Start the webserver python manage.py runserver Management Command is used to create our own actions with manage.py. If your app is in projectdirectory then create the directories projectdirectory/app/management/commands. Create an empty file called __init__.py in both the management and commands directories. This will make that every other python file in the commands directory can be executed via manage.py command. If you create the file project/app/management/commands/management_command.py. Django will register a manage.py command for each Python module in that directory whose name doesn’t begin with an underscore, then it can be run as manage.py management_command. In the app which the command is used for make the following directory structure: management/ __init__.py commands/ __init__.py your_command_name.py from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.core.management import call_command import json class Command(BaseCommand): args = '' help = 'Loads the initial data in to database' def handle(self, *args, **options): # Your Code call_command('loaddata', 'peeldb/fixtures/countries.json', verbosity=0) … -
Integration of 2checkout with django
Integration of payment gateways is an important part of developing an e-commerce application which includes communication with several banks with different ways online banking/debit credit cards. and also providing security is the most important feature for all payment gateways integration. We are having payment gateways like paypal,braintree,payumoney,2checkout... In this post,we will see how to integrate 2checkout with our django application. To integrate it to the application,it offers 3 different integration methods. 1.inline checkout In inline chekout,we displays a secure payment form as an overlay on your checkout page. .It collects the buyers's billing/shipping address and finalize the cart total sum the function of inline checkout is same as standard checkout, but when the required parameter is missing(buyer's name,email address and billing address),it willredirect to the standard checkout. To know about request parameters, and response please refer to https://www.2checkout.com/documentation/checkout/inline-checkout 2.standard checkout It can handle every part of the buyer’s checkout process on a single page. You can customize the whole checkout process to your needs by passing user billing/shipping information details, currency details, language and checkout steps. To know about request parameters, and response please refer to https://www.2checkout.com/documentation/checkout/standard-checkout 3.Payment Api In payment api,we are taking the credit card information … -
Mercurial Mirror For Django 1.9 branch
I forgot to mention it, but I’ve created the 1.9 “production” mirror at the usual location: As a reminder, those mirrors have two purposes: be a lightweight read-only repository to clone from for production servers hide the ugly git stuff behind a great mercurial interface The clone is at the usual location at bitbucket, from which […] -
Django + Celery & Rabbit - part one
Hello, today post is first one in series about Celery in Django application and how to use it. What you gain after reading such series? How to integrate celery + rabbitmq in basic Django application. So what will be our basic application? It is planned to be web service where you can upload mp3 file and then have them transcoded into ogg, wav and ac3 files. I wanted to make easy and in the same time sophisticated project. Recently I started reading an excellent book called Two Scoops of Django: Best Practices for Django 1.8. The book is about what to do and what not to do for your Django project. I feel some opportunity to try advice from the book in real project. I will start from project layout: normally you have something like this: $ tree trancoder trancoder ├── audiotranscoder │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── trancoder ├── manage.py └── trancoder ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py But in the book authors suggest that it can be changed to something like this: $ tree transcoder transcoder … -
Django + Celery & Rabbit - part one
Hello, today post is first one in series about Celery in Django application and how to use it. What you gain after reading such series? How to integrate celery + rabbitmq in basic Django application. So what will be our basic application? It is planned to be web service where you can upload mp3 file and then have them transcoded into ogg, wav and ac3 files. I wanted to make easy and in the same time sophisticated project. Recently I started reading an excellent book called Two Scoops of Django: Best Practices for Django 1.8. The book is about what to do and what not to do for your Django project. I feel some opportunity to try advice from the book in real project. I will start from project layout: normally you have something like this: $ tree trancoder trancoder ├── audiotranscoder │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── trancoder ├── manage.py └── trancoder ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py But in the book authors suggest that it can be changed to something like this: $ tree transcoder transcoder …