Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Understanding 'GenericForeignKey' in Django
In some cases we might want to store generic model object, rather a particular specific model as 'ForeignKey'. Here is the scenario of such kind. Suppose there are models like User, Project, Ticket and TimeLine as below. class Ticket(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Project(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class User(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Timeline(models.Model): involved_object = ***** event_type = models.CharField(max_length=250, default="created") If we want to store the user activities with these models like "created User, created Project, created Task" in a timeline, we have to create all the three models(User, Project, Task) as 'ForeignKey' fields. This is not a good programming practice. To overcome this, Django's content types framework provides a special field type (GenericForeignKey) which allows the relationship to be with any model. Using 'GenericForeignKey': Here is the solution for the above scenario. There are three parts to setting up a GenericForeignKey: Give your model a ForeignKey to ContentType. The usual name for this field is “content_type”. Give your model a field that can store primary key values from the models you’ll be relating to. For … -
Understanding 'GenericForeignKey' in Django
In some cases the we might want to store generic model object, rather a particular specific model as 'ForeignKey'. Here is scenario of such kind. Suppose there are models like User, Project, Ticket and TimeLine as below. class Ticket(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Project(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class User(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Timeline(models.Model): involved_object = ***** event_type = models.CharField(max_length=250, default="created") If we want to store the user activities with these models like "created User, created Project, created Task" in time line, we have to create all the three models(User, Project, Task) as 'ForeignKey' fields. This is not a good programming practice. To overcome this, Django's contenttypes framework provides a special field type (GenericForeignKey) which allows the relationship to be with any model. Using 'GenericForeignKey' : Here is the solution for the above scenario. There are three parts to setting up a GenericForeignKey: Give your model a ForeignKey to ContentType. The usual name for this field is “content_type”. Give your model a field that can store primary key values from the models you’ll be relating to. For … -
Using Unsaved Related Models for Sample Data in Django 1.8
Note: In between the time I originally wrote this post and it getting published, a ticket and pull request were opened in Django to remove allow_unsaved_instance_assignment and move validation to the model save() method, which makes much more sense anyways. It's likely this will even be backported to Django 1.8.4. So, if you're using a version of Django that doesn't require this, hopefully you'll never stumble across this post in the first place! If this is still an issue for you, here's the original post: -
PyCon 2015 Workshop Video: Building SMS Applications with Django
As proud sponsors of PyCon, we hosted a one and a half hour free workshop. We see the workshops as a wonderful opportunity to share some practical, hands-on experience in our area of expertise: building applications in Django. In addition, it’s a way to give back to the open source community. -
Reviews of two recent Django Books
Introduction When I started building sites in Django, I learned the basics from the excellent Django tutorial. But I had to learn by trial and error which approaches to using Django’s building blocks worked well and which approaches tended to cause problems later on. I looked for more intermediate-level documentation, but beyond James Bennett’s Practical Django Projects and our Karen Tracey’s Django 1.1 Testing and Debugging, there wasn’t much to be found. -
Django and Python 3 How to Setup pyenv for Multiple Pythons
We need to be doing Django development in Python 3. Unfortunately, we have a lot of projects still in Python 2.7 so switching between the 2 versions can be frustrating. Fortunately pyenv takes the guess work out of switching, and makes it super simple.Watch Now... -
Testing Django Views Without Using the Test Client
Testing Django Views Without Using the Test Client -
[Django Tips] Make Django Development Server Persistent.
I use Emacs for writing Python code. I also use real-auto-save to save my files after 10 seconds of inactivity.While coding, when I stop writing in the middle, after 10 seconds Emacs auto saves the file. Django recognizes this & reloads the development server.Once I complete writing code, I go to browser & refresh the page. Since the code I was writing was incomplete somewhere in the middle and had some errors, Django development server was stopped and page won't reload. Now I have to go back to terminal and restart the server and again go back to browser to refresh page.To overcome this, Django server must be made persistent. The easiest way to accomplish this is to use a simple bash script as described here.$ while true; do python manage.py runserver; sleep 4; doneWhen Django development server stops, after 4 seconds it tries to start automatically and goes on forever.Instead of typing that everytime, it better to write this as a shell script and put it in system path, so that it can be used in any project.while true; do echo "Re-starting Django runserver" python manage.py runserver sleep 4doneSave this & make it executable(chmod +x), use it is ./filename.sh and to stop … -
The uWSGI Swiss Army Knife
uWSGI is one of those interesting projects that keeps adding features with every new release without becoming totally bloated, slow, and/or unstable. In this post, we'll look at some of its lesser used features and how you might use them to simplify your Python web service. Let's start by looking at a common Python web project's deployment stack. Nginx: Static file serving, SSL termination, reverse proxy Memcached: Caching Celery: Background task runner Redis or RabbitMQ: Queue for Celery uWSGI: Python WSGI server Five services. That's a lot of machinery to run for a basic site. Let's see how uWSGI can help you simplify things: Static File Serving uWSGI can serve static files quite efficiently. It can even do so without tying up the same worker/thread pool your application uses thanks to it's offloading subsystem. There are a bunch of configuration options around static files, but the common ones we use are: offload-threads the number of threads to dedicate to serving static files check-static this works like Nginx's @tryfiles directive, checking for the existence of a static file before hitting the Python application static-map does the same, but only when a URL pattern is matched Other options exist to allow you … -
Django Tips & Tricks #4 - Make Django Development Server Persistent
I use Emacs for writing Python code. I also use real-auto-save to save my files after 10 seconds of inactivity.While coding, when I stop writing in the middle, after 10 seconds Emacs auto saves the file. Django recognizes this & reloads the development server.Once I complete writing code, I go to browser & refresh the page. Since the code I was writing was incomplete somewhere in the middle and had some errors, Django development server was stopped and page won't reload. Now I have to go back to terminal and restart the server and again go back to browser to refresh page.To overcome this, Django server must be made persistent. The easiest way to accomplish this is to use a simple bash script as described here.$ while true; do python manage.py runserver; sleep 4; doneWhen Django development server stops, after 4 seconds it tries to start automatically and goes on forever.Instead of typing that everytime, it better to write this as a shell script and put it in system path, so that it can be used in any project.while true; do echo "Re-starting Django runserver" python manage.py runserver sleep 4doneSave this & make it executable(chmod +x), use it is ./filename.sh … -
Understanding Django Middlewares
I assume you have read official Django docs on middleware. I will elaborate on things mentioned in the documentation but I assume you are familiar with basics of middleware. In this post we will discuss the following. What is a middleware When to use middleware Things to remember when writing middleware Writing some middlewares to understand how order of middleware matters What is a middleware Middlewares are hooks to modify Django request or response object. Putting the definition of middleware from Django docs. Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output. When to use middleware You can use middleware if you want to modify the request i.e HttpRequest object which is sent to the view. Or you might want to modify the HttpResponse object returned from the view. Both these can be achieved by using a middleware. You might want to perform an operation before the view executes. In such case you would use a middleware. Django provides some default middleware. eg: AuthenticationMiddleware Very often you would have used request.user inside the view. Django wants user attribute to be set on request before any view … -
Profiling Django Middlewares
I assume you have a basic understanding of Profiling, what it means and why we use it. Why this post Recently I had to profile a Django application which wasn't performing as fast as it should. This application had several custom middlewares too. So it was possible that custom middlewares were the cause of slow performance. There are some existing Django libraries to profile Django code. eg: Django Debug Toolbar, django-silk , django_cprofile etc. Most of them can profile view code well but they can't profile other middlewares. I wanted a way to profile middlewares too. Problem with Django Debug Toolbar I assume you understand middlewares and how the order in which middlewares are defined matter. If you want to get more idea about middlewares, this post might help. Django debug toolbar is probably designed for profiling the views. It uses process_view() and returns an HttpResponse instace from process_view(). process_request() of all middlewares run before any middleware's process_view(). So using Django debug toolbar, it's not possible to profile what's going on inside process_request() of different middlewares. And since process_view() of debug toolbar returns HttpResponse, process_view() of other middlewares is bypassed and so we can't profile process_view() of other middlewares. So … -
How to access your Django site from a different computer
Hey guys! Today we'll see how to access your Django site from another computer. Now this won't be a problem if you've hosted on a remote server like PythonAnywhere or Heroku. But what if you have hosted it on your local machine and want to provide people with access to it?I'm developing an online mentorship platform for my college that is hosted on the college server. So for that I had to use this concept. Before you do this, however, here's a disclaimer: only computers connected in the same network as your local machine can access your Django site. You can, of course, provide global access, but there's a lot of complicated networking stuff involved in that. Let's not go into that right now.So let's get on with it. You know the command for hosting and accessing the site on your local machine is python manage.py runserver. This essentially gives your local machine server capabilities and lets you access it from the same machine. However, to let other machines access it, here's the command:python manage.py runserver <ip_address>:<port_number>Replace <ip_address> with your machine's IP address. If you don't know the IP address, do one of the following:Windows: Open command prompt and type ipconfig. … -
Django Birthday: Recap
Django Birthday: Recap -
Q3 2015 ShipIt Day ReCap
Last Friday marked another ShipIt Day at Caktus, a chance for our employees to set aside client work for experimentation and personal development. It’s always a wonderful chance for our developers to test new boundaries, learn new skills and sometimes even build something entirely new in a single day. -
Repository for existing Extbase model class
If you want to use an existing extbase model like Category but want to create a custom repository to implement some custom queries, here is the way to go: Create typo3conf/ext/your_ext/Classes/Domain/Model/Category.php: <?php namespace Dummy\YourExt\Domain\Model; /** * Category */ class Category extends \TYPO3\CMS\Extbase\Domain\Model\Category { } Create typo3conf/ext/your_ext/Classes/Domain/Repository/CategoryRepository.php: <?php namespace Dummy\YourExt\Domain\Repository; /** * The repository for Categories */ class CategoryRepository extends \TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository { // some custom query methods here } Create typo3conf/ext/your_ext/ext_typoscript_setup.txt: config.tx_extbase{ persistence{ classes{ Dummy\YourExt\Domain\Model\Category { mapping { tableName = sys_category recordType = Tx_YourExt_Category } } } } } Clear the cache and you're ready to go! -
Frontend Code Strategy with Django
Web development is getting more and more focused on front-end development. This leads to a lot of questions on what is the best way to handle compiling css, javascript, coffeescirpt, stylus, etc. Having been involved with a project where the frontend deals with 100+ files between stylus files, coffeescirpt files, javascript, and css. This is kind of crazy to manage without a good strategy or even knowing how to accomplish it. How Frontend Code Works in Django When working with django you need to consider how the code is going to go from your code base to be displayed in the browser. The normal path it takes is to live in a static directory which you edit and run locally. Then in production you do a collectstatic command and it moves everything to a folder for your webserver to pull from. With that in mind as long as the above happens you can do almost anything you want for your frontend code. Lets take a look at the 3 most common ways you can do front-end development with django. Three Popular Ways to Write Frontend Code Everything in the static folder The most common way we start projects is to … -
Rendering your STL files with matplotlib using numpy-stl
It’s been a while since the first version of numpy-stl and a lot has changed since. Most importantly, usage has become even easier. So here’s a demo on how to use matplotlib to render your stl files: from stl import mesh from mpl_toolkits import mplot3d from matplotlib import pyplot # Create a new plot figure = pyplot.figure() axes = mplot3d.Axes3D(figure) # Load the STL files and add the vectors to the plot your_mesh = mesh.Mesh.from_file('tests/stl_binary/HalfDonut.stl') axes.add_collection3d(mplot3d.art3d.Poly3DCollection(your_mesh.vectors)) # Auto scale to the mesh size scale = your_mesh.points.flatten(-1) axes.auto_scale_xyz(scale, scale, scale) # Show the plot to the screen pyplot.show() You can make the render prettier yourself of course, but it is certainly useful for testing. Link to this post! -
Einladung zur Django-UserGroup Hamburg am 08. Juli
Das nächste Treffen der Django-UserGroup Hamburg findet am Mittwoch, den 08.07.2015 um 19:30 statt. Achtung: Neue Location! Dieses Mal treffen wir uns in den Räumen der Smaato Inc., Valentinskamp 70, Emporio 19. Stock in 20355 Hamburg. Auf diesem Treffen gibt es einen Vortrag über TDD für APIs von Michael Kuehne. Bitte seid um ca. 19:20 unten im Foyer, wir fahren dann gemeinsam in den 19. Stock. Wer später kommt, sagt bitte am Empfang bescheid, dass er zur Smaato Inc möchte und wird dann hoch gelassen. Eingeladen ist wie immer jeder der Interesse hat sich mit anderen Djangonauten auszutauschen. Eine Anmeldung ist nicht erforderlich, hilft aber bei der Planung. Weitere Informationen über die UserGroup gibt es auf unserer Webseite www.dughh.de. Die Organisation der Django-UserGroup Hamburg findet ab jetzt über Meetup statt. Um automatisch über zukünftige Treffen informiert zu werden, werdet bitte Mitglied in unserer Meetup-Gruppe: http://www.meetup.com/django-hh -
Observations on the nature of time. And javascript.
In the course of working on one of our latest projects, I picked up an innocuous looking ticket that said: “Date pickers reset to empty on form submission”. “Easy”, I thought. It’s just the values being lost somewhere in form validation.And then I saw the ‘in Firefox and IE’ description. Shouldn’t be too hard, it’ll be a formatting issue or something, maybe even a placeholder, right? Yeah, no. Initial Investigations Everything was fine in Chrome, but not in Firefox. I confirmed the fault also existed in IE (and then promptly ignored IE for now). The responsible element looked like this: <input class="form-control datepicker" data-date-format="{{ js_datepicker_format }}" type="date" name="departure_date" id="departure_date" value="{{ form.departure_date.value|default:'' }}"> This looks pretty innocent. It’s a date input, how wrong can that be? Sit comfortably, there’s a rabbit hole coming up. On Date Inputs Date type inputs are a relatively new thing, they’re in the HTML5 Spec. Support for it is pretty mixed. This jumps out as being the cause of it working in Chrome, but nothing else. Onwards investigations (and flapping at colleagues) led to the fact that we use bootstrap-datepicker to provide a JS/CSS based implementation for the browsers that have no native support. We have … -
Upgrading Django Projects - Introduction
One questions I am asked quite often is how to upgrade larger projects to a newer Django release. While upgrading to a newer minor release is usually really easy and does not require much work it can become a bit harder upgrading to a new major release. My oldest project points back to 0.9x, so it has seen some upgrades, and there are certain patters that proved to work pretty well. Upgrading a Django project is not harder or easier than upgrading any other project of the same size which is using a big third party framework as base and smaller libraries for certain parts of the system. I will try to start with general and simple principles on upgrading projects and move to more Python and Django specific topics later on. Before upgrading you should ask yourself if you have to. Let us assume your application is running fine and you are on a release that still gets bugfix and security updates. You could upgrade to get new features that eventually help you down the road. Or you could implement a new feature that separates your application from all competitors. The answer in that case is pretty obvious, isn’t … -
Upgrading Django Projects - Introduction
Upgrading Django Projects - Introduction One questions I am asked quite often is how to upgrade larger projects to a newer Django release. While upgrading to a newer minor release is usually really easy and does not require much work it can become a bit harder upgrading to a new major release. My oldest project points back to 0.9x, so it has seen some upgrades, and there are certain patters that proved to work pretty well. Upgrading a Django project is not harder or easier than upgrading any other project of the same size which is using a big third party framework as base and smaller libraries for certain parts of the system. I will try to start with general and simple principles on upgrading projects and move to more Python and Django specific topics later on. Before upgrading you should ask yourself if you have to. Let us assume your application is running fine and you are on a release that still gets bugfix and security updates. You could upgrade to get new features that eventually help you down the road. Or you could implement a new feature that separates your application from all competitors. The answer in that … -
Wrapping Up CycleMento
in this video we wrap up the Building a Product series by doing an overview of topics we discussed in the previous 11 videos.Watch Now... -
Announcing the Evennia example-game project "Ainneve"
The Evennia example-game project is underway! I was quite impressed with the response I got on the mailing list to my call for developing an Evennia example game (see my Need your Help blog post).The nature of the responses varied, many were from interested people with little to no experience in Evennia or Python whereas others had the experience but not the time to lead it. It was however clear that the interest to work on an "official" Evennia game is quite big. I'm happy to announce, however, that after only a week we now have a solid lead developer/manager, George Oliver. Helping him on the technical/architecture side is Whitenoise (who, despite a barren github profile, is a professional developer). George put together a game proposal based on the OpenAdventure rpg, an open-source (CC-SA) ruleset that is also found on github. The example game is to be named "Ainneve" and its development is found in a in a separate repository under the github Evennia organisation.All the relevant links and future discussion can be found on the mailing list.George and whitenoise have already made it clear that they aim to not only make Ainneve a good example Evennia game for others to … -
Inclusion Tags
Django’s template system comes with a wide variety of built-in tags and filters designed to address the presentation logic needs of your application. You can extend the template engine by defining custom tags and filters using Python, and then make them available to your templates using the {% load %} tag. Custom template tags and filters must be inside a Django app. If they relate to an existing app it makes sense to create them there; otherwise, you should create a new app to hold them. The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget to include __init__.py file to ensure the directory is treated as a Python package. Your custom tags and filters will be there in a module inside the templatetags directory. The name of the module file is the name you’ll use to load the tags later, so be careful to pick a name that won’t clash with custom tags and filters in another app. For example, if your custom tags/filters are in a file called poll_extras.py, your app layout might look like this: polls/ |- __init__.py …