Django Rest Framework and Forms – Reusing validation logic

Django Rest Framework is great for creating an API. It allows you to quickly create an restful API while still giving you a lot of power. It uses Class based views that you can then extend.

This creates an issue though. You most likely already have an entry point for your data: forms. Your forms probably have validation on them right now. Adding a new entry point will allow users to enter invalid data. Continue reading “Django Rest Framework and Forms – Reusing validation logic”

FormView is Broken (kinda)

Have I dropped enough praise of Two Scoops of Django? You really should buy the book.

I started with Django by going through the tutorial. It is a great tutorial, but I do have one issue with it. It focuses on function based views (FBV). I understand why. It is easier to understand these then the newer class based views (CBV). Because of this I had been using FBV in my projects.

Chapter 7 of Two Scoops of Django really breaks down the difference and the pros and cons of each approach. I have firmly fell into the CBV camp. There are two reason why.

The first is the fact that you write less code. This brings the added benefit of having less code to test. Here is a great example:

 class MyTemplateView(TemplateView):
    template_name = 'template.html'

That is all you need to render a template. It takes one test that checks for the template used and you can move on.

The other benefit I see is the HTTP verbs being broke out. This means no more writing if request.method == ‘POST’. You now have a get, post, put, patch, delete, head, options, and trace. The verb is also the name of the method. This post isn’t about CBVs though.

A Broken FormView

This brings me to my point. The default CBV FormView is broken in Django. FormView throws away all your kwargs that were passed into it. The offending line is 161 in django.views.generic.edit.py:

 return self.render_to_response(self.get_context_data(form=form))

It uses the hook get_context_data, which accepts kwargs, and just passes the form kwarg. If you have overridden get_context_data, FormView will just throw them away. This is not a huge thing, but sometimes you pass in an id of something you need to look up in a kwarg.

I just create a simple class that inherits from FormView and adds back in the kwargs. I feel it is the cleanest, most Django way to get them back. I just override the get and the form_invalid methods.

ALLOWED_HOSTS in settings.py

This is going to be a short post. It deals with a specific issue I just ran into.

I had an old project that I had started. I made the decision to start up development on it again. The project was running Django 1.4.3. There were some sites I had done in 1.5, but I had not migrated a site yet. I jumped into my requirements.txt and changed the line to 1.5.2 the most current stable version of Django.

The migration was not too difficult and I decide to push it to Heroku. After pip installs the updated version of Django I load up the app and I get a 500 status code. I double check my local version and I don’t get the error. I push out a change to make Heroku run DEBUG=True (running the local as DEBUG=False would have been too easy). The site works.

I had not setup any logging as there was not much code, so I setup a quick log to console. I notice that it is complaining about the ALLOWED_HOSTS setting.

Django released a security update in February 2013 for 1.4.4 (just missed it) that requires the ALLOWED_HOSTS to be set if DEBUG=False. All you have to do is set it to your FQDN. I went ahead and set it for my local development site and Heroku.

Hopefully this will save someone some time.

Facebook App ID in Django

Download the src(github)

This is a tale of two app IDs. These app IDs are, more than likely, the ones that you use often. Facebook App ID and Google Analytics. If you have created a site in the last five years or so, you have used these on your site. A common problem with these App IDs is that, you need to have separate IDs based on the environment. Facebook requires a callback domain and will block requests that do not match. I have a localhost app id and then the production app id. So with Google analytics, most likely, you will not track any development traffic.

I will walk you through on how to set them up so they change between environments, without changing any settings. Also, on the two different ways to add variables to the context in Django.

Different Environments, One settings.py

This idea comes from the 12 Factor App config. The 12 factor app is a way of developing an application to minimize differences in deployment. If you have developed a Django app for Heroku, you have followed some of these rules already.

Continue reading “Facebook App ID in Django”

Python, not PHP

The first few posts of this blog dealt with PHP and Zend Framework. I am now leaving PHP behind. I am going to focus on using Python and Django (probably a few others: Flask and web.py look great for small sites) from now on.

This leads to a question: why?

First, I have dabbled in Python and liked it. I had created a few simple Google App Engine sites. I used webapp (an App Engine framework) to build them. Webapp is a very simple framework with which you can easily map the route to a HTTP verb and tell it which function to run. I was able to get something running with very little trouble, despite the fact I knew almost nothing about Python.

Secondly, I have heard many good things about Django. I am always reading blog posts about different frameworks just to see what ideas/methods they have. Django looked great so I decided to use it for a small project I had.

On a side note, the PHP framework Laravel looks great. I have not used it and do not plan to, but if I were to develop something in PHP I would use Laravel.

Was this quick? I believe so. Was it dirty? Certainly not.

Finally a blog post kicked my butt and took every excuse I could make and silenced them – Quick doesn’t have to mean dirty. The author live blogs building a guest book app in Flask. I do not want to be incendiary, but Python just felt more correct. I did not see a need for a lot of boilerplate. There is no web server set-up. I did not have to spend time trying to figure out if you have the correct extensions and correct INI files. I agree with the author by the end: “Was this quick? I believe so. Was it dirty? Certainly not.”

I also have to comment about another post Alex (veekun) wrote. I do not see how this is not incendiary, but here it is: PHP: a fractal of bad design. I have not been able to work on a PHP project since reading this post. I was already moving away from PHP, but I was still using it for a few projects. After reading this I decided to go cold turkey on PHP.

This is not an opening shot to a language flame war. I look forward to posting a lot more Python and Django content.

Google Webmaster or Blitz.io Authentication with Django

This will be just a quick post. Sometimes you have to prove your ownership of a domain. This is true when you sign up for Google Web Master Tools or want to run a test with Blitz.io. Google and Blitz.io give you a long hexadecimal string that you have to respond to from your site.

In the case of Blitz.io they give you a string that needs to respond with ’42’. If you are running django you can do this very quickly and easily. In the main project folder in the urls.py file:

#import HttpResponse
from django.http import HttpResponse

#in the url list add
url(r'^mu-your_hexadecimal_number', lambda r: HttpResponse('42')),

That’s it. I know this kind of breaks separating out views, but this is usually a one time thing. After verifying you can remove this line. I do not really see any sense in creating a view to return two characters.