Question: I'm using django to do a pixel tracker on an email

Is it easy to return an actual image from a django view (and how would this be done?) or is it easier to just return a redirect to the url where the actual image lives?

Answer: 
Since this was the first result on my google search and the best answer is buried in the link by Daniel (but not mentioned as the best), I figured I would just post the answer so nobody is tempted to return a blank response which as a Michael points out is not ideal.

The solution is to use a standard view and return an HttpResponse with the raw data that makes up a single pixel gif. Not having to hit the disk or redirect is a huge advantage.

Note that the url pattern uses the tracking code as the image name so there is no obvious ?code=jf8992jf in the url.

```
from django.conf.urls import patterns, url
from emails.views.pixel import PixelView

urlpatterns = patterns('',
    url(r'^/p/(?P<pixel>\w+).gif$', PixelView.as_view(), name='email_pixel'),
)

```

And here is the view. Note that it uses cache\_control to prevent requests from running wild. Firefox (along with many email clients) for instance will request the image twice every time for some reason you probably don't care about but need to worry about. By adding max\_age=60 you will just get one request per minute.

```
from django.views.decorators.cache import cache_control
from django.http.response import HttpResponse
from django.views.generic import View   

class PixelView(View):

    @cache_control(must_revalidate=True, max_age=60)
    def get(self, request, pixel):
        """
        Tracking pixel for opening an email
        :param request: WSGIRequest
        :param pixel: str
        :return: HttpResponse
        """

        # Do whatever tracking you want here

        # Render the pixel
        pixel_image = b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x01\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b'
        return HttpResponse(pixel_image, content_type='image/gif')

```
Django has a [static file](https://docs.djangoproject.com/en/dev/howto/static-files/) helper that could be used to serve up the image, but it is not recommended because of performance. I believe that having a view that does the bookkeeping to track the pixel, then redirect to a url that [serves the actual image via the webserver](https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-from-a-dedicated-server) is going to give you the best performance.