Stack Overflow


1425 votes
How can I upgrade specific packages using pip and a requirements file?
answers

I ran the following command and it upgraded from 1.2.3 to 1.4.0 Shortcut for upgrade: Note: if the package you are upgrading has any requirements this command will additionally upgrade all the requirements to the latest versions available. In recent versions of pip, you can prevent this behavior by specifying . With that flag, dependencies will not be upgraded unless the installed versions of the dependent packages no longer satisfy the requirements of the upgraded package.

django virtualenv pip

1573 votes
How can I temporarily disable a foreign key constraint in MySQL?
answers

Try or Make sure to after.

mysql sql django django-models

1316 votes
How to upload a file in Django?
answers

Phew, Django documentation really does not have good example about this. I spent over 2 hours to dig up all the pieces to understand how this works. With that knowledge I implemented a project that makes possible to upload files and show them as list. To download source for the project, visit https://github.com/axelpale/minimal-django-file-upload-example or clone it: Update 2013-01-30: The source at GitHub has also implementation for Django 1.4 in addition to 1.3. Even though there is few changes the following tutorial is also useful for 1.4. Update 2013-05-10: Implementation for Django 1.5 at GitHub. Minor changes in redirection in urls.py and usage of url template tag in list.html. Thanks to hubert3 for the effort. Update 2013-12-07: Django 1.6 supported at GitHub. One import changed in myapp/urls.py. Thanks goes to Arthedian. Update 2015-03-17: Django 1.7 supported at GitHub, thanks to aronysidoro. Update 2015-09-04: Django 1.8 supported at GitHub, thanks to nerogit. Update 2016-07-03: Django 1.9 supported at GitHub, thanks to daavve and nerogit Project tree A basic Django 1.3 project with single app and media/ directory for uploads. 1. Settings: myproject/settings.py To upload and serve files, you need to specify where Django stores uploaded files and from what URL Django serves them. MEDIA_ROOT and MEDIA_URL are in settings.py by default but they are empty. See the first lines in Django Managing Files for details. Remember also set the database and add myapp to INSTALLED_APPS 2. Model: myproject/myapp/models.py Next you need a model with a FileField. This particular field stores files e.g. to media/documents/2011/12/24/ based on current date and MEDIA_ROOT. See FileField reference. 3. Form: myproject/myapp/forms.py To handle upload nicely, you need a form. This form has only one field but that is enough. See Form FileField reference for details. 4. View: myproject/myapp/views.py A view where all the magic happens. Pay attention how are handled. For me, it was really hard to spot the fact that can be saved to models.FileField just like that. The model's save() handles the storing of the file to the filesystem automatically. 5. Project URLs: myproject/urls.py Django does not serve MEDIA_ROOT by default. That would be dangerous in production environment. But in development stage, we could cut short. Pay attention to the last line. That line enables Django to serve files from MEDIA_URL. This works only in developement stage. See django.conf.urls.static.static reference for details. See also this discussion about serving media files. 6. App URLs: myproject/myapp/urls.py To make the view accessible, you must specify urls for it. Nothing special here. 7. Template: myproject/myapp/templates/myapp/list.html The last part: template for the list and the upload form below it. The form must have enctype-attribute set to "multipart/form-data" and method set to "post" to make upload to Django possible. See File Uploads documentation for details. The FileField has many attributes that can be used in templates. E.g. {{ document.docfile.url }} and {{ document.docfile.name }} as in the template. See more about these in Using files in models article and The File object documentation. 8. Initialize Just run syncdb and runserver. Results Finally, everything is ready. On default Django developement environment the list of uploaded documents can be seen at . Today the files are uploaded to /path/to/myproject/media/documents/2011/12/17/ and can be opened from the list. I hope this answer will help someone as much as it would have helped me.

django file upload

1280 votes
What is the difference between null=True and blank=True in Django?
answers

sets (versus ) on the column in your DB. Blank values for Django field types such as or will be stored as in the DB. determines whether the field will be required in forms. This includes the admin and your custom forms. If then the field will not be required, whereas if it's the field cannot be blank. The combo of the two is so frequent because typically if you're going to allow a field to be blank in your form, you're going to also need your database to allow values for that field. The exception is s and s, which in Django are never saved as . Blank values are stored in the DB as an empty string (). A few examples: Obviously, Those two options don't make logical sense to use (though there might be a use case for if you want a field to always be required in forms, optional when dealing with an object through something like the shell.) and types are never saved as by Django, so is unnecessary. However, you can manually set one of these fields to to force set it as . If you have a scenario where that might be necessary, you should still include .

python django django-models

970 votes
How to revert the last migration?
answers

You can revert by migrating to the previous migration. For example, if your last two migrations are: Then you would do: You don't actually need to use the full migration name, the number is enough, i.e. You can then delete migration . If you're using Django 1.8+, you can show the names of all the migrations with To reverse all migrations for an app, you can run:

django django-migrations

1149 votes
What does on_delete do on Django models?
answers

This is the behaviour to adopt when the referenced object is deleted. It is not specific to Django; this is an SQL standard. Although Django has its own implementation on top of SQL. (1) There are seven possible actions to take when such event occurs: : When the referenced object is deleted, also delete the objects that have references to it (when you remove a blog post for instance, you might want to delete comments as well). SQL equivalent: . : Forbid the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually. SQL equivalent: . : (introduced in Django 3.1) Similar behavior as that matches SQL's more accurately. (See django documentation example) : Set the reference to NULL (requires the field to be nullable). For instance, when you delete a User, you might want to keep the comments he posted on blog posts, but say it was posted by an anonymous (or deleted) user. SQL equivalent: . : Set the default value. SQL equivalent: . : Set a given value. This one is not part of the SQL standard and is entirely handled by Django. : Probably a very bad idea since this would create integrity issues in your database (referencing an object that actually doesn't exist). SQL equivalent: . (2) Source: Django documentation See also the documentation of PostgreSQL for instance. In most cases, is the expected behaviour, but for every ForeignKey, you should always ask yourself what is the expected behaviour in this situation. and are often useful. Setting where it should not, can potentially delete all of your database in cascade, by simply deleting a single user. Additional note to clarify cascade direction It's funny to notice that the direction of the action is not clear to many people. Actually, it's funny to notice that only the action is not clear. I understand the cascade behavior might be confusing, however you must think that it is the same direction as any other action. Thus, if you feel that direction is not clear to you, it actually means that behavior is not clear to you. In your database, a foreign key is basically represented by an integer field which value is the primary key of the foreign object. Let's say you have an entry comment_A, which has a foreign key to an entry article_B. If you delete the entry comment_A, everything is fine. article_B used to live without comment_A and don't bother if it's deleted. However, if you delete article_B, then comment_A panics! It never lived without article_B and needs it, and it's part of its attributes (, but what is article_B???). This is where steps in, to determine how to resolve this integrity error, either by saying: "No! Please! Don't! I can't live without you!" (which is said or in Django/SQL) "All right, if I'm not yours, then I'm nobody's" (which is said ) "Good bye world, I can't live without article_B" and commit suicide (this is the behavior). "It's OK, I've got spare lover, and I'll reference article_C from now" (, or even ). "I can't face reality, and I'll keep calling your name even if that's the only thing left to me!" () I hope it makes cascade direction clearer. :) Footnotes (1) Django has its own implementation on top of SQL. And, as mentioned by @JoeMjr2 in the comments below, Django will not create the SQL constraints. If you want the constraints to be ensured by your database (for instance, if your database is used by another application, or if you hang in the database console from time to time), you might want to set the related constraints manually yourself. There is an open ticket to add support for database-level on delete constrains in Django. (2) Actually, there is one case where can be useful: If you want to skip Django's implementation and implement the constraint yourself at the database-level.

python django django-models

1087 votes
What is the difference between null=True and blank=True in Django?
21 answers

When we add a database field in django we generally write: The same is done with , etc. What is the basic difference in having only only , in respect to different (, , , ) fields. What are the advantages/disadvantages of using 1/2/3?

python django django-models

1179 votes
Does Django scale?
29 answers

I'm building a web application with Django. The reasons I chose Django were: I wanted to work with free/open-source tools. I like Python and feel it's a long-term language, whereas regarding Ruby I wasn't sure, and PHP seemed like a huge hassle to learn. I'm building a prototype for an idea and wasn't thinking too much about the future. Development speed was the main factor, and I already knew Python. I knew the migration to Google App Engine would be easier should I choose to do so in the future. I heard Django was "nice". Now that I'm getting closer to thinking about publishing my work, I start being concerned about scale. The only information I found about the scaling capabilities of Django is provided by the Django team (I'm not saying anything to disregard them, but this is clearly not objective information...). My questions: What's the "largest" site that's built on Django today? (I measure size mostly by user traffic) Can Django deal with 100,000 users daily, each visiting the site for a couple of hours? Could a site like Stack Overflow run on Django?

python django web-applications scalability

1132 votes
How can I combine two or more querysets in a Django view?
answers

Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won't add further cost. Using is faster than looping each list and appending elements one by one, since is implemented in C. It also consumes less memory than converting each queryset into a list before concatenating. Now it's possible to sort the resulting list e.g. by date (as requested in hasen j's comment to another answer). The function conveniently accepts a generator and returns a list: If you're using Python 2.4 or later, you can use instead of a lambda. I remember reading about it being faster, but I didn't see a noticeable speed difference for a million item list.

django search django-queryset django-q

977 votes
Creating a JSON response using Django and Python
answers

I usually use a dictionary, not a list to return JSON content. Pre-Django 1.7 you'd return it like this: For Django 1.7+, use as shown in this SO answer like so :

python django json

743 votes
How to define two fields "unique" as couple
answers

There is a simple solution for you called unique_together which does exactly what you want. For example: And in your case:

django django-models

729 votes
How to check Django version
answers

Django 1.5 supports Python 2.6.5 and later. If you're under Linux and want to check the Python version you're using, run from the command line. If you want to check the Django version, open a Python console and type

python django

574 votes
How can I get the full/absolute URL (with domain) in Django?
answers

Use handy request.build_absolute_uri() method on request, pass it the relative url and it'll give you full one. By default, the absolute URL for is returned, but you can pass it a relative URL as the first argument to convert it to an absolute URL.

django

960 votes
Does Django scale?
answers

"What are the largest sites built on Django today?" There isn't any single place that collects information about traffic on Django built sites, so I'll have to take a stab at it using data from various locations. First, we have a list of Django sites on the front page of the main Django project page and then a list of Django built sites at djangosites.org. Going through the lists and picking some that I know have decent traffic we see: Instagram: What Powers Instagram: Hundreds of Instances, Dozens of Technologies. Pinterest: Alexa rank 37 (21.4.2015) and 70 Million users in 2013 Bitbucket: 200TB of Code and 2.500.000 Users Disqus: Serving 400 million people with Python. curse.com: 600k daily visits. tabblo.com: 44k daily visits, see Ned Batchelder's posts Infrastructure for modern web sites. chesspark.com: Alexa rank about 179k. pownce.com (no longer active): alexa rank about 65k. Mike Malone of Pownce, in his EuroDjangoCon presentation on Scaling Django Web Apps says "hundreds of hits per second". This is a very good presentation on how to scale Django, and makes some good points including (current) shortcomings in Django scalability. HP had a site built with Django 1.5: ePrint center. However, as for novemer/2015 the entire website was migrated and this link is just a redirect. This website was a world-wide service attending subscription to Instant Ink and related services HP offered (*). "Can Django deal with 100,000 users daily, each visiting the site for a couple of hours?" Yes, see above. "Could a site like Stack Overflow run on Django?" My gut feeling is yes but, as others answered and Mike Malone mentions in his presentation, database design is critical. Strong proof might also be found at www.cnprog.com if we can find any reliable traffic stats. Anyway, it's not just something that will happen by throwing together a bunch of Django models :) There are, of course, many more sites and bloggers of interest, but I have got to stop somewhere! Blog post about Using Django to build high-traffic site michaelmoore.com described as a top 10,000 website. Quantcast stats and compete.com stats. (*) The author of the edit, including such reference, used to work as outsourced developer in that project.

python django web-applications scalability

815 votes
Is there a list of Pytz Timezones?
8 answers

I would like to know what are all the possible values for the timezone argument in the Python library pytz. How to do it?

python django pytz

675 votes
Django datetime issues (default=datetime.now())
answers

it looks like is being evaluated when the model is defined, and not each time you add a record. Django has a feature to accomplish what you are trying to do already: or The difference between the second example and what you currently have is the lack of parentheses. By passing without the parentheses, you are passing the actual function, which will be called each time a record is added. If you pass it , then you are just evaluating the function and passing it the return value. More information is available at Django's model field reference

python django

675 votes
How do I do an OR filter in a Django query?
answers

There is objects that allow to complex lookups. Example:

django django-queryset

916 votes
How to reset Django admin password?
answers

see docs

django authentication permissions passwords

637 votes
Django Server Error: port is already in use
answers

A more simple solution just type . This should kill all the processes associated with port 8000. EDIT: For osx users you can use

python django

746 votes
Capturing URL parameters in request.GET
answers

When a URL is like , you would use . is the parameter you want, and is the default value if isn't found. However, if you are instead just configuring your **, then your captures from the are passed to the function as arguments (or named arguments). Such as: Then in your you would have

django url rest

613 votes
How to check Django version
26 answers

I have to use Python and Django for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. But how do I make sure whether Django uses the 2.6 or 2.7 version and what version of modules Django uses?

python django

726 votes
Django - iterate number in for loop of a template
answers

Django provides it. You can use either: index starts at 1. index starts at 0. In template, you can do: More info at: for | Built-in template tags and filters | Django documentation

django for-loop django-templates

847 votes
What is a "slug" in Django?
answers

A "slug" is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually. An example: Now let's pretend that we have a Django model such as: How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this: Or, you might want to reference the title like this: Since spaces aren't valid in URLs, they must be replaced by , which results in: Both attempts are not resulting in very meaningful, easy-to-read URL. This is better: In this example, is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens . Also see the URL of this very web page for another example.

python django django-models slug

710 votes
How to upload a file in Django?
10 answers

As a newbie to Django, I am having difficulty making an upload app in Django 1.3. I could not find any up-to-date example/snippets. May someone post a minimal but complete (Model, View, Template) example code to do so?

django file upload

584 votes
RuntimeWarning: DateTimeField received a naive datetime
answers

The problem is not in Django settings, but in the date passed to the model. Here's how a timezone-aware object looks like: And here's a naive object: So if you are passing email date anywhere (and it eventually gets to some model), just use Django's . If not, then it's probably an issue with an existing package that fetches date without timezone and you can patch the package, ignore the warning or set USE_TZ to False.

django django-mailer

820 votes
How do I do a not equal in Django queryset filtering?
answers

You can use Q objects for this. They can be negated with the operator and combined much like normal Python expressions: will return all entries except the one(s) with as their ID:

python django django-models django-queryset

812 votes
(13: Permission denied) while connecting to upstream:[nginx]
answers

Disclaimer Make sure there are no security implications for your use-case before running this. Answer I had a similar issue getting Fedora 20, Nginx, Node.js, and Ghost (blog) to work. It turns out my issue was due to SELinux. This should solve the problem: Details I checked for errors in the SELinux logs: And found that running the following commands fixed my issue: Option #2 (untested, but probably more secure) https://security.stackexchange.com/questions/152358/difference-between-selinux-booleans-httpd-can-network-relay-and-httpd-can-net References http://blog.frag-gustav.de/2013/07/21/nginx-selinux-me-mad/ https://wiki.gentoo.org/wiki/SELinux/Tutorials/Where_to_find_SELinux_permission_denial_details http://wiki.gentoo.org/wiki/SELinux/Tutorials/Managing_network_port_labels

django python-2.7 nginx gunicorn

928 votes
How to filter empty or NULL names in a QuerySet?
answers

You could do this: If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so: Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where is either null or an empty string, so you get all objects that have a not-null, not-empty field. The generated SQL would look something like: You can also pass multiple arguments to a single call to , which would ensure that only objects that meet every condition get excluded: Here, rows in which and are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this: Alternatively, if your logic is more complex than that, you could use Django's Q objects: For more info see this page and this page in the Django docs. As an aside: My SQL examples are just an analogy--the actual generated SQL code will probably look different. You'll get a deeper understanding of how Django queries work by actually looking at the SQL they generate.

django django-models django-queryset filter null

571 votes
What's the difference between django OneToOneField and ForeignKey?
answers

Be careful to realize that there are some differences between and . As stated in The Definitive Guide to Django: OneToOneField A one-to-one relationship. Conceptually, this is similar to a with , but the "reverse" side of the relation will directly return a single object. In contrast to the "reverse" relation, a "reverse" relation returns a . Example For example, if we have the following two models (full model code below): model uses model uses From within execute the following: Example with Example Model Code

django django-models

563 votes
How to revert the last migration?
11 answers

I've made a migration that added a new table and want to revert it and delete the migration, without creating a new migration. How do I do it? Is there a command to revert last migration and then I can simply delete the migration file?

django django-migrations