Django: Ticket Queryhttps://code.djangoproject.com/query?status=new&status=assigned&status=reopened&needs_tests=1&stage=Accepted&order=summary
The Web framework for perfectionists with deadlines.en-USDjangohttps://www.djangoproject.com/s/img/site/hdr_logo.gifhttps://code.djangoproject.com/query?status=new&status=assigned&status=reopened&needs_tests=1&stage=Accepted&order=summary
Trac 1.0.2https://code.djangoproject.com/ticket/8972
https://code.djangoproject.com/ticket/8972#8972: Add ability to delete selected vector features within the Geodjango/OpenLayers Admin map interfaceMon, 08 Sep 2008 17:35:43 GMTspringmeyer<p>
This feature has been needed for some time, and was recently requested. See: <a class="ext-link" href="http://groups.google.com/group/django-users/browse_thread/thread/36242edfd0d0281c?hl=en"><span class="icon">​</span>http://groups.google.com/group/django-users/browse_thread/thread/36242edfd0d0281c?hl=en</a>
</p>
<p>
I've started a basic patch that adds a javascript function to allow multiple features to be selected in the map interface, deleted from view, and removed from the save method.
</p>
<p>
I've tested this so far when editing multipolygon data in the admin.
</p>
<p>
A known issue I'm hoping others may have a solution to:
</p>
<p>
Currently, an OL javascript error occurs on line 948 of OpenLayer.js after successfully deleting a feature. This do not seem to cause any problems in saving the correct geometry or in continuing to use the select control. This is the firebug output:
</p>
<pre class="wiki">object is undefined
selectFeature()(undefined)OpenLayers.js (line 948)
clearSelectedFeatures()()277 (line 327)
javascript:geodjango_geometry.clearSelectedFeatures()()()javascri...eatures() (line 1)
[Break on this error] this.feature=null;this.dragControl.deact...ply(this.selectControl,[this.feature]);}
</pre>Resultshttps://code.djangoproject.com/ticket/8972#changeloghttps://code.djangoproject.com/ticket/13251
https://code.djangoproject.com/ticket/13251#13251: Add ability to know where an object was deleted from to pre/post delete signalsWed, 31 Mar 2010 01:30:39 GMTskoom<p>
Since deleting objects deletes related objects, it would be good to know the origin of the delete.
</p>
<p>
It lets the signal listeners know why an object is being delete. If it's deleted from a model.delete(), you know which instance initiated the delete and if it's from a queryset.delete() you know which queryset initiated the delete, with the models in that queryset. Using this you know if the instance is being deleted directly or because it's related to another instance.
</p>
Resultshttps://code.djangoproject.com/ticket/13251#changeloghttps://code.djangoproject.com/ticket/13295
https://code.djangoproject.com/ticket/13295#13295: Add a Meta.sequence option to modelsThu, 08 Apr 2010 10:35:07 GMTsmglab<p>
PostgreSQL users need to be able to override the name of the serial sequence. Mostly to match existing databases, but also to solve issues like <a class="closed ticket" href="https://code.djangoproject.com/ticket/15682" title="Bug: Postgresql last_insert_id() failing when using custom schemas (closed: duplicate)">#15682</a>, <a class="closed ticket" href="https://code.djangoproject.com/ticket/13179" title="Bug: last_insert_id method cannot find sequence (closed: duplicate)">#13179</a> and <a class="closed ticket" href="https://code.djangoproject.com/ticket/1946" title="New feature: Allow overriding of default sequence name (closed: duplicate)">#1946</a>.
</p>
Resultshttps://code.djangoproject.com/ticket/13295#changeloghttps://code.djangoproject.com/ticket/12733
https://code.djangoproject.com/ticket/12733#12733: Added support for Extent aggregate on mysql databasesSat, 30 Jan 2010 03:41:35 GMTjann.kleen@…<p>
This patch enables the usage of extent aggregates for mysql backends, using MIN/MAX queries.
</p>
Resultshttps://code.djangoproject.com/ticket/12733#changeloghttps://code.djangoproject.com/ticket/12044
https://code.djangoproject.com/ticket/12044#12044: Add extra_context to admin action delete_selectedFri, 16 Oct 2009 16:06:11 GMTrjc<p>
We need to pass extra context in admin action delete_selected, just like admin view's delete_view.
</p>
Resultshttps://code.djangoproject.com/ticket/12044#changeloghttps://code.djangoproject.com/ticket/11211
https://code.djangoproject.com/ticket/11211#11211: Add GMarkerOptions: clickable, bouncy, dragCrossMove, bounceGravity, autoPan and hideWed, 27 May 2009 05:01:31 GMTTravis Jeffery <eatsleepgolf@…><p>
Hello,
</p>
<p>
I have attached a patch to add every GMarkerOption for Google Maps except for zIndexProcess.
This includes the options: clickable, bouncy, dragCrossMove, bounceGravity, autoPan and hide.
</p>
<p>
Thanks.
</p>
Resultshttps://code.djangoproject.com/ticket/11211#changeloghttps://code.djangoproject.com/ticket/11482
https://code.djangoproject.com/ticket/11482#11482: Add Google map events handlingWed, 15 Jul 2009 14:53:51 GMTkapa77<p>
Now only Markers can have events added, there should be possibility to add events to map also. I'm adding very simple patch.
</p>
Resultshttps://code.djangoproject.com/ticket/11482#changeloghttps://code.djangoproject.com/ticket/11458
https://code.djangoproject.com/ticket/11458#11458: Add GPolylineOptions and GPolygonOptions to django.contrib.gis.maps.google.overlaysSat, 11 Jul 2009 05:26:34 GMTtomchuk<p>
I needed to set mouseOutTolerance on some polygons I'm displaying on a google map. The current API (both google's and Django's wrapper) made this next to impossible as there are no methods supplied to set this behavior. This patch adds GPolylineOptions and GPolygonOptions classes and params in <span class="underline">init</span> for GPolygon and GPolyline for their respective options.
</p>
<p>
Cheers,
Tom
</p>
Resultshttps://code.djangoproject.com/ticket/11458#changeloghttps://code.djangoproject.com/ticket/11072
https://code.djangoproject.com/ticket/11072#11072: Add Info Window Html to GMarkerMon, 11 May 2009 17:07:03 GMTUbercore<p>
I did a quick search for this and didn't find any previous work.
</p>
<p>
It allows you to set HTML for a GInfoWindow on an instance of a GMarker. No support for options on the info window yet, this is just the simplest case.
</p>
<p>
I did see that it's possible to accomplish this using the GEvent class in overlays.py, but I think there's value in being able to set it directly on the marker.
</p>
<p>
google-map.js uses bindInfoWindowHtml() to add the info window when the marker is added.
</p>
<p>
A more complete solution might involve implementing GInfoWindow and GInfoWindowOptions, but I didn't want to implement them since they have no public constructor in the Google Maps API. Maybe represent the info window as a tuple of (html, { options})?
</p>
<p>
Anyway, this tackles the simplest case.
</p>
<p>
Example usage:
</p>
<pre class="wiki">marker = GMarker(object.location, title=object.address)
marker.infowindowhtml = "&lt;p&gt;Info Window!&lt;/p&gt;";
</pre>Resultshttps://code.djangoproject.com/ticket/11072#changeloghttps://code.djangoproject.com/ticket/16220
https://code.djangoproject.com/ticket/16220#16220: Add introspection for multicolumn indexesFri, 10 Jun 2011 13:15:23 GMTjgelens<p>
The current database introspection methods don't support multi column indexes.
</p>
<p>
It's difficult to add this functionality to the current get_indexes methods as it's difficult to include it the current returned data d, which is:
</p>
<pre class="wiki">{u'group_id': {'primary_key': False, 'unique': False},
u'id': {'primary_key': True, 'unique': True}}
</pre><p>
What hvdklauw, jgelens and charstring suggest is a (*cough*) "get_real_indexes" method.
</p>
Resultshttps://code.djangoproject.com/ticket/16220#changeloghttps://code.djangoproject.com/ticket/24230
https://code.djangoproject.com/ticket/24230#24230: Add language name translated into active language to LANG_INFO dictionaryTue, 27 Jan 2015 20:44:18 GMTtricoder42<p>
<tt>get_language_info</tt> tag returns english name and local name of language:
</p>
<pre class="wiki">language.local_name == česky
language.name == Czech
</pre><p>
Neither depends on active language, but sometimes there's need for translated language name, ex. tchèque (in French). The only way how to do it right now is to take the english name and run it through <tt>gettext</tt> since Django already has all languages translated.
</p>
<p>
This would be very handy filter tag:
</p>
<pre class="wiki">@register.filter
def language_translated(code):
"""
Return language name translated into active language
"""
name = translation.get_language_info(code)['name'].capitalize()
return translation.gettext(name)
</pre><hr />
<p>
Maybe we could also extend dictionary returned by the <tt>get_language_info</tt> tag with <tt>name_translated</tt> to keep API consistent. All keys from <tt>get_language_info</tt> have matching filter variants (<tt>language_name</tt>, <tt>language_name_local</tt> and <tt>language_bidi</tt>).
</p>
Resultshttps://code.djangoproject.com/ticket/24230#changeloghttps://code.djangoproject.com/ticket/13774
https://code.djangoproject.com/ticket/13774#13774: add optional rel_db_type() method for model fieldWed, 16 Jun 2010 09:36:57 GMTSuor<p>
rel_db_type() method will return db_type for <a class="wiki" href="https://code.djangoproject.com/wiki/ForeignKey">ForeignKey</a> / OneToOneField to a field,
if not exists value of db_type() method should be used as it's done now.
</p>
<p>
It will remove a need for a hack in <a class="wiki" href="https://code.djangoproject.com/wiki/ForeignKey">ForeignKey</a>.db_type and make possible subclasses of AutoField work such as:
</p>
<pre class="wiki">class BigAutoField(models.AutoField):
def __init__(self, verbose_name=None, name=None, external_sequence=False, **kwargs):
self.external_sequence = external_sequence
models.AutoField.__init__(self, verbose_name, name, **kwargs)
def db_type(self, connection):
# now only for PostgreSQL, should be done more carefully to support other backends
return 'bigint' if self.external_sequence else 'bigserial'
def rel_db_type(self, connection):
return 'bigint'
</pre>Resultshttps://code.djangoproject.com/ticket/13774#changeloghttps://code.djangoproject.com/ticket/10941
https://code.djangoproject.com/ticket/10941#10941: Add querystring helper methods to Page classTue, 28 Apr 2009 00:57:52 GMTbenspaulding<p>
Working with pagination and query strings within a template can be painful. Personally, I have never had a situation when I was paginating using a GET parameter where there were not other parameters that needed to be preserved through out the various pages.
</p>
<p>
Take search, for example. There may be parameters for searching within one or more models, for a particular author and sorting by date. Maintaining all of these parameters within the pagination links takes some serious template logic.
</p>
<pre class="wiki">{# Linebreaks added for readability. In real life this would need to be one, long line. #}
&lt;a href="?{% for key, values in request.GET.iterlists %}
{% ifnotequal key "page" %}
{% for value in values %}
{{ key }}={{ value }}&amp;amp;
{% endfor %}
{% endifnotequal %}
{% endfor %}page={{ page.next_page_number }}"&gt;Next page&lt;/a&gt;
</pre><p>
That kind of logic shouldn’t be in a template. I have created a patch that would allow for something much simpler, like so:
</p>
<pre class="wiki">&lt;a href="?{{ page.next_page_querystring }}"&gt;Next page&lt;/a&gt;
</pre><p>
Though there has been much talk of creating template tags which would produce all-out pagination bars, I believe this particular functionality should be an actual method on the page object for two reasons:
</p>
<ol><li>This is basic functionality whose end result is hard to dispute (as opposed to a full pagination bar where markup and features could be disputed eternally),
</li><li>This does not require the request context processor to be installed.
</li></ol><p>
Note that this patch includes documentation. Tests are still needed. I am not married to the exact implementation, but I and others I have discussed this and feel that this simplicity and fuctionality belong in Django’s pagination.
</p>
Resultshttps://code.djangoproject.com/ticket/10941#changeloghttps://code.djangoproject.com/ticket/21273
https://code.djangoproject.com/ticket/21273#21273: Add read only support for Oracle XE to django.contrib.gisTue, 15 Oct 2013 17:02:50 GMTvinhussey<p>
django.contrib.gis.backends supports Oracle but does not support the spatial component of Oracle XE. Oracle XE has a more lenient licence than Oracle and may be useful for accessing legacy spatial data.
</p>
<p>
Oracle XE may be accessed using cx_Oracle, but spatial data is not converted into a usable form. The spatial data stored in oracle is documented (search for 'oracle sdo_geometry').
</p>
<p>
The following is a short description of the point attribute - I will expand with other types asap.
</p>
<p>
Example - Oracle spatial table named Floods with a spatial field geoloc:
</p>
<pre class="wiki">&gt;&gt;&gt; from import_data.models import *
&gt;&gt;&gt; floods = Floods.objects.all()
&gt;&gt;&gt; f = floods[99]
&gt;&gt;&gt; g = f.geoloc
&gt;&gt;&gt; g
&lt;cx_Oracle.OBJECT object at 0xa02a3e0&gt;
&gt;&gt;&gt; dir(g)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'type']
&gt;&gt;&gt; gtype = str(int(g.__getattribute__('SDO_GTYPE')))
&gt;&gt;&gt; print gtype
2001
&gt;&gt;&gt; gdims = gtype[0]
&gt;&gt;&gt; gdims
'2'
&gt;&gt;&gt; gtopo = gtype[1]
&gt;&gt;&gt; gtopo
'0'
&gt;&gt;&gt; ggeomtype = gtype[2:]
&gt;&gt;&gt; ggeomtype
'01'
&gt;&gt;&gt; gsrid = g.__getattribute__('SDO_SRID')
&gt;&gt;&gt; gsrid
82086.0
&gt;&gt;&gt; gpoint_x = g.__getattribute__('SDO_POINT').X
&gt;&gt;&gt; gpoint_y = g.__getattribute__('SDO_POINT').Y
&gt;&gt;&gt; gpoint_z = g.__getattribute__('SDO_POINT').Z
&gt;&gt;&gt; print gpoint_x, gpoint_y, gpoint_z
162913.389524 340748.357977 None
&gt;&gt;&gt; g_ewkt = "SRID:%s:POINT(%f %f)" % (str(int(g.__getattribute__('SDO_SRID'))), g.__getattribute__('SDO_POINT').X, g.__getattribute__('SDO_POINT').Y)
&gt;&gt;&gt; g_ewkt
'SRID:82086:POINT(162913.389524 340748.357977)'
</pre><p>
From the Oracle docs, this is a 2 dimensional (gdims), null topology (gtopo), POINT geometry, srid = 82086 (Irish Grid), with x and y co-ordinates and null z coordinates.
</p>
<p>
Further information is stored in other attributes for more complex geometries - a very wide range is available. For a point, these may not necessarily be used.
</p>
<pre class="wiki">&gt;&gt;&gt; print g.__getattribute__('SDO_ELEM_INFO')
None
&gt;&gt;&gt; print g.__getattribute__('SDO_ORDINATES')
None
</pre>Resultshttps://code.djangoproject.com/ticket/21273#changeloghttps://code.djangoproject.com/ticket/14098
https://code.djangoproject.com/ticket/14098#14098: Add "--skip" option to inspectdb.Wed, 11 Aug 2010 23:06:09 GMTadamv<p>
If you're inspecting a MySQL db, and it has a view that references missing columns, then inspectdb will stop with an exception while inspecting that database.
</p>
<p>
Add a "--skip" option to inspectdb to skip over tables that throw errors instead of aborting.
</p>
Resultshttps://code.djangoproject.com/ticket/14098#changeloghttps://code.djangoproject.com/ticket/23299
https://code.djangoproject.com/ticket/23299#23299: Add some interoperability to _() function calls parsing in templatize function.Fri, 15 Aug 2014 19:41:19 GMTniwibe<p>
The current implementation only works for django and works very well. But for make easy use another template engine like jinja2 and combine it with django i18n makemessages process, would be awesome include some support for more generic parsing of _() function calls.
</p>
<p>
The change is very small, it uses findall instead of match, that allows finding inner _() function calls that are very common in jinja2 templates (and not in django templates):
</p>
<p>
<a class="ext-link" href="https://github.com/niwibe/django/compare/interoprability-jinja-django-i18n-parse"><span class="icon">​</span>https://github.com/niwibe/django/compare/interoprability-jinja-django-i18n-parse</a>
</p>
Resultshttps://code.djangoproject.com/ticket/23299#changeloghttps://code.djangoproject.com/ticket/5815
https://code.djangoproject.com/ticket/5815#5815: Adds per-view cache refreshing (clearing)Thu, 25 Oct 2007 05:20:57 GMTk0001<p>
This patch adds the possibility to clear(refresh) cached data per view.
</p>
<p>
SmileyChris sugested it would be good to add another key to the cached keys where we could keep track of all the different cache_page_key hashes, so we that can delete those then.
</p>
<p>
It is possible to clear the cache for an specific view, to achieve that, you
should tell your view's url path (and optionally, a key_prefix) to
<tt></tt>clear_cache_for_path(path, key_prefix=None)<tt></tt>.
</p>
<pre class="wiki"> from django.utils.cache import clear_cache_for_path
# clear the all cached data for path '/blog/posts/2/'
clear_cache_for_path('/blog/posts/2/')
</pre><p>
Note that it will delete every page cached from matching this path, <tt></tt>Vary<tt></tt> headers
doesn't matter.
</p>
<p>
NOTE: Thanks SmileyChris for your help and supervision with this.
</p>
Resultshttps://code.djangoproject.com/ticket/5815#changeloghttps://code.djangoproject.com/ticket/12410
https://code.djangoproject.com/ticket/12410#12410: add support for St_Line_Locate_Point to geodjango postgis backendSun, 20 Dec 2009 17:06:16 GMTIanWard<p>
Here's a patch that adds a line_locate_point method to the GeoQuerySet class, allowing a calculation of the closest point along a LineString to a point field. The value returned is a float between 0 and 1. This is useful for estimating addresses and ordering points given a LineString reference.
</p>
Resultshttps://code.djangoproject.com/ticket/12410#changeloghttps://code.djangoproject.com/ticket/11854
https://code.djangoproject.com/ticket/11854#11854: Add support of PostGIS's Azimuth functionWed, 09 Sep 2009 11:05:57 GMTckarrie<p>
Hi, I would like to see the azimuth function in the gis component.
</p>
<p>
Thank you very much.
</p>
Resultshttps://code.djangoproject.com/ticket/11854#changeloghttps://code.djangoproject.com/ticket/17613
https://code.djangoproject.com/ticket/17613#17613: Add validation method for cache keysMon, 30 Jan 2012 10:35:05 GMTvzima<p>
We encountered a problem that we can not check keys for cache before we try to use them. This is quite in need in case you are using identifiers that not entirely under your control e.g. URLs or you have more permissive checks than cache requires, e.g. length &lt;= 255.
</p>
<p>
If you want to use memcache in such cases you need to use quite ugly code to catch exceptions from invalid keys:
</p>
<div class="code"><pre><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> cache
<span class="kn">from</span> <span class="nn">somewhere</span> <span class="kn">import</span> slugify<span class="p">,</span> expensive_function
<span class="k">try</span><span class="p">:</span>
<span class="kn">from</span> <span class="nn">memcache</span> <span class="kn">import</span> Client
MemcachedKeyError <span class="o">=</span> Client<span class="o">.</span>MemcachedKeyError
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
<span class="c"># If memcached is not present create dummy exception</span>
<span class="k">class</span> <span class="nc">MemcachedKeyError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="k">pass</span>
<span class="k">def</span> <span class="nf">cached_expensive_function</span><span class="p">(</span>url<span class="p">)</span>
key <span class="o">=</span> slugify<span class="p">(</span>url<span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
result <span class="o">=</span> cache<span class="o">.</span>cache<span class="o">.</span>get<span class="p">(</span>key<span class="p">)</span>
<span class="k">except</span> MemcachedKeyError<span class="p">:</span>
<span class="k">return</span> expensive_function<span class="p">(</span>url<span class="p">)</span>
<span class="k">if</span> result <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
result <span class="o">=</span> expensive_function<span class="p">(</span>url<span class="p">)</span>
cache<span class="o">.</span>cache<span class="o">.</span>set<span class="p">(</span>key<span class="p">,</span> result<span class="p">)</span>
<span class="k">return</span> result
</pre></div><p>
A nice code for such cases would be:
</p>
<div class="code"><pre><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> cache
<span class="kn">from</span> <span class="nn">somewhere</span> <span class="kn">import</span> slugify<span class="p">,</span> expensive_function
<span class="k">def</span> <span class="nf">cached_expensive_function</span><span class="p">(</span>url<span class="p">)</span>
key <span class="o">=</span> slugify<span class="p">(</span>url<span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> cache<span class="o">.</span>cache<span class="o">.</span>check_key<span class="p">(</span>key<span class="p">)</span>
<span class="k">return</span> expensive_function<span class="p">(</span>url<span class="p">)</span>
result <span class="o">=</span> cache<span class="o">.</span>cache<span class="o">.</span>get<span class="p">(</span>key<span class="p">)</span>
<span class="k">if</span> result <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
result <span class="o">=</span> expensive_function<span class="p">(</span>url<span class="p">)</span>
cache<span class="o">.</span>cache<span class="o">.</span>set<span class="p">(</span>key<span class="p">,</span> result<span class="p">)</span>
<span class="k">return</span> result
</pre></div><p>
I also append basic patch that adds such method.
</p>
Resultshttps://code.djangoproject.com/ticket/17613#changeloghttps://code.djangoproject.com/ticket/12075
https://code.djangoproject.com/ticket/12075#12075: Add wsgiorg.routing args supportThu, 22 Oct 2009 16:06:12 GMTGustavo<p>
The <a class="ext-link" href="http://wsgi.readthedocs.org/en/latest/specifications/routing_args.html"><span class="icon">​</span>wsgiorg.routing_args</a> standard may be really useful if you want to use WSGI middleware or applications inside Django because some of them take advantage of that to do nice/useful things.
</p>
<p>
It's currently not supported in Django - But it will with the attached patch.
</p>
<p>
<em>[edit] fixed broken link.</em>
</p>
Resultshttps://code.djangoproject.com/ticket/12075#changeloghttps://code.djangoproject.com/ticket/12974
https://code.djangoproject.com/ticket/12974#12974: Admindocs app introspection omits several model methodsFri, 26 Feb 2010 06:41:54 GMTjabapyth<p>
The problem is that some methods are preprocessed (especially those with a @decorator) are ignored by admin docs, because they take <em>no arguments</em> as opposed to a single (self) argument. This patch changes a <strong>single character</strong> (from '==' to '&lt;=').
</p>
Resultshttps://code.djangoproject.com/ticket/12974#changeloghttps://code.djangoproject.com/ticket/17905
https://code.djangoproject.com/ticket/17905#17905: Admin documentation lists all models, even for users without access to certain applicationsThu, 15 Mar 2012 13:20:41 GMTchriscohoat<p>
By default, the admin docs lists documentation for all models. Some users may not have access to models that are still listed in their entirety.
</p>
<p>
The easiest way to fix this was to check each model in the model index, and only add the model to the listing if a user has the correct permissions. I'm not sure if this is the correct way to go about this, but I'm submitting the patch for review.
</p>
Resultshttps://code.djangoproject.com/ticket/17905#changeloghttps://code.djangoproject.com/ticket/15819
https://code.djangoproject.com/ticket/15819#15819: Admin searches should use distinct, if query involves joinsWed, 13 Apr 2011 08:40:49 GMTAdam Kochanowski <aip@…><p>
If search on inline relation in django-admin I've got multiple same rows. It do search unusable... On django 1.2 it works right.
</p>
Resultshttps://code.djangoproject.com/ticket/15819#changeloghttps://code.djangoproject.com/ticket/18549
https://code.djangoproject.com/ticket/18549#18549: Admin should not use verbose_name_plural for OneToOne fieldSun, 01 Jul 2012 16:44:50 GMTRoySmith<p>
Do something like the following:
</p>
<pre class="wiki">class Foo(Model):
i = IntegerField()
bar = OneToOneField("Bar")
class FooInline(admin.TabularInline):
model = Foo
class Bar(Model):
i = Integerfield()
class BarAdmin(admin.ModelAdmin):
inlines = [FooInline]
admin.site.register(Foo, FooAdmin)
admin.site.register(Bar)
</pre><p>
When you edit a Bar in the admin, the formset section for entering a Foo will be labeled "Foos" (plural). Since it's a one-to-one mapping, it should be labeled "Foo" (singular).
</p>
Resultshttps://code.djangoproject.com/ticket/18549#changeloghttps://code.djangoproject.com/ticket/5899
https://code.djangoproject.com/ticket/5899#5899: Allow admin fieldsets to be collapsible but not initially collapsedThu, 08 Nov 2007 14:08:08 GMTIonut Ciocirlan <ionut.ciocirlan@…><p>
I want to use the collapse feature of the admin, but not have the field initially collapsed, so I made this little patch.
</p>
<p>
It adds a "collapsible" class that does just that. It also patches the documentation.
</p>
Resultshttps://code.djangoproject.com/ticket/5899#changeloghttps://code.djangoproject.com/ticket/22986
https://code.djangoproject.com/ticket/22986#22986: Allow disabling session model database table creation if not used by session engineWed, 09 Jul 2014 18:04:47 GMTtimo<p>
Previously, we recommended removing <tt>contrib.sessions</tt> from <tt>INSTALLED_APPS</tt> but this causes the test client login to break (<a class="closed ticket" href="https://code.djangoproject.com/ticket/22934" title="Bug: INSTALLED_APPS must contain django.contrib.sessions for ... (closed: fixed)">#22934</a>) and also disables the <tt>clearsessions</tt> management command which could be useful for the file-based sessions (which also don't require the database tables).
</p>
Resultshttps://code.djangoproject.com/ticket/22986#changeloghttps://code.djangoproject.com/ticket/12772
https://code.djangoproject.com/ticket/12772#12772: Allow loading template tags by fully qualified python module pathThu, 04 Feb 2010 12:19:03 GMTpatrys<p>
Currently templatetags are magically searched for in the list of installed apps. This leads to all kind of problems when debugging code, starting from being forced to use find to locate tag libraries and ending with global namespace collisions.
</p>
<p>
The attached patch adds the possibility to import tags by fully qualified module path by first trying to make an absolute import and only then falling back to searching inside installed apps.
</p>
<p>
This also allows people to import tag libraries that are not parts of any application (so common tags can be kept together without the need of adding a fake app).
</p>
<p>
Also: "Explicit is better than implicit." :)
</p>
Resultshttps://code.djangoproject.com/ticket/12772#changeloghttps://code.djangoproject.com/ticket/11927
https://code.djangoproject.com/ticket/11927#11927: Allow manage.py dumpdata to dump YAML in block styleTue, 22 Sep 2009 13:54:20 GMTsampablokuper<p>
Using
</p>
<pre class="wiki">python manage.py dumpdata --format=yaml
</pre><p>
produces output in <a class="ext-link" href="http://pyyaml.org/wiki/PyYAMLDocumentation#Dictionarieswithoutnestedcollectionsarenotdumpedcorrectly"><span class="icon">​</span>flow style</a>. That's OK for automated processing, but it isn't anything like as human-readable as block style YAML. For people who, like me, need to edit the fixtures manually, it would be very useful to be able to do something like:
</p>
<pre class="wiki">python manage.py dumpdata --format=yaml --flowstyle=false
</pre>Resultshttps://code.djangoproject.com/ticket/11927#changeloghttps://code.djangoproject.com/ticket/15859
https://code.djangoproject.com/ticket/15859#15859: Allow more precise placement of admin inlinesWed, 20 Apr 2011 03:58:23 GMTJeff Blaine <jblaine@…><p>
I just had to copy django/contrib/admin/templates/admin/change_form.html (bad!) for wholesale replacement in my site for an easily fixable reason: I wanted my TabularInline to show at the top of the change form for my model, not at the bottom.
</p>
<p>
Inlines are for composition of a form, they're not a second-class citizen like "related objects". As such, I believe there should be a way to allow someone to at least choose top or bottom.
</p>
Resultshttps://code.djangoproject.com/ticket/15859#changeloghttps://code.djangoproject.com/ticket/14671
https://code.djangoproject.com/ticket/14671#14671: Allow overriding of ModelChoiceField.choicesFri, 12 Nov 2010 05:20:17 GMTsimon29<p>
This patch fixes a validation bug when attempting to override choices manually on a ModelChoiceField. Comments in code suggest this should be able to be done.
</p>
<p>
Note, this used to work until the recent model/form validation changes.
</p>
Resultshttps://code.djangoproject.com/ticket/14671#changeloghttps://code.djangoproject.com/ticket/18166
https://code.djangoproject.com/ticket/18166#18166: Allow the formset class to contribute kwargs to form instancesWed, 18 Apr 2012 13:39:01 GMTtevans<p>
When we use a formset, each form is instantiated by the method <tt>BaseFormSet._construct_forms()</tt>, which is called from <tt>BaseFormSet.__init__()</tt>
</p>
<p>
<tt>_construct_forms()</tt> allows for additional kwargs to be passed through to the individual form constructor, but <tt>BaseFormSet.__init__()</tt> does not provide any mechanism for kwargs to be passed through to the <tt>_construct_forms()</tt> call.
</p>
<p>
Also, we may not be able to supply a static unchanging list of kwargs that should be supplied to each form constructor - the kwargs we want to pass may depend upon the specific instance of the form being instantiated.
</p>
<p>
I propose the following changes:
</p>
<p>
Add a <tt>form_kwargs</tt> argument to <tt>BaseFormSet.__init__()</tt>. This would be stored on self, and consumed in <tt>BaseFormSet._construct_forms()</tt>
</p>
<p>
Add a method, <tt>BaseFormSet._kwargs_for_form(self, i)</tt>. This method would be called for each form instantiated, passing the index of the form within the formset. The return value of this method would be merged with the form_kwargs supplied in <tt>BaseFormSet.__init__()</tt> and used to instantiate the form.
</p>
<p>
With these changes, a user could add additional constructor arguments to all forms by passing in form_kwargs to the formset constructor, and could add additional constructor arguments to specific forms by implementing _kwargs_for_form on a derived BaseFormSet class.
</p>
<p>
(I found it strange, when <tt>BaseFormSet</tt> was written, it was clearly intended to be able to pass kwargs to the forms - <tt>_construct_form()</tt> allows for it, there just is not the plumbing to do so. I worked around this by redefining - copy/pasting - the <tt>_construct_forms()</tt> method in my derived <tt>BaseFormSet</tt> class)
</p>
<p>
Patch doesn't have tests or doc changes, will add if this idea gets traction.
</p>
<p>
Cheers
</p>
<p>
Tom
</p>
Resultshttps://code.djangoproject.com/ticket/18166#changeloghttps://code.djangoproject.com/ticket/20757
https://code.djangoproject.com/ticket/20757#20757: A more Object-Oriented URLResolverWed, 17 Jul 2013 17:58:09 GMTfcurella<p>
Currently, the <tt>RegexURLResolver</tt> is populated using tuples.
</p>
<p>
Because of that, code that tries to inspect the resolver will end up containg awkward indexing like this (semplified code for clarity's sake):
</p>
<pre class="wiki">def get_urlformat(urlname):
"""
Given a URL name, returns the URL as a string suitable for string.format.
Example::
urlpatterns = patterns('',
url(r'^extra/(?P&lt;extra&gt;\w+)/$', empty_view, name="named-url2"),
)
&gt;&gt;&gt; get_urlformat('named-url2')
'extra/%(extra)s/'
"""
resolver = get_resolver()
return resolver.reverse_dict[urlname][0][0][0]
</pre><p>
My proposal is to replace tuples with a tuple-like object whose elements can be accessed by using attribute names. That way, the above method could become:
</p>
<pre class="wiki">def get_urlformat(urlname):
"""
Given a URL name, returns the URL as a string suitable for string.format.
Example::
urlpatterns = patterns('',
url(r'^extra/(?P&lt;extra&gt;\w+)/$', empty_view, name="named-url2"),
)
&gt;&gt;&gt; get_urlformat('named-url2')
'extra/%(extra)s/'
"""
resolver = get_resolver()
urlbit = resolver.reverse_dict[urlname].urlbits[0]
return urlbit.format
</pre><p>
I realize this is mostly aesthetic, and there could be performance implications since the URLResolver is probably the most hit codepath, so I appreciate every kind of opinion.
</p>
<p>
The attached patch is still a draft, it definitely needs more extensive test coverage, but it's a start to get the idea.
</p>
Resultshttps://code.djangoproject.com/ticket/20757#changeloghttps://code.djangoproject.com/ticket/14476
https://code.djangoproject.com/ticket/14476#14476: annotate, default aggregation naming and filter annoyanceFri, 15 Oct 2010 12:59:25 GMTdirleyrls<p>
Going straight to the point, if I do the following:
</p>
<pre class="wiki">from django.db import models
...
class Answer(models.Model):
entry = models.ForeignKey(Question)
...
qsa = Question.objects.annotate(answer_count=models.Count('answer')).filter(answer_count=0)
qsb = Question.objects.annotate(models.Count('answer')).filter(answer__count=0)
</pre><p>
qsa will be correctly evaluted, but qsb will raise a "FieldError: Cannot resolve keyword 'count' into field. Choices are ... answer_ _count".
</p>
<p>
Now, isn't this annoying? The error message is lying!
</p>
Resultshttps://code.djangoproject.com/ticket/14476#changeloghttps://code.djangoproject.com/ticket/19259
https://code.djangoproject.com/ticket/19259#19259: Annotations generating inefficient SQL on PostgreSQLWed, 07 Nov 2012 19:25:34 GMThcarvalhoalves<p>
Considering the following models:
</p>
<pre class="wiki"> class Movie(EditableBase, TimestampBase):
year = models.PositiveSmallIntegerField(u"ano", null=True)
country = models.CharField(u"país", max_length=100, blank=True, null=True)
release_date = models.DateField(u"data de estréia", blank=True, null=True)
length = models.PositiveSmallIntegerField(u"duração", blank=True, null=True)
rating = models.PositiveIntegerField(u"avaliação", blank=True, null=True, choices=RATING_CHOICES)
suitable_for = models.PositiveSmallIntegerField(u"censura", blank=True, null=True, choices=AGE_CHOICES)
website_original = models.URLField(u"website", max_length=255, blank=True, null=True)
website_national = models.URLField(u"website (nacional)", max_length=255, blank=True, null=True)
synopsis = models.TextField(u"sinopse", blank=True)
cover = models.ImageField(u"poster", upload_to=u'uploads/fichatecnica/', blank=True, null=True)
genres = models.ManyToManyField(MovieGenre, verbose_name=u"gêneros")
class MovieTheaterSession(models.Model):
start_date = models.DateField(u"início")
end_date = models.DateField(u"fim")
movie = models.ForeignKey(Movie, verbose_name=u"filme", related_name='sessions')
</pre><p>
If we annotate the query to count the number of sessions:
</p>
<pre class="wiki"> &gt;&gt;&gt; Movie.objects.all().annotate(sessions_count=Count('sessions')).order_by('release_date')[:60]
</pre><p>
Django generates pretty inneficient SQL by GROUPing BY on all fields from the parent:
</p>
<pre class="wiki"> SELECT "movies_movie"."id", "movies_movie"."creation_date", "movies_movie"."modification_date", "movies_movie"."year", "movies_movie"."country", "movies_movie"."release_date", "movies_movie"."length", "movies_movie"."rating", "movies_movie"."suitable_for", "movies_movie"."website_original", "movies_movie"."website_national", "movies_movie"."synopsis", "movies_movie"."cover", COUNT("theaters_movietheatersession"."id") AS "sessions_count" FROM "movies_movie" LEFT OUTER JOIN "theaters_movietheatersession" ON ("movies_movie"."id" = "theaters_movietheatersession"."movie_id") GROUP BY "movies_movie"."id", "movies_movie"."creation_date", "movies_movie"."modification_date", "movies_movie"."year", "movies_movie"."country", "movies_movie"."release_date", "movies_movie"."length", "movies_movie"."rating", "movies_movie"."suitable_for", "movies_movie"."website_original", "movies_movie"."website_national", "movies_movie"."synopsis", "movies_movie"."cover" ORDER BY "movies_movie"."release_date" ASC LIMIT 60
Time: 892,122 ms
</pre><p>
EXPLAIN shows the database is sorting all fields from the GROUP BY clause:
</p>
<pre class="wiki"> Limit (cost=2250.37..2250.52 rows=60 width=502)
-&gt; Sort (cost=2250.37..2256.15 rows=2311 width=502)
Sort Key: (count(theaters_movietheatersession.id)), movies_movie.release_date
-&gt; GroupAggregate (cost=1975.47..2170.56 rows=2311 width=502)
-&gt; Sort (cost=1975.47..1986.94 rows=4586 width=502)
Sort Key: movies_movie.id, movies_movie.creation_date, movies_movie.modification_date, movies_movie.year, movies_movie.country, movies_movie.release_date, movies_movie.length, movies_movie.rating, movies_movie.suitable_for, movies_movie.website_original, movies_movie.website_national, movies_movie.synopsis, movies_movie.cover
-&gt; Merge Left Join (cost=0.00..660.58 rows=4586 width=502)
Merge Cond: (movies_movie.id = theaters_movietheatersession.movie_id)
-&gt; Index Scan using movies_movie_pkey on movies_movie (cost=0.00..283.14 rows=2311 width=498)
-&gt; Index Scan using theaters_movietheatersession_movie_id on theaters_movietheatersession (cost=0.00..314.34 rows=4586 width=8)
</pre><p>
It suffices to GROUP BY by the PK field:
</p>
<pre class="wiki"> SELECT "movies_movie"."id", "movies_movie"."creation_date", "movies_movie"."modification_date", "movies_movie"."year", "movies_movie"."country", "movies_movie"."release_date", "movies_movie"."length", "movies_movie"."rating", "movies_movie"."suitable_for", "movies_movie"."website_original", "movies_movie"."website_national", "movies_movie"."synopsis", "movies_movie"."cover", COUNT("theaters_movietheatersession"."id") AS "sessions_count" FROM "movies_movie" LEFT OUTER JOIN "theaters_movietheatersession" ON ("movies_movie"."id" = "theaters_movietheatersession"."movie_id") GROUP BY "movies_movie"."id" ORDER BY "movies_movie"."release_date" ASC LIMIT 60
Time: 16,285 ms
</pre><p>
EXPLAIN shows the database doesn't need to sort anymore:
</p>
<pre class="wiki"> Limit (cost=786.42..786.57 rows=60 width=502)
-&gt; Sort (cost=786.42..792.20 rows=2311 width=502)
Sort Key: movies_movie.release_date
-&gt; GroupAggregate (cost=0.00..706.62 rows=2311 width=502)
-&gt; Merge Left Join (cost=0.00..660.58 rows=4586 width=502)
Merge Cond: (movies_movie.id = theaters_movietheatersession.movie_id)
-&gt; Index Scan using movies_movie_pkey on movies_movie (cost=0.00..283.14 rows=2311 width=498)
-&gt; Index Scan using theaters_movietheatersession_movie_id on theaters_movietheatersession (cost=0.00..314.34 rows=4586 width=8)
</pre><p>
I've tried fixing it by setting the undocumented <tt>group_by</tt> attribute, but Django doesn't seem to pick it up:
</p>
<pre class="wiki">class MovieManager(models.Manager):
def with_sessions(self):
qs = self.get_query_set().annotate(
sessions_count=Count('sessions'))
qs.group_by = ['id']
return qs
</pre><p>
I'm using Django 1.4 and PostgreSQL 9.1.
</p>
Resultshttps://code.djangoproject.com/ticket/19259#changeloghttps://code.djangoproject.com/ticket/12651
https://code.djangoproject.com/ticket/12651#12651: AutoSlugField, that can recreate unique slugs during saving.Wed, 20 Jan 2010 15:11:23 GMTCiantic<p>
Hi!
</p>
<p>
I would like to see something that can create <em>unique slugs</em> during <em>saving of the model</em> like <a class="ext-link" href="http://www.djangosnippets.org/snippets/728/"><span class="icon">​</span>AutoSlugField by GaretJax in djangosnippets</a>. That specific implementation might be too simple and not enough configurable, but if it were improved a little perhaps? There are several slug hacks in djangosnippets alone that tries to implement unique slugs, with varying results.
</p>
<p>
Naturally it should be <em>part of Django</em> since it is used by almost every project and every model. Housing fleet of utility libraries is not the nicest way to implement programs, I have stumbled with that a lot in the past.
</p>
Resultshttps://code.djangoproject.com/ticket/12651#changeloghttps://code.djangoproject.com/ticket/10933
https://code.djangoproject.com/ticket/10933#10933: Avoid " TypeError: Cannot convert Decimal("0.0000") to Decimal " when the decimal module has been reloadedMon, 27 Apr 2009 09:54:32 GMTgagravarr<p>
If for some reason the decimal module gets reloaded (seems fairly easy to trigger when using runserver, but we've seen it once or twice wiht apache + mod_python too), then calling db_obj.save() on a model with a decimal field will blow up (see <a class="ext-link" href="http://groups.google.com/group/django-users/browse_thread/thread/7da92d7f5d6e2a53"><span class="icon">​</span>http://groups.google.com/group/django-users/browse_thread/thread/7da92d7f5d6e2a53</a> for example)
</p>
<p>
One workaround is to have extra code in the decimal field logic in django, to detect when the value is no longer being recognised as a Decimal but is one, and port it over to the new decimal object.
</p>
<pre class="wiki">--- django/db/models/fields/__init__.py (revision 9643)
+++ django/db/models/fields/__init__.py (working copy)
@@ -579,6 +579,11 @@
def to_python(self, value):
if value is None:
return value
+ # Work around reload(decimal) problems
+ if not isinstance(value, decimal.Decimal) and \
+ len(str(value.__class__).split("'")) == 3 and \
+ str(value.__class__).split("'")[1] == 'decimal.Decimal':
+ return decimal.Decimal( value.to_eng_string() )
try:
return decimal.Decimal(value)
except decimal.InvalidOperation:
</pre><p>
I'm not sure if this is an ideal fix or not, but it'd be great to have this (or something like it) in django to help avoid the issue
</p>
Resultshttps://code.djangoproject.com/ticket/10933#changeloghttps://code.djangoproject.com/ticket/20287
https://code.djangoproject.com/ticket/20287#20287: BaseContext (and it's subclasses) lack emulation of dictionary items()Thu, 18 Apr 2013 19:52:24 GMTKeryn Knight <django@…><p>
Given the Context usually behaves like a dictionary (though underlying it is obviously also a stack), I was somewhat surprised that it has no <tt>items()</tt> nor <tt>iteritems()</tt> methods that would allow it to be iterated as one might expect to, though it does have an <tt>__iter__()</tt> method, which could probably be used if this has any merit.
</p>
Resultshttps://code.djangoproject.com/ticket/20287#changeloghttps://code.djangoproject.com/ticket/14688
https://code.djangoproject.com/ticket/14688#14688: BaseInlineFormSet does not support "auto_id"Mon, 15 Nov 2010 01:56:22 GMTvicvicvic<p>
<tt>BaseInlineFormSet.__init__</tt> does not accept the <tt>auto_id</tt> argument, unlike its ancestors. Furthmore, its parent <tt>BaseModelFormSet</tt> takes <tt>**kwargs</tt> and passes them along.
</p>
<p>
I can't think of a good reason for this omission/difference. I've attached a small patch to "match" <tt>BaseInlineFormSet.__init__</tt> with <tt>BaseModelFormSet.__init__</tt>. The patch puts the "new" <tt>auto_id</tt> argument last in order to maximize backwards compatibility (the order is different for <tt>BaseModelFormSet</tt>).
</p>
<p>
Arguably, both <tt>prefix</tt> and <tt>auto_id</tt> could be removed from the explicit arg list since they're just passed along (in both <tt>BaseModelFormSet</tt> and <tt>BaseInlineFormSet</tt>).
</p>
Resultshttps://code.djangoproject.com/ticket/14688#changeloghttps://code.djangoproject.com/ticket/18597
https://code.djangoproject.com/ticket/18597#18597: `BaseInlineFormSet` should attempt to get it's queryset from it's instance related manager before falling back to it's model's default managerMon, 09 Jul 2012 01:19:52 GMTcharettes<p>
The newly introduced <tt>prefetch_related</tt> method can be quite handy to avoid unnecessary queries (thanks Luke :), however it's quite useless when used with <tt>BaseInlineFormSet</tt> since <a class="ext-link" href="https://github.com/django/django/blob/4a103086d5c67fa4fcc53c106c9fdf644c742dd8/django/forms/models.py#L694"><span class="icon">​</span>it won't even try to get its needed `queryset` from the related manager</a>.
</p>
<p>
i.e.
</p>
<div class="code"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> models
<span class="k">class</span> <span class="nc">Author</span><span class="p">(</span>models<span class="o">.</span>Model<span class="p">):</span>
name <span class="o">=</span> models<span class="o">.</span>CharField<span class="p">(</span>max_length<span class="o">=</span><span class="mi">255</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span>models<span class="o">.</span>Model<span class="p">):</span>
name <span class="o">=</span> models<span class="o">.</span>CharField<span class="p">(</span>max_length<span class="o">=</span><span class="mi">255</span><span class="p">)</span>
author <span class="o">=</span> models<span class="o">.</span>ForeignKey<span class="p">(</span>Author<span class="p">,</span> related_name<span class="o">=</span><span class="s">'books'</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
<span class="c"># Needed because `BaseModelFormSet.get_query_set` wants an ordered set or issue another query</span>
ordering <span class="o">=</span> <span class="p">(</span><span class="s">'pk'</span><span class="p">,)</span>
</pre></div><pre class="wiki">In [1]: from django.conf import settings
In [2]: from django.db import connection
In [3]: from library.models import *
In [4]: from django.forms.models import inlineformset_factory
In [5]: a = Author.objects.create(name='David Abram')
In [6]: b1 = Book.objects.create(name='Becoming Animal', author=a)
In [7]: b2 = Book.objects.create(name='The Spell of the Sensuous', author=a)
In [8]: BookInlineFormSet = inlineformset_factory(Author, Book)
In [9]: settings.DEBUG = True
In [10]: instance = Author.objects.prefetch_related('books').get()
In [11]: BookInlineFormSet(instance=instance)
Out[11]: &lt;django.forms.formsets.BookFormFormSet at 0x3c68d50&gt;
In [12]: print connection.queries
[{u'time': u'0.000', u'sql': u'SELECT "library_author"."id", "library_author"."name" FROM "library_author"'},
{u'time': u'0.000', u'sql': u'SELECT "library_book"."id", "library_book"."name", "library_book"."author_id" FROM "library_book" WHERE "library_book"."author_id" IN (1) ORDER BY "library_book"."id" ASC'},
{u'time': u'0.000', u'sql': u'SELECT "library_book"."id", "library_book"."name", "library_book"."author_id" FROM "library_book" WHERE "library_book"."author_id" = 1 ORDER BY "library_book"."id" ASC'}]
</pre><p>
I guess it's only a matter of time before people start trying to optimize their formsets (or their <tt>ModelAdmin</tt> by overriding <tt>get_queryset</tt>) and stumble on this <em>limitation</em>.
</p>
<p>
I've written a patch (I'll create a pull request) for which I'll write tests if this optimization is <em>Accepted</em>.
</p>
Resultshttps://code.djangoproject.com/ticket/18597#changeloghttps://code.djangoproject.com/ticket/7028
https://code.djangoproject.com/ticket/7028#7028: Better admin raw_id_fields feedbackWed, 16 Apr 2008 00:07:22 GMTMarcob <marcoberi@…><p>
When you select an item for a raw-id-fields, the description of the id showes up only after saving current record. This is a major drawback for the user when id isn't a slug or a "self speaking" id. This little patch solve the problem showing the description immediately after user chooses the item in the raw id popup window.
</p>
Resultshttps://code.djangoproject.com/ticket/7028#changeloghttps://code.djangoproject.com/ticket/6363
https://code.djangoproject.com/ticket/6363#6363: Bug with has_permission method of AdminSite class.Fri, 11 Jan 2008 19:15:42 GMTmichelts<p>
I found a bug when using the has_permission method of the AdminSite class to filter which users can access the admin page:
</p>
<pre class="wiki">class SuperuserAdminSite(admin.AdminSite):
def has_permission(self, request):
return super(SuperuserAdminSite, self).has_permission(request) and request.user.is_superuser
admin_site = SuperuserAdminSite()
</pre><p>
When I try to log on a user that is not a superuser, it already get the login but stay on the login page (with the header but no application loaded), I think this is a bug :) The user should get a error message as if it passed a wrong password or such, isn´t it?
</p>
Resultshttps://code.djangoproject.com/ticket/6363#changeloghttps://code.djangoproject.com/ticket/19527
https://code.djangoproject.com/ticket/19527#19527: bulk_create() can set the primary keyThu, 27 Dec 2012 12:42:00 GMTTuttle<p>
(Sorry if I missed a pre-existing ticket for this.)
</p>
<p>
There is an IMO big caveat of bulk_create(): It does not set primary key of objects it creates.
</p>
<p>
In my current project, using bulk_create would improve performance, but as I often need an id of the newly created objects, I have to save them one by one.
</p>
<p>
I think it would be perfect if bulk_create starts to set the primary keys of the objects in the given sequence. At least postgresql supports it ("RETURNING id" clause gives us a set of id's).
</p>
Resultshttps://code.djangoproject.com/ticket/19527#changeloghttps://code.djangoproject.com/ticket/22669
https://code.djangoproject.com/ticket/22669#22669: bulk_create with empty model fields fails on oracleWed, 21 May 2014 04:35:51 GMTsns1081@…<p>
I did the minimal example for reproducing this bug. Model looks very simple:
</p>
<div class="code"><pre><span class="k">class</span> <span class="nc">ProbaModel</span><span class="p">(</span>models<span class="o">.</span>Model<span class="p">):</span>
num <span class="o">=</span> models<span class="o">.</span>IntegerField<span class="p">(</span>null<span class="o">=</span><span class="bp">True</span><span class="p">,</span> blank<span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div><p>
When i tried to run the following test code:
</p>
<div class="code"><pre><span class="k">class</span> <span class="nc">ProbaTestCase</span><span class="p">(</span>TestCase<span class="p">):</span>
<span class="k">def</span> <span class="nf">test_bulk_create</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
ProbaModel<span class="o">.</span>objects<span class="o">.</span>bulk_create<span class="p">(</span>
<span class="p">[</span>
ProbaModel<span class="p">(</span>num<span class="o">=</span><span class="mi">1</span><span class="p">),</span>
ProbaModel<span class="p">()</span>
<span class="p">]</span>
<span class="p">)</span>
</pre></div><p>
I got an
</p>
<pre class="wiki">Traceback (most recent call last):
File "/home/sns/devel/proba/proba/app1/tests.py", line 10, in test_bulk_create
ProbaModel()
File "/home/sns/devel/proba/local/lib/python2.7/site-packages/django/db/models/manager.py", line 160, in bulk_create
return self.get_queryset().bulk_create(*args, **kwargs)
File "/home/sns/devel/proba/local/lib/python2.7/site-packages/django/db/models/query.py", line 359, in bulk_create
self._batched_insert(objs_without_pk, fields, batch_size)
File "/home/sns/devel/proba/local/lib/python2.7/site-packages/django/db/models/query.py", line 838, in _batched_insert
using=self.db)
File "/home/sns/devel/proba/local/lib/python2.7/site-packages/django/db/models/manager.py", line 232, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/home/sns/devel/proba/local/lib/python2.7/site-packages/django/db/models/query.py", line 1514, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/sns/devel/proba/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 903, in execute_sql
cursor.execute(sql, params)
File "/home/sns/devel/proba/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/home/sns/devel/proba/local/lib/python2.7/site-packages/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/sns/devel/proba/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/home/sns/devel/proba/local/lib/python2.7/site-packages/django/db/backends/oracle/base.py", line 816, in execute
return self.cursor.execute(query, self._param_generator(params))
DatabaseError: ORA-01790: expression must have same datatype as corresponding expression
</pre><p>
This bug confirmed on Oracle 11.2.0.4 and 12. Complete project located on my GitHub: <a class="ext-link" href="https://github.com/nsadovskiy/bulk_create_fail"><span class="icon">​</span>https://github.com/nsadovskiy/bulk_create_fail</a>
</p>
<p>
Solution that works fo me is patch on django/db/backends/oracle/base.py:
</p>
<pre class="wiki">*** base.py 2014-05-20 18:37:07.000000000 +0700
--- base.py 2014-05-20 18:41:45.000000000 +0700
***************
*** 467,509 ****
return '%s_TR' % util.truncate_name(table, name_length).upper()
def bulk_insert_sql(self, fields, num_values):
! MAPPER = {
! 'CharField': 'to_nchar(%s)',
! 'CommaSeparatedIntegerField': 'to_nchar(%s)',
! 'EmailField': 'to_nchar(%s)',
! 'FileField': 'to_nchar(%s)',
! 'FilePathField': 'to_nchar(%s)',
! 'ImageField': 'to_nchar(%s)',
! 'SlugField': 'to_nchar(%s)',
! 'URLField': 'to_nchar(%s)',
!
! 'IPAddressField': 'to_char(%s)',
! 'GenericIPAddressField': 'to_char(%s)',
!
! 'AutoField': 'to_number(%s)',
! 'BigIntegerField': 'to_number(%s)',
! 'BooleanField': 'to_number(%s)',
! 'DecimalField': 'to_number(%s)',
! 'FloatField': 'to_number(%s)',
! 'IntegerField': 'to_number(%s)',
! 'NullBooleanField': 'to_number(%s)',
! 'PositiveIntegerField': 'to_number(%s)',
! 'PositiveSmallIntegerField': 'to_number(%s)',
! 'SmallIntegerField': 'to_number(%s)',
! 'ForeignKey': 'to_number(%s)',
! 'ManyToManyField': 'to_number(%s)',
! 'OneToOneField': 'to_number(%s)',
!
! 'DateField': 'to_date(%s)',
!
! 'DateTimeField': 'to_timestamp(%s)',
! 'TimeField': 'to_timestamp(%s)',
!
! 'BinaryField': 'to_blob(%s)',
!
! 'TextField': 'to_nclob(%s)'
! }
! items_sql = "SELECT %s FROM DUAL" % ", ".join([MAPPER.get(field.get_internal_type(), '%s') for field in fields])
return " UNION ALL ".join([items_sql] * num_values)
--- 467,473 ----
return '%s_TR' % util.truncate_name(table, name_length).upper()
def bulk_insert_sql(self, fields, num_values):
! items_sql = "SELECT %s FROM DUAL" % ", ".join(["%s"] * len(fields))
return " UNION ALL ".join([items_sql] * num_values)
</pre>Resultshttps://code.djangoproject.com/ticket/22669#changeloghttps://code.djangoproject.com/ticket/18929
https://code.djangoproject.com/ticket/18929#18929: CachedFilesMixin is not compatible with S3BotoStorageSat, 08 Sep 2012 07:02:41 GMTidanzalz@…<p>
CachedFilesMixin breaks S3BotoStorage when used together because it applies "unquote" on the result of the storage url method.
see <a class="ext-link" href="https://github.com/django/django/pull/321"><span class="icon">​</span>https://github.com/django/django/pull/321</a> for more details
</p>
Resultshttps://code.djangoproject.com/ticket/18929#changeloghttps://code.djangoproject.com/ticket/5372
https://code.djangoproject.com/ticket/5372#5372: Cache inline ForeignKey optionsSun, 09 Sep 2007 21:36:10 GMTanonymousResultshttps://code.djangoproject.com/ticket/5372#changeloghttps://code.djangoproject.com/ticket/13875
https://code.djangoproject.com/ticket/13875#13875: cannot customize admin submit_rowSat, 03 Jul 2010 15:45:22 GMTdrul<p>
django submit_row inclusion tag doesn't pass extra_context from ModelAdmin.(add|change|..)_view to submit_row.html template. Because of that, i cannot add extra button to submit row (i.e. print invoice). this tag should pass whole context to the template
</p>
Resultshttps://code.djangoproject.com/ticket/13875#changeloghttps://code.djangoproject.com/ticket/15250
https://code.djangoproject.com/ticket/15250#15250: Cannot fill parent model instance in cacheWed, 09 Feb 2011 15:42:36 GMTvzima<p>
Continue of <a class="closed ticket" href="https://code.djangoproject.com/ticket/14371" title="Select related and parents (closed: worksforme)">#14371</a>
I tried again in django trunk (tested also in 1.2.4)
</p>
<p>
I have following models (in SQLite3)
</p>
<div class="code"><pre><span class="k">class</span> <span class="nc">Parent</span><span class="p">(</span>models<span class="o">.</span>Model<span class="p">):</span>
parent_int <span class="o">=</span> models<span class="o">.</span>IntegerField<span class="p">()</span>
<span class="k">class</span> <span class="nc">Child</span><span class="p">(</span>Parent<span class="p">):</span>
child_int <span class="o">=</span> models<span class="o">.</span>IntegerField<span class="p">()</span>
</pre></div><div class="code"><pre>In <span class="p">[</span><span class="mi">1</span><span class="p">]:</span> <span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> connection
In <span class="p">[</span><span class="mi">2</span><span class="p">]:</span> <span class="kn">from</span> <span class="nn">testmodule.models</span> <span class="kn">import</span> Parent<span class="p">,</span> Child
In <span class="p">[</span><span class="mi">3</span><span class="p">]:</span> Child<span class="o">.</span>objects<span class="o">.</span>create<span class="p">(</span>parent_int <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> child_int <span class="o">=</span> <span class="mi">2</span><span class="p">)</span>
Out<span class="p">[</span><span class="mi">3</span><span class="p">]:</span> <span class="o">&lt;</span>Child<span class="p">:</span> Child <span class="nb">object</span><span class="o">&gt;</span>
In <span class="p">[</span><span class="mi">4</span><span class="p">]:</span> Child<span class="o">.</span>objects<span class="o">.</span>get<span class="p">(</span>parent_int <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> child_int <span class="o">=</span> <span class="mi">2</span><span class="p">)</span><span class="o">.</span>parent_ptr
Out<span class="p">[</span><span class="mi">4</span><span class="p">]:</span> <span class="o">&lt;</span>Parent<span class="p">:</span> Parent <span class="nb">object</span><span class="o">&gt;</span>
In <span class="p">[</span><span class="mi">5</span><span class="p">]:</span> connection<span class="o">.</span>queries
Out<span class="p">[</span><span class="mi">5</span><span class="p">]:</span>
<span class="p">[{</span><span class="s">'sql'</span><span class="p">:</span> <span class="s">u'INSERT INTO "testmodule_parent" ("parent_int") VALUES (1)'</span><span class="p">,</span>
<span class="s">'time'</span><span class="p">:</span> <span class="s">'0.001'</span><span class="p">},</span>
<span class="p">{</span><span class="s">'sql'</span><span class="p">:</span> <span class="s">u'INSERT INTO "testmodule_child" ("parent_ptr_id", "child_int") VALUES (2, 2)'</span><span class="p">,</span>
<span class="s">'time'</span><span class="p">:</span> <span class="s">'0.000'</span><span class="p">},</span>
<span class="p">{</span><span class="s">'sql'</span><span class="p">:</span> <span class="s">u'SELECT "testmodule_parent"."id", "testmodule_parent"."parent_int", "testmodule_child"."parent_ptr_id", "testmodule_child"."child_int" FROM "testmodule_child" INNER JOIN "testmodule_parent" ON ("testmodule_child"."parent_ptr_id" = "testmodule_parent"."id") WHERE ("testmodule_parent"."parent_int" = 1 AND "testmodule_child"."child_int" = 2 )'</span><span class="p">,</span>
<span class="s">'time'</span><span class="p">:</span> <span class="s">'0.000'</span><span class="p">},</span>
<span class="p">{</span><span class="s">'sql'</span><span class="p">:</span> <span class="s">u'SELECT "testmodule_parent"."id", "testmodule_parent"."parent_int" FROM "testmodule_parent" WHERE "testmodule_parent"."id" = 2 '</span><span class="p">,</span>
<span class="s">'time'</span><span class="p">:</span> <span class="s">'0.000'</span><span class="p">}]</span>
In <span class="p">[</span><span class="mi">6</span><span class="p">]:</span> Child<span class="o">.</span>objects<span class="o">.</span>select_related<span class="p">(</span><span class="s">'parent'</span><span class="p">)</span><span class="o">.</span>get<span class="p">(</span>parent_int <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> child_int <span class="o">=</span> <span class="mi">2</span><span class="p">)</span><span class="o">.</span>parent_ptr
Out<span class="p">[</span><span class="mi">6</span><span class="p">]:</span> <span class="o">&lt;</span>Parent<span class="p">:</span> Parent <span class="nb">object</span><span class="o">&gt;</span>
In <span class="p">[</span><span class="mi">7</span><span class="p">]:</span> connection<span class="o">.</span>queries
Out<span class="p">[</span><span class="mi">7</span><span class="p">]:</span>
<span class="p">[{</span><span class="s">'sql'</span><span class="p">:</span> <span class="s">u'INSERT INTO "testmodule_parent" ("parent_int") VALUES (1)'</span><span class="p">,</span>
<span class="s">'time'</span><span class="p">:</span> <span class="s">'0.001'</span><span class="p">},</span>
<span class="p">{</span><span class="s">'sql'</span><span class="p">:</span> <span class="s">u'INSERT INTO "testmodule_child" ("parent_ptr_id", "child_int") VALUES (2, 2)'</span><span class="p">,</span>
<span class="s">'time'</span><span class="p">:</span> <span class="s">'0.000'</span><span class="p">},</span>
<span class="p">{</span><span class="s">'sql'</span><span class="p">:</span> <span class="s">u'SELECT "testmodule_parent"."id", "testmodule_parent"."parent_int", "testmodule_child"."parent_ptr_id", "testmodule_child"."child_int" FROM "testmodule_child" INNER JOIN "testmodule_parent" ON ("testmodule_child"."parent_ptr_id" = "testmodule_parent"."id") WHERE ("testmodule_parent"."parent_int" = 1 AND "testmodule_child"."child_int" = 2 )'</span><span class="p">,</span>
<span class="s">'time'</span><span class="p">:</span> <span class="s">'0.000'</span><span class="p">},</span>
<span class="p">{</span><span class="s">'sql'</span><span class="p">:</span> <span class="s">u'SELECT "testmodule_parent"."id", "testmodule_parent"."parent_int" FROM "testmodule_parent" WHERE "testmodule_parent"."id" = 2 '</span><span class="p">,</span>
<span class="s">'time'</span><span class="p">:</span> <span class="s">'0.000'</span><span class="p">},</span>
<span class="p">{</span><span class="s">'sql'</span><span class="p">:</span> <span class="s">u'SELECT "testmodule_parent"."id", "testmodule_parent"."parent_int", "testmodule_child"."parent_ptr_id", "testmodule_child"."child_int" FROM "testmodule_child" INNER JOIN "testmodule_parent" ON ("testmodule_child"."parent_ptr_id" = "testmodule_parent"."id") WHERE ("testmodule_parent"."parent_int" = 1 AND "testmodule_child"."child_int" = 2 )'</span><span class="p">,</span>
<span class="s">'time'</span><span class="p">:</span> <span class="s">'0.000'</span><span class="p">},</span>
<span class="p">{</span><span class="s">'sql'</span><span class="p">:</span> <span class="s">u'SELECT "testmodule_parent"."id", "testmodule_parent"."parent_int" FROM "testmodule_parent" WHERE "testmodule_parent"."id" = 2 '</span><span class="p">,</span>
<span class="s">'time'</span><span class="p">:</span> <span class="s">'0.000'</span><span class="p">}]</span>
</pre></div><p>
You can see that query is correct for selecting parent, but it's instance is not created in cache as usual and that leads to another select.
</p>
Resultshttps://code.djangoproject.com/ticket/15250#changeloghttps://code.djangoproject.com/ticket/4136
https://code.djangoproject.com/ticket/4136#4136: CharField(null=True, blank=True, unique=True)Tue, 24 Apr 2007 00:16:51 GMTDavid Cramer <dcramer@…><p>
When Django sends an update to MySQL for a NULL field it does not insert it as NULL (when you are in the admin).
</p>
<p>
e.g.
You have an openid_key field, which is the url of the users openid url. This url has to be unique and should be marked as such for db integrity.
</p>
<p>
You go into the admin and edit a user, they have no openid_key. You save the user. All is fine.
</p>
<p>
You go into the admin and edit a different user, they have no openid_key. You save the user. SQL throws a fit about the key needs to be unique.
</p>
<p>
Django tried to insert "" instead of NULL for this field.
</p>
Resultshttps://code.djangoproject.com/ticket/4136#changeloghttps://code.djangoproject.com/ticket/17637
https://code.djangoproject.com/ticket/17637#17637: Client side validation classes for formsSat, 04 Feb 2012 13:18:51 GMTkarthikabinav<p>
Having client side javascript validation for forms having common fields like username having only alphanumerics or password and Confirm password fields matching by providing a validation class.
</p>
<p>
For example a user should be able to do something like :
</p>
<pre class="wiki">forms.TextField(validators ="usernameValidation")
</pre><p>
And automatically a javascript validation for this form field should be in place.
</p>
<p>
One way to do it could be using HTML5 attributes like ticket <a class="closed ticket" href="https://code.djangoproject.com/ticket/16304" title="New feature: Add HTML5 'placeholder' attribute support to form fields. (closed: wontfix)">#16304</a>.
</p>
Resultshttps://code.djangoproject.com/ticket/17637#changeloghttps://code.djangoproject.com/ticket/494
https://code.djangoproject.com/ticket/494#494: Collapse in admin interface for inline related objectsMon, 12 Sep 2005 19:00:50 GMTjcstover@…<p>
It would be nice if there is a property to tell the admin interface to collapse the related object.
</p>
<p>
eg:
organisatie = meta.<a class="wiki" href="https://code.djangoproject.com/wiki/ForeignKey">ForeignKey</a>(Organisatie, edit_inline=meta.STACKED, edit_inline_style='collapse')
</p>
<p>
I changed line 610 in the django/views/admin/main.py to
t.append('&lt;fieldset class="module%s"&gt;\n' % ((rel_field.rel.edit_inline != meta.TABULAR) and ' aligned collapse' or ' collapse'))
and it works. But using a property would be better.
</p>
<p>
Thanks
</p>
Resultshttps://code.djangoproject.com/ticket/494#changeloghttps://code.djangoproject.com/ticket/23986
https://code.djangoproject.com/ticket/23986#23986: Collectstatic --clear fails if the static dir doesn't exist yetFri, 12 Dec 2014 15:24:01 GMTmvantellingen<p>
The --clear flag on collectstatic fails if the target directory doesn't exist yet.
</p>
<pre class="wiki">Traceback (most recent call last):
File "redacted/bin/manage.py", line 16, in &lt;module&gt;
execute_from_command_line(sys.argv)
File "redacted/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "redacted/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "redacted/local/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "redacted/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "redacted/local/lib/python2.7/site-packages/django/core/management/base.py", line 533, in handle
return self.handle_noargs(**options)
File "redacted/local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 168, in handle_noargs
collected = self.collect()
File "redacted/local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 89, in collect
self.clear_dir('')
File "redacted/local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 202, in clear_dir
dirs, files = self.storage.listdir(path)
File "redacted/local/lib/python2.7/site-packages/django/core/files/storage.py", line 270, in listdir
for entry in os.listdir(path):
OSError: [Errno 2] No such file or directory: '/redacted/public/static/2.1.0-dev'
</pre><p>
Adding
</p>
<pre class="wiki"> if not os.path.exists(self.storage.location):
return
</pre><p>
In Command.clear_dir() fixes the issue
</p>
Resultshttps://code.djangoproject.com/ticket/23986#changeloghttps://code.djangoproject.com/ticket/16281
https://code.djangoproject.com/ticket/16281#16281: ContentType.get_object_for_this_type using wrong database for creating objectThu, 16 Jun 2011 09:29:37 GMTtfrydrychewicz@…<p>
There is a subtle error in <a class="ext-link" href="https://docs.djangoproject.com/en/1.3/ref/contrib/contenttypes/#django.contrib.contenttypes.models.ContentType.get_object_for_this_type"><span class="icon">​</span>ContentType.get_object_for_this_type</a> method.
</p>
<pre class="wiki">def get_object_for_this_type(self, **kwargs):
return self.model_class()._default_manager.using(self._state.db).get(**kwargs)
</pre><p>
Database used to <em>get</em> <em>model_class</em> object is taken from self._state.db, which provides an error when <em>contenttype</em> model is hold in one database and model, of which object we're going to create, in another one.
</p>
<p>
Database should be provided using self.model_class().objects.db not self._state.db.
</p>
Resultshttps://code.djangoproject.com/ticket/16281#changeloghttps://code.djangoproject.com/ticket/13019
https://code.djangoproject.com/ticket/13019#13019: create_update: proxy object displayed instead of model verbose nameWed, 03 Mar 2010 15:05:51 GMTBeuc<p>
I get this kind of error at <a class="ext-link" href="http://localhost:8000/users/10/"><span class="icon">​</span>http://localhost:8000/users/10/</a>
</p>
<pre class="wiki">No &lt;django.utils.functional.__proxy__ object at 0x85c2fcc&gt; found for {'username__exact': u'10'}
</pre><p>
Apparently this is due to its non-unicode expansion:
</p>
<pre class="wiki"> # Note: User.Meta.verbose_name == _('user')
raise Http404("No %s found for %s"
% (model._meta.verbose_name, lookup_kwargs))
</pre><p>
It's fixed by using a Unicode string:
</p>
<pre class="wiki">u"No %s found for %s"
</pre><p>
Patch attached.
</p>
Resultshttps://code.djangoproject.com/ticket/13019#changeloghttps://code.djangoproject.com/ticket/18501
https://code.djangoproject.com/ticket/18501#18501: Custom fields as foreign keys fixThu, 21 Jun 2012 16:49:05 GMTmsopacua<p>
Custom fields which have a different database representation as python representation are not handled correctly when rendered as Select fields. The underlying cause is that the value on the model that has the foreign key is the database representation and it is not converted to python representation when model_to_dict is called.
</p>
<p>
The <a class="wiki" href="https://code.djangoproject.com/wiki/ForeignKey">ForeignKey</a> field subclasses RelatedField and Field, but RelatedField does not override it's value_from_object method to convert the value to python.
</p>
Resultshttps://code.djangoproject.com/ticket/18501#changeloghttps://code.djangoproject.com/ticket/13112
https://code.djangoproject.com/ticket/13112#13112: Customize map type in contrib.gis.maps.googleSun, 14 Mar 2010 06:28:10 GMTnbv4<p>
By default, all maps are of the type "G_PHYSICAL_MAP", I propose you add a keyword option "map_type" which specifies which type gets rendered:
</p>
<p>
<tt>map = GoogleMap(map_type='terrain', markers=[marker])</tt>
</p>
Resultshttps://code.djangoproject.com/ticket/13112#changeloghttps://code.djangoproject.com/ticket/2539
https://code.djangoproject.com/ticket/2539#2539: Custom tags and filters can be restricted by namespaceSun, 13 Aug 2006 04:09:44 GMTlimodou@…<p>
How to use namespace? For example,
</p>
<pre class="wiki">{% load example %}
{% example.testtag %}
</pre><p>
And I think if the namespace can be optional is better. I don't know
if it's useful, but sometimes I read others projects, and as I reading
the template, I don't know which tag is in which file. So find the
correct tag definition file is somewhat diffcult. If I can add
namespace in the front of a custom tag name, it'll be easy to locate
the source file.
</p>
<p>
The maillist discussion thread is <a class="ext-link" href="http://groups.google.com/group/django-developers/browse_frm/thread/2b5a4a31f0349d27/b92c96a8dccc214b#b92c96a8dccc214b"><span class="icon">​</span>HERE</a>
</p>
Resultshttps://code.djangoproject.com/ticket/2539#changeloghttps://code.djangoproject.com/ticket/5865
https://code.djangoproject.com/ticket/5865#5865: cycle template tag should accept a single argumentSat, 03 Nov 2007 01:52:35 GMTgwilson<p>
When passed a single argument, the cycle tag should treat it as an iterable to cycle through. For example, with the context:
</p>
<div class="code"><pre><span class="p">{</span><span class="s">'colors'</span><span class="p">:</span> <span class="p">[</span><span class="s">'red'</span><span class="p">,</span> <span class="s">'blue'</span><span class="p">,</span> <span class="s">'green'</span><span class="p">]}</span>
</pre></div><p>
you should be able to have a template like:
</p>
<div class="code"><pre>{% for row in mydata %}
<span class="nt">&lt;tr</span> <span class="na">class=</span><span class="s">"{% cycle colors %}"</span><span class="nt">&gt;</span>...<span class="nt">&lt;/tr&gt;</span>
{% endfor %}
</pre></div><p>
that would output:
</p>
<div class="code"><pre><span class="nt">&lt;tr</span> <span class="na">class=</span><span class="s">"red"</span><span class="nt">&gt;</span>...<span class="nt">&lt;/tr&gt;</span>
<span class="nt">&lt;tr</span> <span class="na">class=</span><span class="s">"blue"</span><span class="nt">&gt;</span>...<span class="nt">&lt;/tr&gt;</span>
<span class="nt">&lt;tr</span> <span class="na">class=</span><span class="s">"green"</span><span class="nt">&gt;</span>...<span class="nt">&lt;/tr&gt;</span>
<span class="nt">&lt;tr</span> <span class="na">class=</span><span class="s">"red"</span><span class="nt">&gt;</span>...<span class="nt">&lt;/tr&gt;</span>
...
</pre></div>Resultshttps://code.djangoproject.com/ticket/5865#changeloghttps://code.djangoproject.com/ticket/3461
https://code.djangoproject.com/ticket/3461#3461: DatabaseWrapper should pass through args and kwargs to underlying database adapterThu, 08 Feb 2007 20:38:52 GMTJack Moffitt <metajack@…><p>
Currently the DatabaseWrapper (at least for the postgresql_psycopg2end) does not pass args and kwargs for cursor() calls to the underlying database adapter. This makes it impossible to use the adapter fully at the low level. For example, to use dict cursors in psycopg2 you have to pass a different cursor factory via the cursor_factory keyword argument to cursor(). The attached patch passes through args and kwargs for cursor() calls.
</p>
Resultshttps://code.djangoproject.com/ticket/3461#changeloghttps://code.djangoproject.com/ticket/17508
https://code.djangoproject.com/ticket/17508#17508: DateDetailView should accept less specific dates, ie Year/Month or just YearFri, 06 Jan 2012 12:22:31 GMTAndrewIngram<p>
DateDetailView currently expects segments for year, month and day in the URL. This introduces the requirement to have an archive page for each level of the date; ie a year archive, a month archive, and a day archive:
</p>
<p>
/2012/
/2012/jan/
/2012/jan/06/
/2012/jan/06/blog-entry-name/
</p>
<p>
I don't think I'm inaccurate in saying that most bloggers (as opposed to news sites) don't usually create more than one post a day, and many (myself included) have a frequency of much less than once per month. This means we're introducing views such as day archive that have exactly the same information as the higher levels. As a URL purist, I don't like unnecessary segments in my schema and unnecessary pages in my information architecture.
</p>
<p>
In my case my URL structure is as follows, I don't use DayArchive at all:
</p>
<p>
/2012/
/2012/jan/
/2012/jan/blog-entry-name/
</p>
<p>
I've achieved this by creating my own version of DateDetailView that removes the use of DayMixin, but I think this can also be achieved by modifying DateDetailView itself to allow looser date matching using configuration of the view itself.
</p>
<p>
Is this a common enough use case to be worth making the change in Django itself? I think it can be done without affecting backwards compatibility.
</p>
Resultshttps://code.djangoproject.com/ticket/17508#changeloghttps://code.djangoproject.com/ticket/23714
https://code.djangoproject.com/ticket/23714#23714: `date` filter raises an exception for naive datetimes during DST changeSun, 26 Oct 2014 01:48:42 GMTmbertheau<p>
When an exception, that would normally - with <tt>DEBUG=True</tt> - be displayed in the detailed 500 page, occurs during the DST/no-DST ambiguous hour of the geographical area that is set as TIMEZONE, the handler crashes with <tt>AmbiguousTimeError</tt>. This seriously limits the ability of many developers to develop and Django applications for a time span of 1/8760 of the year. This is unacceptable! ;)
</p>
<pre class="wiki">2014-10-26 02:40:14,104 ERROR django.request :handle_uncaught_exception 231 Internal Server Error: /dashboard/suppliers/
Traceback (most recent call last):
File "/home/markus/src/django/django/core/handlers/base.py", line 111, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/markus/src/django/django/db/transaction.py", line 394, in inner
return func(*args, **kwargs)
File "/home/markus/src/django/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/markus/src/django/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/markus/src/django/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/home/markus/src/django/django/views/generic/base.py", line 87, in dispatch
return handler(request, *args, **kwargs)
File "/home/markus/src/django/django/views/generic/list.py", line 145, in get
self.object_list = self.get_queryset()
File "/home/markus/src/machtfit/apps/dashboard/supplier/views.py", line 44, in get_queryset
.annotate(num_orders=Count('partner__order_line')))
File "/home/markus/src/django/django/db/models/query.py", line 802, in annotate
is_summary=False)
File "/home/markus/src/django/django/db/models/sql/query.py", line 1012, in add_aggregate
field_list, opts, self.get_initial_alias())
File "/home/markus/src/django/django/db/models/sql/query.py", line 1419, in setup_joins
names, opts, allow_many, fail_on_missing=True)
File "/home/markus/src/django/django/db/models/sql/query.py", line 1383, in names_to_path
self.raise_field_error(opts, name)
File "/home/markus/src/django/django/db/models/sql/query.py", line 1389, in raise_field_error
"Choices are: %s" % (name, ", ".join(available)))
FieldError: Cannot resolve keyword u'order_line' into field. Choices are: &lt;irrelevant&gt;
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/home/markus/src/django/django/contrib/staticfiles/handlers.py", line 64, in __call__
return self.application(environ, start_response)
File "/home/markus/src/django/django/core/handlers/wsgi.py", line 187, in __call__
response = self.get_response(request)
File "/home/markus/src/django/django/core/handlers/base.py", line 199, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/home/markus/src/django/django/core/handlers/base.py", line 236, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/home/markus/src/django/django/views/debug.py", line 91, in technical_500_response
html = reporter.get_traceback_html()
File "/home/markus/src/django/django/views/debug.py", line 350, in get_traceback_html
return t.render(c)
File "/home/markus/src/django/django/template/base.py", line 148, in render
return self._render(context)
File "/home/markus/src/django/django/test/utils.py", line 88, in instrumented_test_render
return self.nodelist.render(context)
File "/home/markus/src/django/django/template/base.py", line 844, in render
bit = self.render_node(node, context)
File "/home/markus/src/django/django/template/debug.py", line 80, in render_node
return node.render(context)
File "/home/markus/src/django/django/template/debug.py", line 90, in render
output = self.filter_expression.resolve(context)
File "/home/markus/src/django/django/template/base.py", line 624, in resolve
new_obj = func(obj, *arg_vals)
File "/home/markus/src/django/django/template/defaultfilters.py", line 769, in date
return format(value, arg)
File "/home/markus/src/django/django/utils/dateformat.py", line 343, in format
return df.format(format_string)
File "/home/markus/src/django/django/utils/dateformat.py", line 35, in format
pieces.append(force_text(getattr(self, piece)()))
File "/home/markus/src/django/django/utils/dateformat.py", line 268, in r
return self.format('D, j M Y H:i:s O')
File "/home/markus/src/django/django/utils/dateformat.py", line 35, in format
pieces.append(force_text(getattr(self, piece)()))
File "/home/markus/src/django/django/utils/dateformat.py", line 136, in O
seconds = self.Z()
File "/home/markus/src/django/django/utils/dateformat.py", line 189, in Z
offset = self.timezone.utcoffset(self.data)
File "/home/markus/.virtualenvs/machtfit/local/lib/python2.7/site-packages/pytz/tzinfo.py", line 406, in utcoffset
dt = self.localize(dt, is_dst)
File "/home/markus/.virtualenvs/machtfit/local/lib/python2.7/site-packages/pytz/tzinfo.py", line 349, in localize
raise AmbiguousTimeError(dt)
AmbiguousTimeError: 2014-10-26 02:40:14.190834
</pre>Resultshttps://code.djangoproject.com/ticket/23714#changeloghttps://code.djangoproject.com/ticket/15522
https://code.djangoproject.com/ticket/15522#15522: delete_model on admin delete actionMon, 28 Feb 2011 17:42:46 GMTDivad<p>
Based on [Ticket <a class="closed ticket" href="https://code.djangoproject.com/ticket/11108" title="add a ModelAdmin.delete_model method, similar to ModelAdmin.save_model ... (closed: fixed)">#11108</a>]
</p>
<p>
The correction should also include this change in actions.py:
</p>
<pre class="wiki">47c47
&lt; modeladmin.delete_model(request,obj)
---
&gt; queryset.delete()
</pre><p>
To have the same result using delete_selected from actions.
</p>
Resultshttps://code.djangoproject.com/ticket/15522#changeloghttps://code.djangoproject.com/ticket/17962
https://code.djangoproject.com/ticket/17962#17962: Django Admin delete_view could benefit from extension pointsFri, 23 Mar 2012 17:13:52 GMTgcc<p>
I want to increase control over who can delete what objects using the admin interface.
</p>
<p>
<tt>delete_view</tt> calls <tt>has_delete_permission()</tt>, which is fine, but then it calls <tt>get_deleted_objects()</tt> from <tt>django.contrib.admin.util</tt>.
</p>
<p>
This is very hard to override without monkey-patching <tt>get_deleted_objects()</tt>, because it requires replacing the whole of <tt>delete_view</tt> just to change one line.
</p>
<p>
I propose calling a member method <tt>get_deleted_objects()</tt>, which by default just calls the one from <tt>util</tt>, to make it easy to override this behaviour.
</p>
<p>
I've attached a patch without tests, because the existing tests should check that this doesn't break anything.
</p>
Resultshttps://code.djangoproject.com/ticket/17962#changeloghttps://code.djangoproject.com/ticket/21113
https://code.djangoproject.com/ticket/21113#21113: django_admin_log table stores messages in different languages depending on which language was active while editing.Tue, 17 Sep 2013 13:53:44 GMTdimyur27@…<p>
In my project (in development) there are 3 different languages supported. Admin site supposed to have 3 main superusers, each is a native speaker of one of the languages. If one superuser edited an object, another one is not able to read what his fellow superuser previously did, because "Change history" page doesn't respect the current user language and displays the messages in the language that was current when the changes took place.
Maybe change_message field should be removed and the messages generated each time they are displayed.
So is object_repr, because object's representation may be dependant on the current language too.
Thank you.
</p>
Resultshttps://code.djangoproject.com/ticket/21113#changeloghttps://code.djangoproject.com/ticket/10827
https://code.djangoproject.com/ticket/10827#10827: django.auth create_permissions must clear the content type cache before creating permissionsWed, 15 Apr 2009 21:39:56 GMTseanl<p>
I hit a problem which took some time to track down, where at the DB flush stage in a sequence of tests (using TransactionTestCase) the recreation of permissions was failing with a FK constraint error.
</p>
<p>
This was caused by inserting a permission referring to a content type that didn't exist in the DB.
</p>
<p>
This happened because the content type was still in the cache, even thought the django_content_type table had been truncated.
</p>
<p>
The cache hadn't been cleared because post_syncdb signal dispatch had called create_permissions before calling update_contenttypes (which does clear the cache and recreate the content types correctly).
</p>
<p>
The real problem here is that create_permissions and update_contenttypes are both connected to the post_syncdb signal, with the former depending on the latter having been run first, but the dispatcher doesn't guarantee order of dispatch (or rather it dispatches in the order the signal handlers are connected, but that order depends on the order in which modules are loading which is not well-defined). Unfortunately that's a hard problem to solve, and I don't have any ideas about that short of substantive changes to the signal dispatcher.
</p>
<p>
An easier solution to this particular problem is for create_permissions to clear the content types cache before it recreates permissions, that way the necesarry content types will be created as needed (see attached patch).
</p>
Resultshttps://code.djangoproject.com/ticket/10827#changeloghttps://code.djangoproject.com/ticket/19806
https://code.djangoproject.com/ticket/19806#19806: django_bash_completion clobbers upstream completion of ‘python’Tue, 12 Feb 2013 04:44:17 GMTandersk<p>
<tt>extras/django_bash_completion</tt> now tries to complete <tt>python manage.py</tt> in addition to <tt>./manage.py</tt> (<a class="closed ticket" href="https://code.djangoproject.com/ticket/12174" title="bash completion for python manage.py (closed: fixed)">#12174</a>), but this results in the upstream completion hook for <tt>python</tt> being entirely clobbered. For example, the upstream hook completes <tt>python -Q</tt>, but this is lost when loading <tt>django_bash_completion</tt>:
</p>
<pre class="wiki">$ python -Q &lt;TAB&gt;
new old warn warnall
$ . extras/django_bash_completion
$ python -Q &lt;TAB&gt;
AUTHORS .git/ LICENSE setup.py
CONTRIBUTING.rst .gitattributes MANIFEST.in tests/
django/ .gitignore README.rst .tx/
docs/ .hgignore scripts/
extras/ INSTALL setup.cfg
</pre><p>
That seems like a really unfriendly thing to do, especially on Linux distros where merely installing the Django package pulls in <tt>django_bash_completion</tt> automatically.
</p>
<p>
I don’t know of a way to install a completion hook for <tt>python manage.py</tt> without clobbering all of <tt>python</tt>, so I would propose that the second half of the script (starting at <tt>_python_django_completion</tt>) should be deleted entirely. Users who want bash completion can type <tt>./manage.py</tt> or <tt>django-admin</tt> instead.
</p>
Resultshttps://code.djangoproject.com/ticket/19806#changeloghttps://code.djangoproject.com/ticket/12405
https://code.djangoproject.com/ticket/12405#12405: django.contrib.auth.views.logout() should support LOGOUT_REDIRECT_URLSat, 19 Dec 2009 15:06:32 GMTcmwslw<p>
I was wondering why django.contrib.auth.views.logout() doesn't support a REDIRECT_URL override in the settings file as login() does. I'm aware that it is possible to specify a next_page argument, however, this is cumbersome if the urls.py containing logout() is a third party library such as django-registration. I haven't taken a good look at the source, but I am guessing this would be a simple patch to write in order to support LOGOUT_REDIRECT_URL. Before I work on it, I need to know if there are any possible regressions or if there are any opinions against this.
</p>
Resultshttps://code.djangoproject.com/ticket/12405#changeloghttps://code.djangoproject.com/ticket/24382
https://code.djangoproject.com/ticket/24382#24382: django.utils.numberformat should be UTF-8 safeSat, 21 Feb 2015 10:51:54 GMTjrief<p>
By adding
</p>
<pre class="wiki">from __future__ import unicode_literals
</pre><p>
to <tt>django/utils/numberformat.py</tt>, one could write formatters for numbers in charsets other than ASCII, for instance code block U+2150 through U+218F, which contains the representation of Roman numbers in UTF-8.
</p>
Resultshttps://code.djangoproject.com/ticket/24382#changeloghttps://code.djangoproject.com/ticket/20098
https://code.djangoproject.com/ticket/20098#20098: Django validate command fails to detect that multiple models declare the same db_tableWed, 20 Mar 2013 15:10:48 GMTcarsten.klein@…<p>
When declaring two models using a custom db_table setting in the Meta class, I found out that django failed to detect that the two models declared the same db_table and subsequently it will fail on syncdb when trying to create the same table twice.
</p>
<p>
This, of course, was introduced by copy&amp;paste, but at least django should report this on validate instead of failing when trying to syncdb.
</p>
Resultshttps://code.djangoproject.com/ticket/20098#changeloghttps://code.djangoproject.com/ticket/13664
https://code.djangoproject.com/ticket/13664#13664: Enable admin permission checks from outside the ModelAdmin [PATCH]Sat, 29 May 2010 09:21:10 GMTsebastian_noack<p>
At the moment there is no clean and convinient way to check for the admin permissions of a model from outside its ModelAdmin class. But for example, when I link from one model's admin to onther models's admin changelist, It would be good pratice to check first if the logged in user has the change permission for the other model. So it would be nice if the AdminSite, which is accessible from all ModelAdmin classes has methods to check those permissions for the admin of a given model. My patch adds the has_*_permission() methods from the ModelAdmin class also to the AdminSite class. But those methods in the AdminSite class takes also a model (or a string in the form 'app_label.model_name') and forwards the call to the corresponding method on the given models's admin class.
</p>
Resultshttps://code.djangoproject.com/ticket/13664#changeloghttps://code.djangoproject.com/ticket/20752
https://code.djangoproject.com/ticket/20752#20752: Error signals are not reliable, especially when dealing with database errorsMon, 15 Jul 2013 19:45:47 GMTtal@…<p>
In core.handlers.base, unhandled exceptions are processed as such:
</p>
<pre class="wiki"> except: # Handle everything else, including SuspiciousOperation, etc.
# Get the exception info now, in case another exception is thrown later.
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
</pre><p>
Which delivers the error signal to the various handlers (database transaction resets, things like Sentry etc).
However, the code that dispatches signals aborts the dispatch if any of the handlers fail (to try..except block):
</p>
<pre class="wiki"> for receiver in self._live_receivers(_make_id(sender)):
response = receiver(signal=self, sender=sender, **named)
responses.append((receiver, response))
return responses
</pre><p>
This is perfectly reasonable in most cases, but is problematic when dealing with top-level error handling, as this prevents the unhandled error from reaching handlers that just want to report it.
</p>
<p>
This is very noticeable in cases where "something bad" happens to the database connection, as the first handler is always the database rollback handler, which only catches DatabaseError, which excludes a lot of errors that can and do crop up in production
</p>
<pre class="wiki">def _rollback_on_exception(**kwargs):
from django.db import transaction
for conn in connections:
try:
transaction.rollback_unless_managed(using=conn)
except DatabaseError:
pass
</pre><p>
I think that it will be better to have the error signal dispatcher defer except raising until after all the handlers were called (or just swallow them all).
Alternatively, a different signal for error reporting is possible, but I think that's a little confusing.
</p>
<p>
Thoughts?
</p>
Resultshttps://code.djangoproject.com/ticket/20752#changeloghttps://code.djangoproject.com/ticket/23387
https://code.djangoproject.com/ticket/23387#23387: Error when saving inline formsets as new after a validation error.Fri, 29 Aug 2014 18:56:47 GMTjohnrtipton<p>
This bug seems to have been around for a long time, as I've tried this from version 1.4 up.
</p>
<p>
While in the admin, if you have a form with inline formsets and you try to do a save as new, it works properly, unless there is a validation error. If you get a validation error, Django sends you through the add_view which no longer has the "Save as new" option. If you click save here, you will get the error below:
</p>
<p>
ValueError at /admin/drawings/sow/add/
invalid literal for int() with base 10: <em>
Request Method: POST
Request URL: <a class="ext-link" href="http://127.0.0.1:8000/admin/drawings/sow/add/"><span class="icon">​</span>http://127.0.0.1:8000/admin/drawings/sow/add/</a>
Django Version: 1.6.6.dev20140829183230
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: </em>
Exception Location: /Users/tip/Dropbox/websites/isotekrms/django/db/models/fields/<span class="underline">init</span>.py in get_prep_value, line 613
Python Executable: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.6
</p>
<p>
I, have written a small patch that will check to see if the formset had validation errors and it was submitted as a save as new, it will set the context variable change=True which causes the "Save as new" button to show on the form again. Fixing the validation errors on the screen and pressing "Save as new" again will save the form properly.
</p>
Resultshttps://code.djangoproject.com/ticket/23387#changeloghttps://code.djangoproject.com/ticket/17834
https://code.djangoproject.com/ticket/17834#17834: ETag generated from empty content can break http cachingMon, 05 Mar 2012 15:48:27 GMTpaulegan<p>
The [source:/django/trunk/django/utils/cache.py?rev=17286#L100 patch_response_headers] function will set an ETag header using an md5 hash of the response content. Many responses like redirects can have an empty body and this results in the same ETag for each such response. The response headers may vary but an intermediate cache can serve an incorrect response because the ETag is not unique.
</p>
<p>
A simple solution is to not set ETag if the content is empty - see attached patch.
</p>
<div class="code"><pre><span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> HttpResponseRedirect
<span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">django.utils.cache</span> <span class="kn">import</span> patch_response_headers
<span class="o">&gt;&gt;&gt;</span> r1 <span class="o">=</span> HttpResponseRedirect<span class="p">(</span><span class="s">'/u1'</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> patch_response_headers<span class="p">(</span>r1<span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> r2 <span class="o">=</span> HttpResponseRedirect<span class="p">(</span><span class="s">'/u2'</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> patch_response_headers<span class="p">(</span>r2<span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> r1<span class="p">[</span><span class="s">'ETag'</span><span class="p">]</span> <span class="o">==</span> r2<span class="p">[</span><span class="s">'ETag'</span><span class="p">]</span>
<span class="bp">True</span>
</pre></div>Resultshttps://code.djangoproject.com/ticket/17834#changeloghttps://code.djangoproject.com/ticket/12890
https://code.djangoproject.com/ticket/12890#12890: extra() tables included twice do not generate aliasesWed, 17 Feb 2010 07:30:48 GMTsemenov<p>
The documentation at <a class="ext-link" href="http://docs.djangoproject.com/en/1.1/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none"><span class="icon">​</span>http://docs.djangoproject.com/en/1.1/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none</a> says: "When you add extra tables via the tables parameter, Django assumes you want that table included an extra time, if it is already included. That creates a problem, since the table name will then be given an alias."
</p>
<p>
That is not true even for simple cases:
</p>
<div class="code"><pre><span class="k">print</span> User<span class="o">.</span>objects\
<span class="o">.</span>extra<span class="p">(</span>tables<span class="o">=</span><span class="p">[</span><span class="s">'auth_user_group'</span><span class="p">],</span> where<span class="o">=</span><span class="p">[</span><span class="s">'auth_user.ud=auth_user_group.user_id'</span><span class="p">])</span>\
<span class="o">.</span>extra<span class="p">(</span>tables<span class="o">=</span><span class="p">[</span><span class="s">'auth_user_group'</span><span class="p">],</span> where<span class="o">=</span><span class="p">[</span><span class="s">'auth_user.ud=auth_user_group.user_id'</span><span class="p">])</span><span class="o">.</span>all<span class="p">()</span>
<span class="c"># crashes with OperationalError(1066, "Not unique table/alias: 'auth_user_group'")</span>
</pre></div><p>
This is a real-life example (with different models, of course) from my project. I have to run an extra() query against the same table <em>twice</em> to achieve the double filtration, but it's not working and doesn't even allow me to specify the aliases manually. A usual double filter() trick would probably work but it is also broken due to <a class="new ticket" href="https://code.djangoproject.com/ticket/12885" title="Bug: GenericRelation fails to join the related table from a inherited model (new)">#12885</a>.
</p>
Resultshttps://code.djangoproject.com/ticket/12890#changeloghttps://code.djangoproject.com/ticket/15590
https://code.djangoproject.com/ticket/15590#15590: FileField path isn't settableThu, 10 Mar 2011 06:31:12 GMTsimon29<p>
Currently we can't set filefield/imagefield's underlying filename, without loading the file and feeding it's contents into save(). Obviously this is grossly inefficient.
</p>
<p>
This is a simple patch that allows you to set the path like so --
</p>
<pre class="wiki">instance.myfile.path = 'uploads/new-path.avi'
</pre><p>
Previously, instance.myfile.path is read only. If you set instance.myfile then instance.myfile.path etc will raise a ValueError, The 'myfile' attribute has no file associated with it.
</p>
<p>
Works with FileField, ImageField, and anything else that uses a File object that is subclassed from FieldFile.
</p>
<p>
Check stackoverflow, google, etc- lots of people banging their heads trying to figure out why they can't simply set the filename.
</p>
Resultshttps://code.djangoproject.com/ticket/15590#changeloghttps://code.djangoproject.com/ticket/10244
https://code.djangoproject.com/ticket/10244#10244: FileFields can't be set to NULL in the dbThu, 12 Feb 2009 14:40:54 GMToyvind<p>
Saving FileFields with a none value sets the field to a empty string in the db and not NULL as it should.
</p>
Resultshttps://code.djangoproject.com/ticket/10244#changeloghttps://code.djangoproject.com/ticket/10191
https://code.djangoproject.com/ticket/10191#10191: Fix / Add support for radiobuttons after adding item with popup in Django AdminWed, 04 Feb 2009 10:22:41 GMTtrbs<p>
The following patch adds support for dynamically adding radiobutton items to the admin page.
</p>
<p>
Without this patch the newly added item through the popup menu does not get added to the page and
the user must reload the page before being able to select the new item.
</p>
<p>
The patch adds an extra case to dismissAddAnotherPopup in RelatedObjectsLookup.js which creates and appends the necessary html to the list of radiobuttons on the page.
</p>
<p>
Tested with django.contrib.redirects and a slightly modified version of django-podcast.
Works (for me) on Firefox, IE and Opera.
</p>
Resultshttps://code.djangoproject.com/ticket/10191#changeloghttps://code.djangoproject.com/ticket/11265
https://code.djangoproject.com/ticket/11265#11265: ForeignKey/OneToOneField should support user-defined id attribute nameFri, 05 Jun 2009 12:03:46 GMTdstora<p>
Currently, when defining a ForeignKey/OneToOneField field XXX, Django automatically defines a XXX_id attribute to store the id value.<br />
However, it is sometimes desirable to decide of the name as XXX_id may not be the most appropriate.
</p>
<hr />
<p>
Let's take the following example:
</p>
<ul><li>I initially have a table "Payment" with a "ccy_code" field designating a 3-letter currency code.
</li></ul><p>
My model definition looks like:
</p>
<pre class="wiki"> from django.db import model
class Payment(models.Model):
# ...
ccy_code = models.CharField(max_length=3)
</pre><p>
In my python code I refer to the currency code as follows:
</p>
<pre class="wiki"> p = Payment()
#...
print p.ccy_code
</pre><ul><li>Later, I decide to actually create a "Currency" table to hold some information about currencies.
</li></ul><p>
And I also decide to define a foreign key constraint from "Payment" to "Currency".
My model now looks like:
</p>
<pre class="wiki"> from django.db import model
class Currency(models.Model):
ccy_code = models.CharField(max_length=3, primary_key=True)
#...
class Payment(models.Model):
# ...
ccy = models.ForeignKey(Currency, to_field="ccy_code", db_column="ccy_code")
</pre><p>
The problem here is that my existing Python code is broken, because "ccy_code" is not defined anymore for "Payment".
Django has instead define a "ccy_id" attribute.
</p>
<hr />
<p>
Based on the principle that defining things like foreign keys should only add functionality (and not remove any) it seems quite important to me that one can choose the id attribute name.<br />
<br />
This can be achieved by adding an optional keyword argument to ForeignKey/OneToOneField constructors (here I decided to call it "id_attr_name").<br />
The implementation of this feature is pretty small and fully backward-compatible.<br />
Here is the SVN diff against trunk:
</p>
<pre class="wiki">Index: related.py
===================================================================
--- related.py (revision 10924)
+++ related.py (working copy)
@@ -660,6 +660,7 @@
class ForeignKey(RelatedField, Field):
empty_strings_allowed = False
def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs):
+ self.__id_attr_name = kwargs.pop('id_attr_name', None)
try:
to_name = to._meta.object_name.lower()
except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT
@@ -679,7 +680,10 @@
self.db_index = True
def get_attname(self):
- return '%s_id' % self.name
+ if self.__id_attr_name:
+ return self.__id_attr_name
+ else:
+ return '%s_id' % self.name
def get_validator_unique_lookup_type(self):
return '%s__%s__exact' % (self.name, self.rel.get_related_field().name)
</pre><p>
In my example, I could then define my model like:
</p>
<pre class="wiki"> from django.db import model
class Currency(models.Model):
ccy_code = models.CharField(max_length=3, primary_key=True)
#...
class Payment(models.Model):
# ...
ccy = models.ForeignKey(Currency, to_field="ccy_code", db_column="ccy_code", id_attr_name="ccy_code")
</pre>Resultshttps://code.djangoproject.com/ticket/11265#changeloghttps://code.djangoproject.com/ticket/8467
https://code.djangoproject.com/ticket/8467#8467: For ManyToMany manager, we should convert objects being added or removed to the pk type if they are not.Thu, 21 Aug 2008 06:39:08 GMTWonlay<p>
For example:
</p>
<pre class="wiki">class A(models.Model):
name = models.CharField(blank=True)
class B(models.Model):
a = models.ManyToManyField(A)
a = A(name='aaa')
a.save()
b = B()
b.save()
# This line works fine:
b.a.add('1')
# But this one will raise 'Duplicate entry' error:
b.a.add('1')
</pre><p>
This is caused by <tt> '1' </tt> is not an integer, the duplication checking code in <tt> add() </tt> fails when checking the string type <tt>'1'</tt>.
</p>
<p>
The same problem is applied to the <tt> remove() </tt> method.
</p>
<p>
If we convert the objects to its pk type of the model, code will run correctly.
</p>
<p>
And my patch is attached.
</p>
Resultshttps://code.djangoproject.com/ticket/8467#changeloghttps://code.djangoproject.com/ticket/17577
https://code.djangoproject.com/ticket/17577#17577: Form instantiation hook for adminMon, 23 Jan 2012 02:34:13 GMTsimon29<p>
Currently there is no hook to alter how forms are instantiated in admin, without hacking add_view/change_view.
</p>
<p>
This simple change could allow some nice stuff like access to the request object for form validation, customising fields, etc.
</p>
<p>
<a class="ext-link" href="http://stackoverflow.com/a/2684552/489638"><span class="icon">​</span>http://stackoverflow.com/a/2684552/489638</a>
</p>
<p>
<a class="ext-link" href="http://stackoverflow.com/a/1388881/489638"><span class="icon">​</span>http://stackoverflow.com/a/1388881/489638</a>
</p>
<p>
Proposed syntax --
</p>
<pre class="wiki">class MyAdmin(admin.ModelAdmin):
...
def get_form_instance(self, request, obj=None):
... (default method calls get_form() here)
</pre><p>
</p>
Resultshttps://code.djangoproject.com/ticket/17577#changeloghttps://code.djangoproject.com/ticket/9061
https://code.djangoproject.com/ticket/9061#9061: formsets with can_delete=True shouldn't add delete field to extra formsFri, 12 Sep 2008 18:47:59 GMTgsf<p>
Current behavior of formsets with can_delete=True is to add a delete field to every form. This behavior differs from that expected, however (why would one want a delete option on an "add" form?), as well as that of the builtin admin. I've included a patch on formsets.py, but haven't bothered with patching tests yet.
</p>
Resultshttps://code.djangoproject.com/ticket/9061#changeloghttps://code.djangoproject.com/ticket/12139
https://code.djangoproject.com/ticket/12139#12139: forms.fields.DateTimeField and TimeField so not accept stringified datetimesTue, 03 Nov 2009 12:33:20 GMTmattbennett<p>
When you stringify a datetime.datetime or datetime.time object, it includes fractional seconds e.g. '2009-11-03 12:21:10.800641'. The default input formats for DateTimeField and TimeField do not expect the fractional seconds part.
</p>
<p>
This is irritating when using a ModelForm and populating directly without preprocessing the datetimes, for example in a REST API where the form data is generated automatically.
</p>
Resultshttps://code.djangoproject.com/ticket/12139#changeloghttps://code.djangoproject.com/ticket/3254
https://code.djangoproject.com/ticket/3254#3254: full text search support for postgres, oracle and mssqlMon, 08 Jan 2007 19:12:47 GMTRonny Pfannschmidt<p>
I didn't like it was missing.
</p>
<p>
oracle, mssql : add a FulltextIndex for the Fields
</p>
<p>
postgresql: for each FulltextField add a extra tsvector Field named like <tt>"%(fieldname)_tsv"</tt>
</p>
<p>
Problems with sqlite fts:
</p>
<ul><li>they stated a match statement may only be used once in a query
</li><li>it needs a very specific syntax to search multiple fields
</li><li>i have no idea how to get that into the ORM
</li></ul>Resultshttps://code.djangoproject.com/ticket/3254#changeloghttps://code.djangoproject.com/ticket/15610
https://code.djangoproject.com/ticket/15610#15610: Generic Foreign Keys break when used with multi-db.Tue, 15 Mar 2011 02:56:21 GMTlegutierr<p>
Specifically, retrieving and saving objects that use the GenericForeignKey descriptor fails when the ContentType table is stored in a different database than the table of the instance being retrieved or saved.
</p>
<p>
There can only be one valid and consistent content-type table in a system. In a two-db system, the content type table will be in either db A or db B. Therefore, a portion of the system's tables will be registered in a content-type table that is stored in a different database.
</p>
<p>
This is all OK when retrieving objects based on a GenericForeignKey reference, because a user in such a situation will typically rely on the underlying routers to determine which database to use in retrieving content-type records.
</p>
<p>
However, this method in <a class="ext-link" href="http://code.djangoproject.com/browser/django/trunk/django/contrib/contenttypes/generic.py#L52"><span class="icon">​</span>django/trunk/django/contrib/contenttypes/generic.py</a> does not use routers in determining what database to use to fetch the content-type, but instead uses the source database of the orm object the content-type of which is being queried:
</p>
<pre class="wiki">52 def get_content_type(self, obj=None, id=None, using=None):
53 # Convenience function using get_model avoids a circular import when
54 # using this model
55 ContentType = get_model("contenttypes", "contenttype")
56 if obj:
57 return ContentType.objects.db_manager(obj._state.db).get_for_model(obj)
58 elif id:
59 return ContentType.objects.db_manager(using).get_for_id(id)
60 else:
61 # This should never happen. I love comments like this, don't you?
62 raise Exception("Impossible arguments to GFK.get_content_type!")
</pre><p>
The above method is what is used at object-creation time to transform a generic object in the <tt>__init__</tt> kwargs of a new orm object into a content-type/object-id pair for purposes of saving. The use of this method results in either: (a) an error being generated when the specified table is not to be found in the designated database; or (b) incorrect information being saved when a parallel--but incorrect (according to the router rules)--content type table from the other database is used (i.e. database corruption).
</p>
<p>
A simple fix would be to not assume that the content-types table is in the same database as the object with the GenericForeignKey field. I don't have a patch right now, but it may be as simple as replacing line 57:
</p>
<pre class="wiki">57 return ContentType.objects.db_manager(obj._state.db).get_for_model(obj)
</pre><p>
with:
</p>
<pre class="wiki">57 return ContentType.objects.db_manager(using).get_for_model(obj)
</pre><p>
A similar error seems to exist in the following block of code as well, however:
</p>
<pre class="wiki">220 manager = RelatedManager(
221 model = rel_model,
222 instance = instance,
223 symmetrical = (self.field.rel.symmetrical and instance.__class__ == rel_model),
224 join_table = qn(self.field.m2m_db_table()),
225 source_col_name = qn(self.field.m2m_column_name()),
226 target_col_name = qn(self.field.m2m_reverse_name()),
227 content_type = ContentType.objects.db_manager(instance._state.db).get_for_model(instance),
228 content_type_field_name = self.field.content_type_field_name,
229 object_id_field_name = self.field.object_id_field_name
230 )
</pre><p>
Requiring that line 227 be replaced, perhaps:
</p>
<pre class="wiki">227 content_type = ContentType.objects.get_for_model(instance),
</pre><p>
The problem here is that no <tt>using</tt> argument is specified for the <tt>__get__</tt> method, nor can a <tt>using</tt> argument be specified there, making the usage in that function inconsistent with the rest of the file, should this fix be put in place.
</p>
Resultshttps://code.djangoproject.com/ticket/15610#changeloghttps://code.djangoproject.com/ticket/17133
https://code.djangoproject.com/ticket/17133#17133: get_script_name goofs when there is Apache URL rewritingFri, 28 Oct 2011 22:34:41 GMTgjanee@…<p>
When running under Apache+mod_wsgi (I'm not sure the mod_wsgi is relevant here), using a WSGIScriptAlias of <tt>/foo</tt>, a request for URL <tt>/foo/bar//baz</tt> (note double slash) gets transformed by Apache to <tt>/foo/bar/baz</tt> and then by Django to <tt>/foo//bar/baz</tt> (note where double slashes are now). Furthermore, a callback function for urlpattern <tt>"^bar/.*"</tt> will be called on this latter path even though it doesn't match the pattern. That is, request.path will be <tt>/foo//bar/baz</tt>, which can be confusing for a callback function that is expecting request.path to match the WSGIScriptAlias plus the urlpattern.
</p>
<p>
I don't totally understand what Django is doing here, but I believe the problem is in django.core.handlers.base.get_script_name. In that function, to get the script name in this situation Django starts with the environment variable SCRIPT_URL, and strips off a number of characters at the end equal to the length of environment variable PATH_INFO. Because in this case Apache collapses the double slash in <tt>/foo/bar//baz</tt> to <tt>/foo/bar/baz</tt>, get_script_name strips off one less character than necessary, so that instead of the script name being <tt>/foo</tt> it is <tt>/foo/</tt>. This may account for the double slash appearing <tt>/foo</tt>, as in <tt>/foo//bar/baz</tt>.
</p>
Resultshttps://code.djangoproject.com/ticket/17133#changeloghttps://code.djangoproject.com/ticket/12199
https://code.djangoproject.com/ticket/12199#12199: Give 'firstof' tag ability to assign result to contextWed, 11 Nov 2009 19:06:26 GMTtiliv<p>
When you need to access fields on objects in a <tt> {% firstof %} </tt> fashion, semantically 'optional' fields can cause issues:
</p>
<pre class="wiki"> Today the teacher is {% firstof substitute.name teacher.name %},
and drives a {% firstof substitute.car teacher.car %}
</pre><p>
If <tt> substitute </tt> doesn't have a value for <tt> car </tt>, then it will fall back to <tt> teacher.car </tt>.
</p>
<p>
The real issue is that <tt> {% firstof %} </tt> cannot preserve its value for later multiple inspections. If the <tt> {% firstof %} </tt> tag could assign its result to a context variable, it would solve this problem:
</p>
<pre class="wiki"> {% firstof substitute teacher as teacher_for_today %}
Today the teacher is {{ teacher_for_today }}
{% if teacher_for_today.car %}
and drives a {{ teacher_for_today.car }}
{% endif %}
</pre><p>
I am unsure that this is possible to achieve without the <tt> as </tt> syntax. One would have to code a template tag or filter for the sole purpose of duplicating the exact functionality that I propose be added to <tt> {% firstof %} </tt>.
</p>
<p>
Attached patch for functionality and documentation on the subject.
</p>
Resultshttps://code.djangoproject.com/ticket/12199#changeloghttps://code.djangoproject.com/ticket/10449
https://code.djangoproject.com/ticket/10449#10449: HTML accents not escaped out when using formsMon, 09 Mar 2009 15:44:36 GMTtipan<p>
When passing a translated string to a select box using a Forms Select widget, the output string still contains accent HTML entity codes.
</p>
<p>
For example: "Problemas para el Inicio de Sesi&amp;oacute;n o relacionados con la Cuenta
</p>
<p>
My code is set up as follows:
</p>
<p>
Models.py
</p>
<pre class="wiki">from django.utils import translation
from django.utils.translation import ugettext_lazy as _
SUBJECT = (
(10, _('Log-in or Account related problems')),
(20, _('General enquiry')),
(30, _('Other feedback')),
)
</pre><p>
This is then used in a form:
</p>
<pre class="wiki">class HelpFeedbackForm(forms.Form):
#form for user to submit their feedback when not logged in
subject = forms.CharField(widget=forms.Select(choices=SUBJECT))
</pre><p>
This is then presented in the template as:
{{ form.subject }}
</p>
<p>
which produces: "Problemas para el Inicio de Sesi&amp;oacute;n o relacionados con la Cuenta" as mentioned above.
</p>
<p>
The translations are returned from the django.po file, but all of the HTML entity codes are returned as is, in the Select box in the template.
Also, use of the safe template filter tag does affect this and the string is still rendered with accents.
</p>
Resultshttps://code.djangoproject.com/ticket/10449#changeloghttps://code.djangoproject.com/ticket/11715
https://code.djangoproject.com/ticket/11715#11715: If change mutable list "inlines" in one admin options then it will change "inlines" for all admin options.Thu, 13 Aug 2009 22:35:05 GMTaiv<p>
Now attribute "inlines" is mutable and declared in the body of ModelAdmin class:
</p>
<pre class="wiki">class ModelAdmin(BaseModelAdmin):
...
inlines = []
...
</pre><p>
When we change this attribute in one sub-class, python will change it in all other sub-classes:
</p>
<pre class="wiki">from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length=100)
</pre><pre class="wiki">from django.contrib import admin
from models import *
class BookInline(admin.TabularInline):
model = Book
class AuthorAdmin(admin.ModelAdmin):
def __init__(self, *args, **kwds):
self.inlines.append(BookInline)
return super(AuthorAdmin, self).__init__(*args, **kwds)
class BookAdmin(admin.ModelAdmin):
pass
admin.site.register(Author, AuthorAdmin)
admin.site.register(Book, BookAdmin)
</pre><p>
This code will add BookInline to BookAdmin, too!
</p>
<p>
So, when we will go to admin and try to change Book, we will see exception:
</p>
<pre class="wiki">&lt;class 'test.models.Book'&gt; has no ForeignKey to &lt;class 'test.models.Book'&gt;
</pre><p>
We can fix it like this:
</p>
<pre class="wiki">--- django/contrib/admin/options.py
+++ django/contrib/admin/options.py
@@ -187,7 +187,7 @@ class ModelAdmin(BaseModelAdmin):
save_as = False
save_on_top = False
ordering = None
- inlines = []
+ inlines = None
# Custom templates (designed to be over-ridden in subclasses)
change_form_template = None
@@ -206,6 +206,8 @@ class ModelAdmin(BaseModelAdmin):
self.opts = model._meta
self.admin_site = admin_site
self.inline_instances = []
+ if self.inlines is None:
+ self.inlines = []
for inline_class in self.inlines:
inline_instance = inline_class(self.model, self.admin_site)
self.inline_instances.append(inline_instance)
--- django/contrib/admin/validation.py
+++ django/contrib/admin/validation.py
@@ -133,7 +133,7 @@ def validate(cls, model):
# inlines = []
- if hasattr(cls, 'inlines'):
+ if hasattr(cls, 'inlines') and cls.inlines is not None:
check_isseq(cls, 'inlines', cls.inlines)
for idx, inline in enumerate(cls.inlines):
if not issubclass(inline, BaseModelAdmin):
</pre><p>
But then our sample will raise:
</p>
<pre class="wiki">'NoneType' object has no attribute 'append'
</pre><p>
I think, we can do it like this:
</p>
<pre class="wiki">--- django/contrib/admin/options.py
+++ django/contrib/admin/options.py
@@ -187,7 +187,7 @@ class ModelAdmin(BaseModelAdmin):
save_as = False
save_on_top = False
ordering = None
- inlines = []
+ inlines = ()
# Custom templates (designed to be over-ridden in subclasses)
change_form_template = None
</pre><p>
It will fix logic with mutable attribute, but users will have to write:
</p>
<pre class="wiki"> from django.contrib import admin
from models import *
class BookInline(admin.TabularInline):
model = Book
class AuthorAdmin(admin.ModelAdmin):
+ inlines = []
def __init__(self, *args, **kwds):
self.inlines.append(BookInline)
return super(AuthorAdmin, self).__init__(*args, **kwds)
class BookAdmin(admin.ModelAdmin):
pass
admin.site.register(Author, AuthorAdmin)
admin.site.register(Book, BookAdmin)
</pre><p>
I believe, this will be more correct variant.
</p>
Resultshttps://code.djangoproject.com/ticket/11715#changeloghttps://code.djangoproject.com/ticket/16362
https://code.djangoproject.com/ticket/16362#16362: Ignore, rather than disallow, negative lookahead assertionsTue, 28 Jun 2011 03:38:02 GMTcharles@…<p>
At present, <tt>django.utils.regexhelper.normalize()</tt> is defined and documented to raise an exception on encountering lookahead and lookbehind matches in the name of reversability. This behaviour unnecessarily restricts the range of valid configurations.
</p>
<p>
Consider the following case:
</p>
<div class="code"><pre>url<span class="p">(</span><span class="s">r'^(?P&lt;city&gt;[-\w._])/'</span><span class="p">,</span> name<span class="o">=</span><span class="s">'city-landing'</span><span class="p">),</span>
</pre></div><p>
One may wish to assert that certain inputs are *certainly not* cities, and should never match this (in my particular use case, the desired outcome is actually a <tt>Resolver404</tt>, such that adding an additional, earlier <tt>url()</tt> entry to the urlconf is not an option):
</p>
<div class="code"><pre>url<span class="p">(</span><span class="s">r'^(?!NotACity)(?P&lt;city&gt;[-\w._])/'</span><span class="p">,</span> name<span class="o">=</span><span class="s">'city-landing'</span><span class="p">),</span>
</pre></div><p>
This *does* mean that <tt>reverse('city-landing', kwargs={'name': 'NotACity'})</tt> will result in an invalid result (a URL which, when resolved, does not in fact match the given reversed string). However, such a case clearly constitutes user error -- as the application developer trying to request a <tt>city-landing</tt> URL for <tt>NotACity</tt> is asking the impossible -- and does not constitute cause for making such patterns unsupported.
</p>
Resultshttps://code.djangoproject.com/ticket/16362#changeloghttps://code.djangoproject.com/ticket/17881
https://code.djangoproject.com/ticket/17881#17881: Implement BaseModelAdmin.get_raw_id_fields, similar to get_readonly_fieldsMon, 12 Mar 2012 18:16:54 GMTaaugustin<p>
In order to prevent massive drop downs for related fields when the related model has lots of items, I'd like to add such fields automatically to <tt>raw_id_fields</tt>.
</p>
<p>
I've managed to make them read only by implementing the following <tt>get_readonly_fields</tt> method in the base class that all my <tt>ModelAdmin</tt> classes inherit:
</p>
<pre class="wiki">MODELS_WITH_TOO_MANY_INSTANCES_FOR_ADMIN_SELECT = [
'auth.User',
# ...
}
class ModelAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
explicit_readonly_fields = super(ModelAdmin, self).get_readonly_fields(request, obj)
automatic_readonly_fields = self.related_fields_with_too_many_instances()
return tuple(set(explicit_readonly_fields) | set(automatic_readonly_fields))
def related_fields_with_too_many_instances(self):
fields = []
for f in self.model._meta.fields:
# If the field isn't shown anyway, don't bother.
if self.fields and not f.name in self.fields:
continue
# If we made the field editable by id, that means we want to edit it, even if it's impractical
if f.name in self.raw_id_fields:
continue
# If the field is a ForeignKey to a blacklisted model, make it read only.
if isinstance(f, (django_models.ForeignKey, django_models.ManyToManyField)):
related_model = '%s.%s' % (f.rel.to._meta.app_label, f.rel.to._meta.object_name)
if related_model in MODELS_WITH_TOO_MANY_INSTANCES_FOR_ADMIN_SELECT:
fields.append(f.name)
return fields
</pre><p>
However, power users occasionally complain that they can no longer edit these fields... which is why I'd like a <tt>get_raw_id_fields</tt> method that I could override.
</p>
Resultshttps://code.djangoproject.com/ticket/17881#changeloghttps://code.djangoproject.com/ticket/11495
https://code.djangoproject.com/ticket/11495#11495: Improvements to django.views.static.serve directory indexesFri, 17 Jul 2009 02:18:06 GMTSmileyChris<p>
This patch sorts indexes and shows directories before files.
It also adds functionality for providing an index prefix so the template can show the full indexed path correctly.
</p>
Resultshttps://code.djangoproject.com/ticket/11495#changeloghttps://code.djangoproject.com/ticket/16027
https://code.djangoproject.com/ticket/16027#16027: Include app_label in ContentType.__unicode__Sat, 14 May 2011 22:43:48 GMTjakub<p>
When there are multiple models with same name in your project and you use the amazing content types framework, then selects for foreign keys to ContentType contain indistinguishable items. To fix this, the app_label needs to be included in ContentType's <span class="underline">unicode</span>.
</p>
Resultshttps://code.djangoproject.com/ticket/16027#changeloghttps://code.djangoproject.com/ticket/19536
https://code.djangoproject.com/ticket/19536#19536: in ModelAdmin disabling has_add_permission results in not showing any object-toolsSat, 29 Dec 2012 07:31:29 GMTa.fazeli@…<p>
in change_list.html when has_add_permission is false all the object-tools (buttons) are not shown, even if you have implemented some custom tools. This permission check should only be for the add button item.
</p>
<p>
I tweaked the code (very small change) that will fix this problem.
</p>
<p>
My proposal for this matter is attached to this ticket
</p>
Resultshttps://code.djangoproject.com/ticket/19536#changeloghttps://code.djangoproject.com/ticket/14096
https://code.djangoproject.com/ticket/14096#14096: Insert code generated by models using multiple inheritance is incorrect and fails in postgresqlWed, 11 Aug 2010 22:17:59 GMTpembo13<p>
When a model with multiple concrete parents is saved (inserted) the parents are saved first. Currently, the first parent is saved and its primary key is also set as the primary key of the yet unsaved top model. Any parent following uses the new primary key of 'self' and explicitly inserts the PK into the parent models table
</p>
<p>
There is no reason to explicitly set the PK of any of the parent classes, the code already handles retrieval of the DB assigned PK.
</p>
<p>
While other DBs let this pass, PostgreSQL does not. The problem comes not on the offending .save() but subsequent inserts to the table, this time <strong>without</strong> an explicit PK. The DB's internal counter has not advanced, so the next chosen PK already exists and yields a database error due to duplicate of a key field.
</p>
<p>
There is no apparent need to explicitly set any of the PK on insert. I believe that changing the following code block within source:django/trunk/django/db/models/base.py#13538 , line 533 , Model.save_base(...) can solve the problem:
</p>
<p>
from
</p>
<div class="code"><pre> <span class="k">if</span> update_pk<span class="p">:</span>
<span class="nb">setattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> meta<span class="o">.</span>pk<span class="o">.</span>attname<span class="p">,</span> result<span class="p">)</span>
</pre></div><p>
to
</p>
<div class="code"><pre> <span class="k">if</span> update_pk <span class="ow">and</span> cls <span class="o">==</span> <span class="bp">self</span><span class="o">.</span>__class__<span class="p">:</span>
<span class="nb">setattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> meta<span class="o">.</span>pk<span class="o">.</span>attname<span class="p">,</span> result<span class="p">)</span>
</pre></div><p>
I have attached a sample site ('minherit') with app ('data') and a test case in a ZIP file.
</p>
Resultshttps://code.djangoproject.com/ticket/14096#changeloghttps://code.djangoproject.com/ticket/7556
https://code.djangoproject.com/ticket/7556#7556: inspectdb fails in MySql if a table references a table outside the current schemaFri, 27 Jun 2008 15:32:35 GMTbrockweaver<p>
If a table contains a foreign key that refers to another table that sits outside the schema, that index includes a '.' in the table name. Suppose our current schema is <tt>schema1</tt>:
</p>
<pre class="wiki">CREATE TABLE `T1` (
`ACID` int(8) unsigned NOT NULL,
`SITE` varchar(8) character set latin1 default NULL,
CONSTRAINT `FK_T1_SITE` FOREIGN KEY (`SITE`) REFERENCES `schema2`.`site` (`SITE`)
)
</pre><p>
For this situation, inspectdb will return something similar to this:
</p>
<pre class="wiki">_mysql_exceptions.ProgrammingError: (1146, "Table 'schema1.site' doesn't exist")
</pre><p>
So it tries to use <tt>schema1.site</tt> as the table to introspect instead of the appropriate <tt>schema2</tt>.<tt>site</tt> Notice it not only needs to use the schema as part of the table name, but also not quote the '.'. Also, introspection.py was not pulling the schema name and just assuming the current schema, which for most cases is right, but in this case causes issues for legacy databases.
</p>
Resultshttps://code.djangoproject.com/ticket/7556#changeloghttps://code.djangoproject.com/ticket/17186
https://code.djangoproject.com/ticket/17186#17186: Inverted F expression (negation)Wed, 09 Nov 2011 17:51:41 GMTniwi<p>
By default, the expression F django, can not make something like:
</p>
<div class="code"><pre><span class="k">UPDATE</span> <span class="ss">"testmodel"</span> <span class="k">SET</span> <span class="ss">"done"</span> <span class="o">=</span> <span class="k">NOT</span> <span class="ss">"testmodel"</span><span class="p">.</span><span class="ss">"done"</span><span class="p">;</span>
</pre></div><p>
The idea is to make updates or queries like this:
</p>
<div class="code"><pre>TestModel<span class="o">.</span>objects<span class="o">.</span>update<span class="p">(</span>done<span class="o">=~</span>F<span class="p">(</span><span class="s">'done'</span><span class="p">))</span>
</pre></div><p>
Taking as a reference, this model:
</p>
<div class="code"><pre><span class="k">class</span> <span class="nc">TestModel</span><span class="p">(</span>models<span class="o">.</span>Model<span class="p">):</span>
done <span class="o">=</span> models<span class="o">.</span>BooleanField<span class="p">(</span>default<span class="o">=</span><span class="bp">False</span><span class="p">)</span>
</pre></div><p>
Attached is a patch that works for me, but not if it's the best way to do it.
</p>
Resultshttps://code.djangoproject.com/ticket/17186#changeloghttps://code.djangoproject.com/ticket/20932
https://code.djangoproject.com/ticket/20932#20932: Issues with model Manager and inheritance.Sun, 18 Aug 2013 11:14:17 GMTloic84<p>
I've found a couple of issues with the current handling of managers with inheritance.
</p>
<ol><li>Weird bug that I can't explain yet: <a class="ext-link" href="https://github.com/loic/django/compare/manager_inheritance_bug"><span class="icon">​</span>https://github.com/loic/django/compare/manager_inheritance_bug</a>
</li></ol><blockquote>
<p>
<tt>model_inheritance_regress.tests.ModelInheritanceTest.test_abstract_base_class_m2m_relation_inheritance</tt> fails with <tt>AttributeError: 'BachelorParty' object has no attribute 'bachelorparty_ptr'</tt>.
</p>
</blockquote>
<ol start="2"><li>Managers in MTI *are* inherited, contrary to what is said <a class="ext-link" href="https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers-and-model-inheritance"><span class="icon">​</span>in the docs</a>.
</li></ol><blockquote>
<p>
Quoting the docs: "Managers defined on non-abstract base classes are not inherited by child classes. [...] Therefore, they aren’t passed onto child classes.". The problem is that, since we create the new class by calling <tt>object.__new__()</tt>, normal Python attribute resolution applies, and we gain access to the attributes of the base classes. This doesn't happen to fields because these are removed during the class creation process, but managers are left behind. It's always tempting to think we could just delete them, but you cannot delete something that is not in your own <tt>__dict__</tt>. The problem is not so much that we inherit those managers, but that they don't return the right model type as demonstrated in <a class="ext-link" href="https://github.com/loic/django/compare/manager_inheritance_bug2"><span class="icon">​</span>https://github.com/loic/django/compare/manager_inheritance_bug2</a>.
</p>
</blockquote>
<p>
Note: I know we usually should have one ticket for each bug. This time though, we only have a couple of lines of codes that have multiple consequences, so I'd like to keep the discussion centralized. We can always open a ticket for each bug when the time comes to actually implement what we decide.
</p>
Resultshttps://code.djangoproject.com/ticket/20932#changeloghttps://code.djangoproject.com/ticket/15982
https://code.djangoproject.com/ticket/15982#15982: Lack DateTime formats in some languagesMon, 09 May 2011 11:22:03 GMTpmartin<p>
Lack DateTime formats in some languages.
</p>
<p>
For example in english:
</p>
<pre class="wiki">
DATETIME_INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
'%Y-%m-%d', # '2006-10-25'
'%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M', # '10/25/2006 14:30'
'%m/%d/%Y', # '10/25/2006'
'%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
'%m/%d/%y %H:%M', # '10/25/06 14:30'
'%m/%d/%y', # '10/25/06'
)
</pre><p>
But in spanish, I think that it lacks this format <tt> '%d/%m/%y' </tt>:
</p>
<pre class="wiki">
DATETIME_INPUT_FORMATS = (
'%d/%m/%Y %H:%M:%S',
'%d/%m/%Y %H:%M',
'%d/%m/%y %H:%M:%S',
'%d/%m/%y %H:%M',
)
</pre>Resultshttps://code.djangoproject.com/ticket/15982#changeloghttps://code.djangoproject.com/ticket/18296
https://code.djangoproject.com/ticket/18296#18296: Make creating apps inside project folder more intuitive with manage.py startapp commandThu, 10 May 2012 07:14:49 GMTlgp171188@…<p>
The structure of the project created by 'django-admin.py startproject' has changed from Django 1.4. The 'manage.py' file is at the same level where the project folder containing settings.py, urls.py is present. In order to create an app within the project as was possible with Django &lt; 1.4, the command to be used is 'python manage.py startapp &lt;app name&gt; &lt;destination folder which is optional&gt;. So if I execute the command "python manage.py startapp myapp myproject", there is an error that says "Error: &lt;full path&gt;/&lt;project name&gt;/&lt;project name&gt;/<span class="underline">init</span>.py already exists, overlaying a project or app into an existing directory won't replace conflicting files". The command actually expects an empty directory having the name of the app inside the project directory to work correctly. So the user has to create that directory and then create the app. This isn't very intuitive and django should create the app directory if it doesn't exist and then create the app to show the same behaviour as the previous versions.
</p>
<p>
One other way to work around this behaviour is to change to the project directory and then execute python ../manage.py startapp appname.
</p>
Resultshttps://code.djangoproject.com/ticket/18296#changeloghttps://code.djangoproject.com/ticket/19567
https://code.djangoproject.com/ticket/19567#19567: Make javascript i18n view as CBV and more extensible.Sat, 05 Jan 2013 10:01:04 GMTniwi<p>
The current view populates a global namespace (see <a href="https://code.djangoproject.com/ticket/18231">https://code.djangoproject.com/ticket/18231</a>) but also is very monolitic.
</p>
<p>
My proposal is create a CBV. I don't understand the use of templates for rendering a view (related ticket).
Now, the initial code is available on this file: <a class="ext-link" href="https://github.com/niwibe/django-jsgettext/blob/master/djsgettext/views.py"><span class="icon">​</span>https://github.com/niwibe/django-jsgettext/blob/master/djsgettext/views.py</a>
</p>
<p>
If the proposal is accepted, I will create a patch.
</p>
Resultshttps://code.djangoproject.com/ticket/19567#changelog