Django: Ticket Query!closed&needs_tests=1&stage=Accepted&order=priority The Web framework for perfectionists with deadlines. en-US Django!closed&needs_tests=1&stage=Accepted&order=priority Trac 1.0 #494: Collapse in admin interface for inline related objects Mon, 12 Sep 2005 19:00:50 GMT jcstover@… <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="">ForeignKey</a>(Organisatie, edit_inline=meta.STACKED, edit_inline_style='collapse') </p> <p> I changed line 610 in the django/views/admin/ 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> Results #2137: [patch] order_with_respect_to in M-R has no affect on admin interface Sun, 11 Jun 2006 23:51:21 GMT anonymous <p> Pre-MR, adding order_with_respect_to would present an ordering field in the admin interface (or a draggable list of inline objects if dom-drag.js was installed). Post M-R, neither appears. Not sure if this is a problem at the template level or at the model level. </p> Results #2443: Add IntervalField to database models Fri, 28 Jul 2006 19:14:54 GMT ben.tucker@… <p> Although not all backends support the interval data type, it can be implemented using some other data type. This field is quite useful and it would be nice if it were available. </p> Results #2539: Custom tags and filters can be restricted by namespace Sun, 13 Aug 2006 04:09:44 GMT limodou@… <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=""><span class="icon">​</span>HERE</a> </p> Results #2843: [patch] serializer can't resolve a one-to-many relation from the "foreign" side Thu, 28 Sep 2006 18:52:57 GMT nikl@… <p> best illustrated with a short example: </p> <div class="code"><pre><span class="k">class</span> <span class="nc">Reporter</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>maxlength<span class="o">=</span><span class="mi">25</span><span class="p">)</span> <span class="k">class</span> <span class="nc">Article</span><span class="p">(</span>models<span class="o">.</span>Model<span class="p">):</span> reporter <span class="o">=</span> models<span class="o">.</span>ForeignKey<span class="p">(</span>Reporter<span class="p">)</span> </pre></div><p> what I want to be able to get is something like the following (python-serialization): </p> <div class="code"><pre><span class="p">[{</span><span class="s">'fields'</span><span class="p">:</span> <span class="p">{</span><span class="s">'articles'</span><span class="p">:</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="s">'name'</span><span class="p">:</span> <span class="s">'Me'</span><span class="p">},</span> <span class="s">'model'</span><span class="p">:</span> <span class="s">'news.reporter'</span><span class="p">,</span> <span class="s">'pk'</span><span class="p">:</span> <span class="s">'1'</span><span class="p">}]</span> </pre></div><p> currently, if I want to get the information in this format, I have two options: </p> <ul><li>construct a Model-like structure, so it can be used with the serializers </li><li>turn the one-to-many into a many-to-many relationship </li></ul><p> both of these are obviously not a clean solution... </p> <p> therefore I'd propose to add an extra parameter to export the ids of those related-objects optionally. </p> <p> if time allows and there are no objections to this, I'll try to throw together a patch this weekend. </p> Results #3254: [patch] experimental fulltext search support for postgres, oracle and mssql Mon, 08 Jan 2007 19:12:47 GMT Ronny 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> Results #3461: DatabaseWrapper should pass through args and kwargs to underlying database adapter Thu, 08 Feb 2007 20:38:52 GMT Jack 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> Results #4136: NULL fields and Unique keys Tue, 24 Apr 2007 00:16:51 GMT David 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> Results #4363: Formpreview doesn't support newform's dynamic initial values Tue, 22 May 2007 20:17:15 GMT Indy <p> The formpreview has no hook for dynamic initial field values. The attached patch provides this hook. </p> Results #5253: serializer for csv format for loaddata and dumpdata Sat, 25 Aug 2007 12:15:21 GMT Adam Schmideg <adam@…> <p> Currently supported serialization formats are to verbose to be easily edited by hand. Csv format would support a more fluent development cycle of click together data, dump data, edit data, load data. </p> Results #5349: Shouldn't the item_enclosure_url automatically prefixed with the current site? Thu, 06 Sep 2007 11:53:12 GMT anonymous <p> I'd recommend to add a call to add_domain() to the enclosure URL because other URLs are also automatically extended with the site's URL. I've included the patch. </p> Results #5372: [newforms-admin] - caching of sql query for inlines Sun, 09 Sep 2007 21:36:10 GMT anonymous Results #5685: [patch] Add ability to perform pre-runtime setup before executing code Thu, 04 Oct 2007 19:07:37 GMT __hawkeye__ <p> Django should allow developers to elegantly inject functionality prior to general code execution. </p> <p> This is useful if something needs to happen <em>before</em> models are loaded (register as a <tt></tt><tt>class_prepared</tt><tt></tt> listener). Malcolm indicated that he is aware of other cases where this could be useful. </p> <p> This issue has been discussed briefly on django-users. <a class="ext-link" href=""><span class="icon">​</span></a> </p> Results #5815: Adds per-view cache refreshing (clearing) Thu, 25 Oct 2007 05:20:57 GMT k0001 <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> Results #5865: cycle template tag should accept a single argument Sat, 03 Nov 2007 01:52:35 GMT gwilson <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> Results #5899: Allow admin fieldsets to be collapsible but not initially collapsed Thu, 08 Nov 2007 14:08:08 GMT Ionut 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> Results #5904: reverse should be more lenient on non-existent views in the urlconf Thu, 08 Nov 2007 22:04:44 GMT SmileyChris <p> If you try to use the <tt>reverse</tt> (even for an existing view) while you have a non-existent view referenced in your urlconf, a <tt>ViewDoesNotExist</tt> error will be raised. </p> <p> This happens because a <tt>reverse_dict</tt> cache is built for the <tt>RegexURLResolver</tt> containing a list to all pattern callbacks and names. </p> <p> Rather than the whole thing falling over, all that should really happen in this case is that the callback is left out of <tt>reverse_dict</tt>. </p> Results #6066: Post-syncdb signal should include a list of done/to-be-done apps. Fri, 30 Nov 2007 21:55:58 GMT jacob <p> See <a class="closed ticket" href="" title="enhancement: [patch] Define order in which &#34;initial sql data&#34; files are processed (closed: wontfix)">#2453</a> -- sometimes you need to run code/SQL at a particular point during initialization. I'd think two params: <tt>done</tt> and {{todo}}}, each of which contains a list of apps that have/have not yet been processed. </p> <p> (Of course, other implementation ideas are welcome; that's just the first that comes to my mind.) </p> Results #6285: Cutting up a list of objects into a table with a given number of columns Sat, 29 Dec 2007 03:24:29 GMT purdeaandrei <h3 id="Cuttingupalistofobjectsintoatablewithagivennumberofcolumns">Cutting up a list of objects into a table with a given number of columns</h3> <h4 id="Approachesthatmightbebad:">Approaches that might be bad:</h4> <ul><li>it is not a good idea for the view to cut up the list, because the number of columns (N) is layout-related. </li></ul><ul><li>useing <em>divisibleby</em> is somewhat low-level, you are implementing a for loop, in a template language that is supposed to be high-level </li></ul><h4 id="Proposal:">Proposal:</h4> <ul><li>to have a <strong>filter</strong> that will behave like this: <pre class="wiki"> {% for row in objectlist|tablecols:3 %} &lt;tr&gt; {% for item in row %} &lt;td&gt; {{ item.content }} &lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} </pre></li></ul> Results #6327: Add has_module_permission to ModelAdmin Sun, 06 Jan 2008 12:11:04 GMT chrj <p> I think it's a bit odd that <tt>ModelAdmin</tt> has permission hooks for add, change and delete but not for the module. Is there a special reasoning behind this? I can't come up with a use case. </p> <p> This patch will fix that. </p> <p> Regards, Christian </p> Results #6343: % symbols not escaped in db_column column names when preparing queries Tue, 08 Jan 2008 12:47:24 GMT Daniel Pope <dan@…> <p> Using <tt>%</tt> in database column names (specified using <tt>db_column</tt>) causes the database wrapper to fail when preparing queries. </p> <p> This is because the <tt>%</tt> symbol is not properly quoted (as <tt>%%</tt>), and conflicts with the usage of <tt>%s</tt> for passing parameters to queries. </p> <p> I am attaching a patch for the MySQL backend where I encountered the issue; I'm not sure if other backends exhibit this bug because it presumably depends both on whether the database's native capability to support <tt>%</tt> characters in column names, and on the <a class="ext-link" href=""><span class="icon">​</span>Python DB-API</a> <tt>paramstyle</tt>. </p> Results #6344: Refactored inspectdb Tue, 08 Jan 2008 14:21:45 GMT Daniel Pope <dan@…> <p> I have inherited a database developed in Microsoft Access that contains 1985 columns in 85 tables. </p> <p> To import this into Django, I tried the existing inspectdb tool, but I found numerous bugs that would be too time-consuming to fix manually. </p> <p> I have refactored the inspectdb tool to do a better job of importing. Aside from better ensuring that output is syntactically valid, the tool now constructs object-oriented structure which is then post-processed and serialized, rather than serializing on-the-fly. This approach makes it easier to procedurally rename models, and to include heuristics to fix up semantic problems with the models. </p> <ul><li>model class names are sanitized and converted to <a class="wiki" href="">CamelCase</a> </li><li>model field names are sanitized and converted to lowercase_with_underscores </li><li>db_column is <strong>always</strong> specified: this allows refactoring of field names in the generated code </li><li>no comment is issued where field names differ from database column names. This should now be assumed for all fields but the use of db_column makes this explicit </li><li>AutoFields are always explicit: again, this is useful when refactoring </li><li>blank lines are added in the output, so that fields definitions are visually grouped into keys, relations and other fields </li><li>write a warning comment if no primary_key is detected, as such models cannot be used with Django </li></ul><p> I've added the following heuristics. These heuristics are not guaranteed to produce the right results, but they should produce the right results more often than if they were not included. For very large database schemas this is very important. </p> <ul><li>heuristically detect field names that are potentially keys but not defined as such, grouping these too (this is safe) </li><li>if no primary key is set, heuristically choose a candidate field if one matches the name of the model (this is unsafe but a warning comment is issued; besides, the alternative cannot work) </li><li>heuristically, upgrade IntegerFields with primary_key=True to AutoField if there is none (this is unsafe. A warning comment is issued.) </li></ul><p> This tool still does not guarantee to resolve conflicts between field or model names (a very insidious issue should it occur), although the refactor was designed partly this this goal in mind. </p> Results #6363: Bug with has_permission method of AdminSite class. Fri, 11 Jan 2008 19:15:42 GMT michelts <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> Results #6376: Please don't force the usage of the 'django' gettext domain Mon, 14 Jan 2008 13:59:11 GMT dennis@… <p> I'm using django as a library in my non-web-based application. As such I prefer not to use the 'django' gettext domain but my own. I currently work around it with some symlinking trickery since being compatible with upstream django is more important than not having workarounds, but it would be great if django supported this. To illustrate what I mean, I've attached a simple and untested patch against current svn (rev 7020). </p> Results #6517: dbshell does not get charset from database_options Thu, 31 Jan 2008 08:42:34 GMT tvrg <p> I noticed that dbshell doesn't respect the database_options.<br /> I ran into an issue with an application we are creating that needs to support mysql and postgre at least, we execute some sql scripts that get piped to dbshell (to avoid hardcoding psql -U xxx or mysql -u xxx and creating 2 scripts every time). </p> <p> When running an utf8 database with utf8 as our charset in database_options, we ran into some weird encoding issues. </p> <p> The solution for us was to learn mysql/ to respect the encoding settings in </p> <p> Are you opposed to something like this? </p> <p> Attaching small patch that fixes our problem. Let me know if it needs extending to support other backends or database_options. </p> Results #6933: You cannot search with spaces if search_fields is declared with "^" Mon, 31 Mar 2008 21:52:58 GMT Martín Conte Mac Donell <Reflejo@…> <p> That is. When search_fields is declared to "starts with" you cannot perform queries with spaces. </p> <p> File contrib/admin/views/; Line 326: </p> <pre class="wiki">for bit in self.query.split(): or_queries = [models.Q(**{construct_search(field_name): bit}) for field_name in self.search_fields] other_qs = QuerySet(self.model) (...) qs = qs &amp; other_qs </pre><p> So, if for example i'm looking for "Hey dud" query will be: </p> <pre class="wiki">qs.filter(field__startswith="Hey") &amp; qs.filter(field__startswith("dud")) </pre> Results #7028: Better raw_id_fields feedback in newform-admins branch Wed, 16 Apr 2008 00:07:22 GMT Marcob <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> Results #7361: newforms-admin delete page gives you no way out! Wed, 04 Jun 2008 14:17:41 GMT simon <p> It's just been pointed out to me that when you hit "Delete" in the Django admin you get a "Are you sure?" page with only one button: "Yes, I'm sure". There's no alternative "no, get me out of here" option. </p> <p> Apparently some people may find this upsetting :) </p> <p> This problem is particularly important for delete pages with lots of related items and hence a massive list of things that will be deleted. The huge list makes the page enormously more frightening, and by the time the user has scrolled down to the button at the bottom they can no longer see the top navigation with safe links to other parts of the interface. </p> Results #7377: "extends" and "block" tags are not available when constructing template from scratch Thu, 05 Jun 2008 21:51:14 GMT mgeorge@… <p> with a fresh svn chekcout, made a new project, and run: ./ shell </p> <pre class="wiki">In [1]: from django.template import Template, Context In [2]: t = Template('''{% block title %}Hello{% end block %}''') --------------------------------------------------------------------------- TemplateSyntaxError Traceback (most recent call last) /Users/mattgeorge/django-code/gapp/&lt;ipython console&gt; in &lt;module&gt;() /Library/Python/2.5/site-packages/django/template/ in __init__(self, template_string, origin, name) 164 if settings.TEMPLATE_DEBUG and origin is None: 165 origin = StringOrigin(template_string) --&gt; 166 self.nodelist = compile_string(template_string, origin) 167 = name 168 /Library/Python/2.5/site-packages/django/template/ in compile_string(template_string, origin) 185 lexer = lexer_class(template_string, origin) 186 parser = parser_class(lexer.tokenize()) --&gt; 187 return parser.parse() 188 189 class Token(object): /Library/Python/2.5/site-packages/django/template/ in parse(self, parse_until) 267 compile_func = self.tags[command] 268 except KeyError: --&gt; 269 self.invalid_block_tag(token, command) 270 try: 271 compiled_result = compile_func(self, token) /Library/Python/2.5/site-packages/django/template/ in invalid_block_tag(self, token, command) 319 320 def invalid_block_tag(self, token, command): --&gt; 321 raise self.error(token, "Invalid block tag: '%s'" % command) 322 323 def unclosed_block_tag(self, parse_until): TemplateSyntaxError: Invalid block tag: 'block' </pre><p> however, this works: </p> <pre class="wiki">Matt-George:gapp mattgeorge$./ shell Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) Type "copyright", "credits" or "license" for more information. IPython 0.8.2 -- An enhanced Interactive Python. ? -&gt; Introduction and overview of IPython's features. %quickref -&gt; Quick reference. help -&gt; Python's own help system. object? -&gt; Details about 'object'. ?object also works, ?? prints more. In [1]: from django.template import Template, Context In [2]: from django.template.loader import * In [3]: t = Template('''{% block title %}Hello{% endblock %}''') </pre><p> it looks like the issue comes from the line:<br /> add_to_builtins('django.template.loader_tags') </p> <p> in django.template.loader </p> Results #7537: Make RegexURLResolver easier to subclass Wed, 25 Jun 2008 15:17:46 GMT kcarnold <p> Referencing <a class="ext-link" href=""><span class="icon">​</span>the django-developers discussion</a>, here's some simple patches to make the URL resolver easier to customize. </p> <p> First is a nearly minimal patch to convert the url_patterns property to an accessor, get_url_patterns, to ease subclassing, and make the other methods use that consistently instead of duplicating its functionality. With only this patch you can make your own URL resolver without duplicating code, but it's still not clean. </p> <p> The second patch cleans up the situation by abstracting the core functionality of a regex URL resolver into <tt>BaseRegexURLResolver</tt>. </p> <p> The third patch is an example of how newforms-admin might use this for URL dispatching. I don't have a deep understanding about what's going on, so treat what I did just as an example. Perhaps the cleanest way to accomplish some of what the old ad-hoc resolver did is to override <tt>resolve</tt>, and if <tt>super().resolve</tt> returns None, do the ad-hoc stuff. </p> <p> You'd use a custom resolver in your urlconf like this: </p> <pre class="wiki">urlpatterns += [AdminSite(r'^admin/')] </pre><p> i.e., like a normal <tt>include</tt> (at least, what that <tt>include</tt> looks like under the hood). </p> <p> The newforms-admin change would be backwards-incompatible, so if people think it's a good idea, it should get a separate ticket. </p> <p> About the accessor: properties don't inherit well. Could add a <tt>url_patterns = property(lambda self: self.get_url_patterns())</tt> if that's not too ugly. </p> Results #7556: inspectdb fails in MySql if a table references a table outside the current schema Fri, 27 Jun 2008 15:32:35 GMT brockweaver <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 '' doesn't exist") </pre><p> So it tries to use <tt></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, 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> Results #7599: add get_user_permissions method to ModelBackend Wed, 02 Jul 2008 05:19:33 GMT gwilson <p> Makes the code more readable and creates a useful method for subclasses. </p> Results #7623: Multi-table inheritance does not allow linking new instance of child model to existing parent model instance. Thu, 03 Jul 2008 15:23:26 GMT brooks.travis@… <p> As it exists now, multi-table inheritance does not allow for the creation of a child model instance that inherits from an existing parent model instance. For example: </p> <p> Parent Class- </p> <pre class="wiki">class Place(models.Model): name = models.CharField(max_length=50) address = models.TextField(max_length=150) </pre><p> Child Classes- </p> <pre class="wiki">class Restaurant(Place): place = models.OneToOneField(Place, parent_link=True) cuisine = models.CharField(max_length=75) rating = models.IntegerField() class Bar(Place): parent = models.OneToOneField(Place, parent_link=True) happy_hour = models.BooleanField() beers_on_tap = models.ManyToManyField("Beers", null=True, blank=True) </pre><p> Sample Use-case- </p> <p> When the system is first deployed, a restaurant instance is created. Later, the restaurant adds a bar to increase revenue, and we now want to create a Bar model instance for the parent Place for the restaurant. I would propose the following interface for doing so: </p> <pre class="wiki">parentPlace = Restaurant.objects.get(name__iexact="Bob's Place").parent barInstance = Bar(parent=parentPlace, happy_hour=True) </pre><p> However, if you attempt to create an instance in this manner now, you receive a DatabaseIntegrityError, saying that a Place object with that id already exists. </p> Results #7732: Oracle Backend with SessionPool Sat, 12 Jul 2008 14:30:08 GMT halturin <p> This new backend uses Oracle session pool to improve database performance in threaded environment. Overall speedup for large amounts of small queries is 2-3 times. </p> Results #8270: Add convenience method to ContentTypeManager Tue, 12 Aug 2008 23:13:54 GMT jdunck <p> app_label, model_name (e.g. ('news', 'story')) is often passed around internally in our codebase. </p> <p> The attached patch would be nice in Django, since otherwise we do a little hula to get the ContentType object. Doing a direct query would miss the handy cache ContentTypeManager includes. </p> Results #8408: Add a new meta option: don't do count(*) in admin Tue, 19 Aug 2008 07:09:11 GMT lidaobing <p> Hello, </p> <p> everytime when I use Admin to view a table, the Admin count the rows in the table. if the database is mysql+innodb, this step is very slow, how about add an option in Meta to prevent this, such as </p> <div class="code"><pre><span class="k">class</span> <span class="nc">A</span><span class="p">(</span>models<span class="o">.</span>Model<span class="p">):</span> <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span> do_not_count <span class="o">=</span> <span class="bp">True</span> </pre></div><p> thanks </p> Results #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 GMT Wonlay <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') b = B() # 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> Results #8690: FormPreview should pass request to parse_params Fri, 29 Aug 2008 17:11:42 GMT bthomas <p> It would be very useful to have request data in parse_params. The example given is to capture something like a user_id, but the main thing I would want to do here is to verify that the current user has permission to access the URL given. Of course, adding a parameter breaks backwards compatibility, so this is a similar request to <a class="closed ticket" href="" title="New feature: FormPreview should pass the form to done() (closed: wontfix)">#7222</a>. </p> Results #8972: Add ability to delete selected vector features within the Geodjango/OpenLayers Admin map interface Mon, 08 Sep 2008 17:35:43 GMT springmeyer <p> This feature has been needed for some time, and was recently requested. See: <a class="ext-link" href=""><span class="icon">​</span></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> Results #9061: formsets with can_delete=True shouldn't add delete field to extra forms Fri, 12 Sep 2008 18:47:59 GMT gsf <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, but haven't bothered with patching tests yet. </p> Results #9422: Incorrect handling of foreign keys by serializers Wed, 22 Oct 2008 16:22:06 GMT etianen <p> When a foreign key points to a remote object via a non-primary key field, the Python serializer and XML serializer classes can sometimes handle this incorrectly. </p> <p> This occurs when the primary key of the related object is a OneToOneField, as is the case for model inheritance. In this case, the serializer will store the <span class="underline">unicode</span> version of the primary key, rather than the primary key itself. </p> <p> As an example: </p> <pre class="wiki">class Foo(models.Model): pass class Bar(Foo): name = models.CharField(max_length=244) slug = models.SlugField(unique=True) def __unicode__(self): return class Wibble(models.Model): bar = models.ForeignKey(Bar, to_field="slug") </pre><p> when a Wibble instance is serialized, the value of the 'bar' property will be serialized as the result of calling <span class="underline">unicode</span> on the referenced Bar. </p> <p> This problem can be resolved with the attached patch. </p> Results #9449: test runner repeatedly parsers fixtures Sat, 25 Oct 2008 19:27:37 GMT trevor <p> The django test runner calls loaddata for every test case which has fixtures. In projects which reuse the same fixtures for multiple test cases, running the test suite results in the wasteful repeated parsing of the same test fixtures, which is very slow. For my application, caching the result of fixture parsing results in an at least 7% speedup in the test suite. </p> Results #9586: Shall upload_to return an urlencoded string or not? Thu, 13 Nov 2008 16:02:31 GMT eibaan <p> Assume a custom upload_to function. If I return any unicode string (for example "<tt>Großköln / €</tt>"), that string is tried to use as a filename and as the URL. It might be an invalid file name and/or an invalid URL. If I use django.util.http.urlquote before returning the string, it becomes a valid URL but at the same time, the file is saved as "<tt>Gro%C3%9Fk%C3%B6ln%20/%20%E2%82%AC</tt>" but is tried to load as "<tt>Großköln / €</tt>" (because the browser already decodes it) from the file system. This does not work. I think, the URL (at least the one used in the admin UI) needs to be urlencoded once more. Or the default storage should automatically make sure that it can store files under any name and is not restricted to the restrictions of the file system. </p> <p> I'm not sure what's the best solution but right now, it doesn't work for anything but an unspecified safe subset of characters. And because there's one function that is the base for both the file system name and the URL path segment, I cannot easiliy fix it. </p> Results #9893: Filename + path length greater than 100 truncated on database insertion in Core.Storage Fri, 19 Dec 2008 21:33:50 GMT Refefer <p> In, the storage object doesn't check the length of filename + upload_to to ensure that it's less than 100 characters. If the path length is greater than 100, it is truncated to 100 characters when inserted into the database. With filename collision mitigation appending an '_' to the end of the filename, popular filenames can easily reach lengths that exceed the size of the. </p> <p> To reproduce the issue, try uploading a file/image with a length over 100 characters. </p> <p> <strong>Solution:</strong> Here's some quick hackery that attempts truncate the filename. Note that it assumes the upload_to length to be less than 30 characters long. Also note that this should probably be divided up into a couple of different methods and this is more to get the ball rolling than anything. </p> <pre class="wiki"> def get_available_name(self, name): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ # If the filename already exists, append an incrementing integer # to the file until the filename doesn't exist. dir_name, file_name = os.path.split(name) flength = len(file_name) if flength &gt; 70: # If filenameis longer than 70, truncate filename offset = flength - (flength % 40 + 20) # modulus of file name + 20 to prevent file type truncation file_name = file_name[offset:] name = os.path.join(dir_name, file_name) if self.exists(name): # filename exists, get dot index try: dot_index = file_name.rindex('.') except ValueError: # filename has no dot dot_index = -1 inc = 0 # Set incrementer to zero while self.exists(name): inc += 1 if dot_index == -1: # If no dot, append to end tname = file_name + str(inc) else: tname = file_name[:dot_index] + str(inc) + file_name[dot_index:] name = os.path.join(dir_name, tname) return name </pre> Results #9894: Give the FileField 'upload_to' callable access to an UploadedFile's contents. Sat, 20 Dec 2008 02:17:03 GMT Pyth <p> <tt>FileField.upload_to</tt> allows for a callable and requests an <tt>instance</tt> and a <tt>filename</tt>. Because it may be of interest to the programmer to use the file's content (MD5 sum, MIME type, ID3 tags etc.) in the upload path, it would be handy to be able to access it from the callable method. </p> <p> One possibility would be to pass an <tt>UploadedFile</tt> instead of a <tt>filename</tt> but this would break the compatibility policy in 1.0.X. Temporarily, this functionality could be added via an <tt>uploaded_file</tt> or <tt>content</tt> property added to the instance (in <tt></tt>), making it accessible from the <tt>upload_to(instance, filename)</tt> callable with <tt>instance.uploaded_file</tt>. </p> <p> I'll throw up some patches if this makes any sense. </p> Results #10070: Named parameters not working on raw sql queries with sqlite Mon, 19 Jan 2009 19:41:46 GMT msurdi <p> The following code shows the problem when using sqlite: </p> <pre class="wiki">$ python shell Python 2.5.2 (r252:60911, Oct 5 2008, 19:29:17) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) &gt;&gt;&gt; from django.db import connection &gt;&gt;&gt; c = connection.cursor() &gt;&gt;&gt; c.execute("select name from inventory_host where id=%(id)s",{'id':'1'}) Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/site-packages/django/db/backends/", line 19, in execute return self.cursor.execute(sql, params) File "/usr/lib/python2.5/site-packages/django/db/backends/sqlite3/", line 167, in execute query = self.convert_query(query, len(params)) File "/usr/lib/python2.5/site-packages/django/db/backends/sqlite3/", line 179, in convert_query return query % tuple("?" * num_params) TypeError: format requires a mapping &gt;&gt;&gt; &gt;&gt;&gt; import django &gt;&gt;&gt; django.VERSION (1, 0, 2, 'final', 0) </pre><pre class="wiki">$ sqlite3 --version 3.5.9 </pre><p> When using Mysql or Postgres, that works (not tested by me, but by others on django-users). </p> Results #10244: FileFields can't be set to NULL in the db Thu, 12 Feb 2009 14:40:54 GMT oyvind <p> Saving FileFields with a none value sets the field to a empty string in the db and not NULL as it should. </p> Results #10403: provide declarative syntax to define FormSets - including ModelFormSet and InlineFormSet Tue, 03 Mar 2009 18:21:58 GMT Koen Biermans <koen.biermans@…> <p> Provide a declarative mechanism to define modelformsets or inlineformsets. </p> <p> The attached patch allows definitions like this: </p> <pre class="wiki">class AuthorForm(forms.ModelForm): class Meta: model = Author class DeclarativeAuthorFormSet(forms.models.ModelFormSet): form = AuthorForm model = Author extra = 3 </pre><p> and </p> <pre class="wiki">class BookForm(forms.ModelForm): class Meta: model = Book class DeclarativeAuthorBooksFormSet(forms.models.InlineFormSet): model = Book form = BookForm parent = 'author' </pre><p> An advantage is that the defined form is directly used as the form class in the formset, not as a base class for a new form class (what inlineformset_factory does). This way specific field definitions and other customisations in the form work like they should so you don't need to redefine things in <span class="underline">init</span>(). </p> Results #10449: HTML accents not escaped out when using newforms Mon, 09 Mar 2009 15:44:36 GMT tipan <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> </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> Results #10609: Permissions on admin actions Tue, 24 Mar 2009 16:08:28 GMT leitjohn <p> Often one would not want an option to appear in the actions select box in the changelist. For instance, you may not want a user who can't delete to see "delete_selected". </p> <p> I propose that we enable the admin to use the auth decorators (permission_required, etc). </p> <pre class="wiki">Index: =================================================================== --- (revision 10163) +++ (working copy) @@ -423,7 +423,11 @@ for klass in [self.admin_site] + self.__class__.mro()[::-1]: for action in getattr(klass, 'actions', []): func, name, description = self.get_action(action) - actions[name] = (func, name, description) + + # check permission + test = getattr(func, "test_func", None) + if test == None or test(request.user): + actions[name] = (func, name, description) return actions </pre> Results #10743: Support lookup separators in ModelAdmin.list_display Sun, 05 Apr 2009 23:08:42 GMT mrts <p> As with <a class="closed ticket" href="" title="Support for lookup separator with list_filter admin option (closed: fixed)">#3400</a>, supporting the <tt>__</tt> lookup separator in <tt>ModelAdmin.list_display</tt> is useful as it avoids calling <tt>__unicode__</tt> bluntly, giving users more control over the output: </p> <ul><li>display several fields from the same related model, </li><li>as listed in <a class="closed ticket" href="" title="Support for lookup separator with list_filter admin option (closed: fixed)">#3400</a>, traverse several levels of relations. </li></ul><p> One could argue that most of this can be achieved with <tt>__unicode__</tt> by cramming the information to its output. </p> <p> However, there's a larger problem with deferred fields (deferring is exemplified in <a class="ext-link" href=""><span class="icon">​</span>this comment</a>) -- namely, that couples admin code to the implementation of <tt>__unicode__</tt> in related models. That is, knowledge of what fields are referred to in <tt>__unicode__</tt> is required to write proper deferred statements. </p> <p> A case to illustrate how changes in <tt>__unicode__</tt> can have dramatic, unintentional impact: </p> <ul><li>assume the related objects are large and complex, </li><li>to keep the admin changelist view snappy, the developer looks which fields are referred to in their <tt>__unicode__</tt> and writes the <tt>ModelAdmin.queryset()</tt> method correspondingly, selecting only these fields with <tt>only()</tt>, </li><li>a single query is all that is needed to display the data in changelist view, admin is snappy, there is much rejoicing, </li><li>a second person keeps hacking at the related models, unknowing the impact changes to <tt>__unicode__</tt> could have to admin, adds another field to it, </li><li>suddenly rendering the changelist results in <tt>n</tt> queries, each of which pulls in the whole object. </li></ul><p> All that can be avoided with explicit <tt>__</tt> support. </p> Results #10827: django.auth create_permissions must clear the content type cache before creating permissions Wed, 15 Apr 2009 21:39:56 GMT seanl <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> Results #10933: Avoid " TypeError: Cannot convert Decimal("0.0000") to Decimal " when the decimal module has been reloaded Mon, 27 Apr 2009 09:54:32 GMT gagravarr <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 on a model with a decimal field will blow up (see <a class="ext-link" href=""><span class="icon">​</span></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/ (revision 9643) +++ django/db/models/fields/ (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> Results #10941: Add querystring helper methods to Page class Tue, 28 Apr 2009 00:57:52 GMT benspaulding <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> Results #11072: Add Info Window Html to GMarker Mon, 11 May 2009 17:07:03 GMT Ubercore <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, 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> Results #11074: syncdb should execute custom field SQL separately from initial model SQL Mon, 11 May 2009 19:42:12 GMT psmith <p> Currently, if I have exception-throwing SQL in a &lt;app&gt;/&lt;model&gt;.sql file, this breaks <a class="wiki" href="">GeoDjango</a>'s creation of geometry fields and indexes on ./ syncdb. You wind up with a database table that has the regular Django fields but is missing geometry fields at the end of the syncdb command. This is because <a class="wiki" href="">GeoDjango</a>'s field-specific post-table-creation SQL which actually creates the geometry fields (from the post_create_sql() hook) is lumped in with the initial model SQL. I am proposing that custom field post-table-creation SQL like <a class="wiki" href="">GeoDjango</a> emits and user-specified initial model SQL in *.sql files be run in separate transactions. </p> <p> Arguably if my custom initial model SQL is broken then I shouldn't expect syncdb to work cleanly. But it may be surprising that my probably unrelated initial model SQL leaves my <a class="wiki" href="">GeoDjango</a> model tables (or any model with a custom field that implements post_create_sql()) in an incomplete or undefined state because it happens to be executing in the same transaction as the custom field SQL. syncdb does charge ahead and create as much as possible despite exceptions, so I think one could argue that leaving the database in as consistent a state as possible despite errors is a decent goal. </p> Results #11111: WSGIRequest should not make PATH_INFO and SCRIPT_NAME unicode Thu, 14 May 2009 01:01:30 GMT mgood <p> The <a class="ext-link" href=""><span class="icon">​</span>WSGI spec</a> requires the standard environment values to be <tt>str</tt>, not <tt>unicode</tt> types, but the WSGIRequest object updates the environ (via self.META which is a reference), setting PATH_INFO and SCRIPT_NAME to unicode objects. These unicode values led to some issues with <a class="ext-link" href=""><span class="icon">​</span>WebTest</a> which checks to ensure that the environ only contains <tt>str</tt> values. </p> Results #11156: Unnecessary savepoints with Oracle Wed, 20 May 2009 10:24:55 GMT Richard Davies <richard.davies@…> <p> Savepoints are implemented in the Postgresql and Oracle backends, and provide a useful features to users of both. </p> <p> In addition, the framework itself wraps various calls in savepoints (e.g. inside django/db/models/ This is to work around a Postgresql-specific oddity that the open transaction needs to be rolled back to a prior savepoint if it experiences a database exception. </p> <p> This oddity is not present on Oracle, so the extra savepoints are not required. We probably need to split the current single backend flag uses_savepoints into two: can_savepoint and needs_savepoint_after_exception. </p> <p> See <a class="ext-link" href=""><span class="icon">​</span></a> </p> Results #11265: ForeignKey/OneToOneField should support user-defined id attribute name Fri, 05 Jun 2009 12:03:46 GMT dstora <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: =================================================================== --- (revision 10924) +++ (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' % + if self.__id_attr_name: + return self.__id_attr_name + else: + return '%s_id' % def get_validator_unique_lookup_type(self): return '%s__%s__exact' % (, 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> Results #11482: Add Google map events handling Wed, 15 Jul 2009 14:53:51 GMT kapa77 <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> Results #11487: Oracle encoding bug when saving more than 4000 characters Thu, 16 Jul 2009 15:11:57 GMT mdpetry <p> I am working on a project where I have to store a large amount of content, (html) in a record from a table, I am using Oracle as the database </p> <p> What is very strange ... is put a text reasonably small, (around 3000 characters) and it works correctly, save without problems, but doubling this size, this content is saved completely changed. </p> <p> This patch works well on: Django 1.1 (svn), debian, and Oracle 10g with cx_oracle 4.4.1 </p> Results #11495: Improvements to django.views.static.serve directory indexes Fri, 17 Jul 2009 02:18:06 GMT SmileyChris <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> Results #11590: REQUEST: Give LabelCommand an option for default behavior (when no labels are specified) Wed, 29 Jul 2009 17:03:03 GMT maaku <p> The LabelCommand class is handy, but I've found circumstances where I need a default behavior when no labels are specified on the command line. For example, when specifying directories os.getcwd() provides a reasonable default and a convenient shorthand. Unless I missed something, implementing these commands required reimplementing LabelCommand.handle with the default hard coded in. Obviously violates DRY. </p> <p> Suggestion: </p> <ol><li>Add field "default_label" to LabelCommand with value "None" </li><li>Switch (line 317-318 in django/trunk/django/core/management/ </li></ol><pre class="wiki">if not labels: raise CommandError('Enter at least one %s.' % self.label) </pre><p> to </p> <pre class="wiki">if not labels: if not self.default_label raise CommandError('Enter at least one %s.' % self.label) else: labels = [self.default_label] </pre><p> or something similar. </p> <p> Patch is attached. </p> Results #11605: syncdb breaks for some proxy models Thu, 30 Jul 2009 19:12:55 GMT jds <p> If the proxy model is in an application listed before the parent model's application, the table does not get created. </p> <p> I have an application, testapp, with this testapp/ </p> <pre class="wiki">from django.contrib.auth.models import User class MyUser(User): class Meta: proxy = True </pre><p> INSTALLED_APPS has testapp listed before django.contrib.auth. The auth_user table does not get created. </p> <p> This is related to <a class="closed ticket" href="" title=" reset not working for proxy models (closed: fixed)">#11428</a>. The patch shows where the issue is. </p> <p> If this is intended behavior, a small addition to the Available Settings &gt; INSTALLED_APPS documentation would clear this up. </p> Results #11634: OpenLayers default position Tue, 04 Aug 2009 20:01:00 GMT dalkvist <p> The openlayers.js templet don't take the display projection setting from the GeoModelAdmin classes in to consideration when applying the default position. </p> <p> Fore example then the display projection is sett to 4326 (wgs83 standard lon/lat) and the map projection is sett to 900913 (the "google projection"). Then it is reasonable to expect the default position to be in the display projection and not the map projection. </p> <p> The supplied patch checks to see if the display_projection is sett, if it is then adds a transformation call (from display projection to map projection) when the default position is used, in the openlayers.js </p> Results #11642: Specify default namespace in Thu, 06 Aug 2009 01:34:43 GMT mrmachine <p> The new URL namespace feature is great, but could be made a little easier to use by allowing a default namespace to be defined as a variable in the urls module being included (e.g. <tt>namespace</tt>). This could be looked up by Django automatically if no namespace is specified when the urls module is included, in the same way that <tt>urlpatterns</tt> is looked up. </p> <p> In <tt>myapp/</tt>: </p> <pre class="wiki">namespace = 'myapp' urlpatterns('myapp', url('^$', 'index', name='index'), ) </pre><p> In <tt>myproject/</tt>: </p> <pre class="wiki">urlpatterns('', url(r'^myapp/$', include('myapp.urls')), ) </pre><p> In your templates: </p> <pre class="wiki">{% url myapp:index %} </pre><p> The benefit here is that users will not need to specify a namespace for every app in their urls module to avoid clashes with commonly named urls (e.g. "index"), unless they are deploying multiple instances of the same app, which I would have thought is the less common case. </p> <p> At the moment I believe the only way to specify a default namespace (like the <tt>admin</tt> app does) is to define a three item tuple somewhere in <tt>myapp</tt> which contains <tt>urlpatterns</tt> from <tt>myapp.urls</tt> plus app and instance namespaces. But this can't be referenced by a simple string like the urls module can, it must be imported directly before being used. It also seems a little messy and counter-intuitive asking users to import and include <tt>myapp.urls.namespace</tt> or <tt>myapp.urls_namespace</tt> or something similar, instead of just importing or referencing the urls module. </p> Results #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 GMT aiv <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, AuthorAdmin), 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/ +++ django/contrib/admin/ @@ -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/ +++ django/contrib/admin/ @@ -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/ +++ django/contrib/admin/ @@ -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, AuthorAdmin), BookAdmin) </pre><p> I believe, this will be more correct variant. </p> Results #11760: Placeholder for through value in ManyToManyField of abstract class Fri, 21 Aug 2009 11:42:43 GMT MS <p> If you have an abstract class with ManyToManyField it is possible to user %(class)s in related_name for generic related name. Same should be possible for through, to define a generic name for through tables. </p> <p> Example: </p> <pre class="wiki">class ClassA(models.Model): ... class AbstractClass(models.Model): name = models.ManyToManyField(ClassA, related_name = '%(class)s_name', through = 'ClassA_%(class)s') class MyClass(AbstractClass): ... Class ClassA_MyClass(models.Model) class_a=models.ForeignKey(ClassA) my_class=models.ForeignKey(MyClass) </pre><p> The applied patch uses the same mechanism as used for related_name. </p> Results #11854: Add support of PostGIS's Azimuth function Wed, 09 Sep 2009 11:05:57 GMT ckarrie <p> Hi, I would like to see the azimuth function in the gis component. </p> <p> Thank you very much. </p> Results #11927: Allow dumpdata to dump YAML in block style Tue, 22 Sep 2009 13:54:20 GMT sampablokuper <p> Using </p> <pre class="wiki">python dumpdata --format=yaml </pre><p> produces output in <a class="ext-link" href=""><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 dumpdata --format=yaml --flowstyle=false </pre> Results #11929: dumpdata outputs YAML in unhelpful order Tue, 22 Sep 2009 16:28:43 GMT sampablokuper <p> The <a class="ext-link" href=""><span class="icon">​</span>docs</a> suggest providing initial YAML data in the following format: </p> <pre class="wiki">- model: myapp.person pk: 1 fields: first_name: John last_name: Lennon </pre><p> but the dumpdata outputs YAML in the following form: </p> <pre class="wiki">- fields: {first_name: John, last_name: Lennon} model: myapp.person pk: 1 </pre><p> The fact that this is flow rather than block style YAML is the subject of <a class="ext-link" href=""><span class="icon">​</span>#11927</a>, but there's another problem, which is that rather than putting the model and PK first (which is most human-readable), dumpdata outputs the fields first. </p> Results #11974: Submit_row in admin doesn't follow the pattern of using admin/app_label/model/submit_line.html Fri, 02 Oct 2009 19:52:59 GMT vbmendes <p> The admin's submit_row template tag does not follow the pattern for searching for templates: admin/app_label/model/submit_line.html </p> <p> And it would be nice if it supports since it will be easier to override this template. </p> <p> I made a patch that add this support. </p> Results #12044: Add extra_context to admin action delete_selected Fri, 16 Oct 2009 16:06:11 GMT rjc <p> We need to pass extra context in admin action delete_selected, just like admin view's delete_view. </p> Results #12075: Add wsgiorg.routing args support Thu, 22 Oct 2009 16:06:12 GMT Gustavo <p> The <a class="ext-link" href=""><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> Results #12098: HttpRequest __repr__ too verbose Tue, 27 Oct 2009 16:34:51 GMT Cody Soyland <codysoyland@…> <p> When working from a shell, printing request always fills my terminal with unneeded information. I would like to type locals() within a view without garbage all over my screen and type request.META, request.POST, etc if I would like to see more details. My patch replaces GET, POST, COOKIES, and META with the method and URL. </p> Results #12139: forms.fields.DateTimeField and TimeField so not accept stringified datetimes Tue, 03 Nov 2009 12:33:20 GMT mattbennett <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> Results #12199: Give 'firstof' tag ability to assign result to context Wed, 11 Nov 2009 19:06:26 GMT tiliv <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 %}, and drives a {% firstof %} </pre><p> If <tt> substitute </tt> doesn't have a value for <tt> car </tt>, then it will fall back to <tt> </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 %} and drives a {{ }} {% 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> Results #12238: ModelAdmin ignores dynamic fields of ModelForm Wed, 18 Nov 2009 03:19:05 GMT anonymous <p> If a ModelForm is created and then modified to programatically add fields (say, in <tt>__init__</tt>), ModelAdmin ignores these fields when rendering the form. If one of these fields is added to the ModelForm's <tt>Meta</tt>, the field shows up just fine. </p> <p> I would expect the field to display without the coaxing in <tt>Meta.fields</tt>. </p> <ol><li>Create a ModelForm </li><li>Add it to ModelAdmin </li><li>View Form </li><li>Update ModelForm's <tt>__init__</tt> to include <tt>self.fields['xyz'] = forms.CharField(max_length=255, initial='keke')</tt> </li><li>View Form (note no change) </li><li>Update ModelForm's <tt>Meta.fields</tt> to include "xyz" </li><li>View Form (note the change) </li></ol> Results #12405: django.contrib.auth.views.logout() should support LOGOUT_REDIRECT_URL Sat, 19 Dec 2009 15:06:32 GMT cmwslw <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 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> Results #12471: Wrong assertion in resolve_aggregate in django.db.models.sql.query Thu, 31 Dec 2009 09:04:49 GMT courtjus <p> In the resolve_aggregate method in the django.db.models.sql.query module : </p> <pre class="wiki">297 elif aggregate.is_computed: 298 # Any computed aggregate (e.g., avg) returns a float 299 return float(value) </pre><p> The assertion that <em>"any computed aggregate like AVG returns a float"</em> is wrong. In particular, I use Postgresql/pyscopg2 and postgresql returns an <strong>interval</strong> (datetime.timedelta from the python point of vue) when the aggregated column is of type <strong>interval</strong>. </p> <p> I made a quick and dirty patch attached to the ticket </p> Results #12581: connection.queries should use a ring buffer to avoid large memory consumption under runserver Mon, 11 Jan 2010 17:36:15 GMT robhudson <p> Currently, when running using runserver, each query is appended to a list. For long running runserver processes, this list can grow quite large. </p> Results #12651: AutoSlugField, that can recreate unique slugs during saving. Wed, 20 Jan 2010 15:11:23 GMT Ciantic <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=""><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> Results #12685: Serialized objects' save function does not respect force_insert Mon, 25 Jan 2010 14:02:36 GMT dcotruta <p> Given a serialized trivial object, of the type models.Model, which does not override any functions, a deserialized object does not accept the force_insert keyword argument for its save function. </p> <pre class="wiki">class XYZ(models.Model): xyz_creation_date = models.DateTimeField(verbose_name=_("Date Opened"), blank=False, auto_now_add=True, editable=False ) xyz_is_open = models.BooleanField(default=True) xyz_last_updated = models.DateTimeField(verbose_name=_("Last Report"), blank=False, auto_now=True ) xyz_synced = models.BooleanField(default=False) </pre><p> If this model exists on two separate servers, and instances of this object are serialized, passed over the wire, and then deserialized, the save function on the receiving server cannot pass force_insert=True - doing so yields "save() got an unexpected keyword argument 'force_insert'". </p> <p> Any ideas? </p> Results #12733: Added support for Extent aggregate on mysql databases Sat, 30 Jan 2010 03:41:35 GMT jann.kleen@… <p> This patch enables the usage of extent aggregates for mysql backends, using MIN/MAX queries. </p> Results #12772: Allow loading template tags by fully qualified python module path Thu, 04 Feb 2010 12:19:03 GMT patrys <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> Results #12780: Provide a hook for compound form/formset validation in ModelAdmin Thu, 04 Feb 2010 22:46:02 GMT mrts <p> Sometimes it is necessary to validate inline formset data based on the main form data and vice-versa. </p> <p> See e.g. <a class="ext-link" href=""><span class="icon">​</span></a> for a use case. </p> <p> My use case is somewhat similar: an object can be published only if its associated items meet certain criteria. Thus, to validate the "is published" flag in the form, access to formsets is required. </p> <p> For advanced users a simple change is sufficient: substitute <tt>if all_valid(formsets) and form_validated:</tt> with <tt>if self.formsets_are_valid(formsets, form, form_validated) and form_validated:</tt> in <tt>admin/</tt>, where <tt>def formset_are_valid(self, formsets, ...): return all_valid(formsets)</tt>. The latter can then be overriden for arbitrary further manipulations. Will upload a patch eventually. </p> <p> However, this means that people have to mess with either <tt>Form</tt> or <tt>FormSet</tt> internals directly (<tt>_non_form_errors</tt> etc) to expose the errors. </p> <p> This is yet another proof of a conceptual problem, quoting myself from <a class="ext-link" href=""><span class="icon">​</span></a> : </p> <p> "<em>Inline formsets usually represent composition, i.e. the inline objects are inseparable from the main entity. The relation is stronger than a <a class="wiki" href="">ForeignKey</a> (from the main entity to another entity), yet the latter is displayed as a field of the form and can be easily manipulated -- but not the inlines.</em>" </p> <p> So, this is yet another reason for introducing FormsetFields in the long run -- <tt>Form.clean()</tt> would have access to formsets both in the admin and ordinary forms. </p> Results #12890: extra() tables included twice do not generate aliases Wed, 17 Feb 2010 07:30:48 GMT semenov <p> The documentation at <a class="ext-link" href=""><span class="icon">​</span></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="" title="Bug: GenericRelation fails to join the related table from a inherited model (new)">#12885</a>. </p> Results #12915: formfield_callback is lost in an inherited ModelForm Fri, 19 Feb 2010 14:56:59 GMT semenov <p> Consider the following code: </p> <div class="code"><pre><span class="k">class</span> <span class="nc">BaseTicketForm</span><span class="p">(</span>forms<span class="o">.</span>ModelForm<span class="p">):</span> <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span> fields <span class="o">=</span> <span class="p">(</span><span class="o">...</span><span class="p">)</span> formfield_callback <span class="o">=</span> <span class="k">lambda</span> f<span class="p">:</span> <span class="o">....</span> <span class="k">class</span> <span class="nc">AddTicketForm</span><span class="p">(</span>BaseTicketForm<span class="p">):</span> <span class="k">pass</span> <span class="k">class</span> <span class="nc">EditTicketForm</span><span class="p">(</span>BaseTicketForm<span class="p">):</span> <span class="c"># some logic related to editing tickets here</span> </pre></div><p> When an instance of AddTicketForm or EditTicketForm is created, a user would expect that formfield_callback is applied. However, the current implementation doesn't do that; instead, a user is forced to copy-paste formfield_callback to each and every derived class. </p> Results #12943: Unnamed captures are not passed to views in included URLconfs Tue, 23 Feb 2010 14:45:28 GMT petri.lehtinen@… <pre class="wiki">### mypkg/ def my_view(request, *args, **kwargs): print args print kwargs ### mypkg/ urlpatterns = patterns('mypkg.views', (r'^$', 'my_view')) ### otherpkg/ urlpatterns = patterns('', (r'^(\w+)/', include('mypkg.urls')) </pre><p> With this setup, in <tt>my_view()</tt>, both <tt>args</tt> and <tt>kwargs</tt> are empty, even though there are no named captures that would make Django ignore the unnamed ones. </p> <p> The following works, as the capture in the upper URLconf is named: </p> <pre class="wiki">### otherpkg/ urlpatterns = patterns('', (r'^(?P&lt;foo&gt;\w+)/', include('mypkg.urls')) </pre><p> In this case, <tt>foo</tt> is passed as a kwarg to <tt>my_view()</tt>. </p> <p> The attached patch fixes this, but there's still an issue with extra kwargs to views: As the URL resolving returns triples of the form <tt>(view_func, view_args, view_kwargs)</tt> along from sub URLconfs back to the including URLconf, there's no way of knowing whether we had named captures or extra kwargs in the sub URLconf. They are all collected to <tt>view_kwargs</tt> which is then returned. </p> <p> This could be fixed by passing around quadruples <tt>(view_func, view_args, view_kwargs, extra_kwargs)</tt>, and collect all named URL captures along the chain to <tt>view_kwargs</tt> and all extra kwargs to <tt>extra_kwargs</tt>. If at some level the <tt>view_kwargs</tt> is not empty, we can throw away all the unnamed captures, i.e. set <tt>view_args</tt> to <tt>()</tt>. This fix would be a bit more intrusive, though, so I haven't tried to do it yet. </p> Results #12974: Admindocs app introspection omits several model methods Fri, 26 Feb 2010 06:41:54 GMT jabapyth <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> Results #13008: @never_cache decorator should add 'no-cache' & 'no-store' Tue, 02 Mar 2010 14:13:40 GMT harm <p> I noticed that the never_cache <tt> django/views/decorators/ </tt> does not add all the proper http headers to prevent that a page is cached. It just adds a max-age=0. This does _not_ prevent browsers to actually cache that page. For example when hitting back, firefox will happily show such a page if the connection to the server disappeared. </p> <p> proposal, let never_cache() act as advertised: <strong>never</strong> cache. Let it add 'no-cache, must-revalidate' to the http response. </p> <p> something like: <tt> </tt> </p> <div class="code"><pre><span class="o">---</span> virtualenv<span class="o">/</span>src<span class="o">/</span>django<span class="o">/</span>django<span class="o">/</span>utils<span class="o">/</span>cache<span class="o">.</span>py <span class="mi">2010</span><span class="o">-</span><span class="mo">03</span><span class="o">-</span><span class="mo">02</span> <span class="mi">15</span><span class="p">:</span><span class="mi">11</span><span class="p">:</span><span class="mf">54.000000000</span> <span class="o">+</span><span class="mo">0100</span> <span class="o">+++</span> <span class="o">/</span>tmp<span class="o">/</span>cache<span class="o">.</span>py <span class="mi">2010</span><span class="o">-</span><span class="mo">03</span><span class="o">-</span><span class="mo">02</span> <span class="mi">15</span><span class="p">:</span><span class="mi">11</span><span class="p">:</span><span class="mf">48.000000000</span> <span class="o">+</span><span class="mo">0100</span> <span class="err">@@</span> <span class="o">-</span><span class="mi">104</span><span class="p">,</span><span class="mi">6</span> <span class="o">+</span><span class="mi">104</span><span class="p">,</span><span class="mi">8</span> <span class="err">@@</span> cache_timeout <span class="o">=</span> settings<span class="o">.</span>CACHE_MIDDLEWARE_SECONDS <span class="k">if</span> cache_timeout <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span> cache_timeout <span class="o">=</span> <span class="mi">0</span> <span class="c"># Can't have max-age negative</span> <span class="o">+</span> patch_cache_control<span class="p">(</span>response<span class="p">,</span> no_cache<span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="o">+</span> patch_cache_control<span class="p">(</span>response<span class="p">,</span> must_revalidate<span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="k">if</span> <span class="ow">not</span> response<span class="o">.</span>has_header<span class="p">(</span><span class="s">'ETag'</span><span class="p">):</span> response<span class="p">[</span><span class="s">'ETag'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'"</span><span class="si">%s</span><span class="s">"'</span> <span class="o">%</span> md5_constructor<span class="p">(</span>response<span class="o">.</span>content<span class="p">)</span><span class="o">.</span>hexdigest<span class="p">()</span> <span class="k">if</span> <span class="ow">not</span> response<span class="o">.</span>has_header<span class="p">(</span><span class="s">'Last-Modified'</span><span class="p">):</span> </pre></div> Results #13019: create_update: proxy object displayed instead of model verbose name Wed, 03 Mar 2010 15:05:51 GMT Beuc <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> Results #13033: MySQL full text search in admin Fri, 05 Mar 2010 04:21:52 GMT simon29 <p> Full text search hasn't been implemented properly in admin. The query is being word split and OR'd like regular fields. </p> <p> Attached patch fixes this, allowing you to type in any mysql boolean search. </p> <p> Simply prefix your admin search_fields with @ to use, eg ('@myfield', ). </p> <p> Be sure to include ALL the fields you have included in your index, else mysql might not use the full text index and instead default back to running a standard LIKE query. </p> <p> BTW, I can't recall the various search_field operators mentioned in docs? </p> Results #13060: ManagementForm exception in case of bad prefix should be easier to understand Mon, 08 Mar 2010 18:09:30 GMT Karel <p> If user adds multiple formsets with prefixes, and specifies the prefix incorrectly when binding the form and validating: </p> <pre class="wiki">some_formset = SomeFormSet(request.POST, 'articles') </pre><p> instead of: </p> <pre class="wiki">some_formset = SomeFormSet(request.POST, prefix='articles') </pre><p> Django "suppresses" the original exception and raises only relatively unhelpful "ManagementForm data is missing or has been tampered with". </p> <p> In file django/forms/, line 57: </p> <pre class="wiki"> 54. if or self.files: 55. form = ManagementForm(, auto_id=self.auto_id, prefix=self.prefix) 56. if not form.is_valid(): 57. raise ValidationError('ManagementForm data is missing or has been tampered with') </pre><p> Suggestion: include form._errors in output, because for such a small bug in code, it can take a really long time find it. </p> <pre class="wiki">{'INITIAL_FORMS': [u'This field is required.'], 'MAX_NUM_FORMS': [u'This field is required.'], 'TOTAL_FORMS': [u'This field is required.']} </pre> Results #13068: The "Add another [inline object]" javascript doesn't respect prepopulated_fields settings Wed, 10 Mar 2010 00:37:55 GMT hejsan <p> If I have an inline form with a prepopulated field, i.e: <br /> </p> <pre class="wiki">class SomethingInline(admin.TabularInline): model = Something prepopulated_fields = {'title_slug': ('title',)} extra = 2 </pre><p> Then the extra inlines added by the new javascript dont automatically populate the title_slug field when entering a title. </p> <p> BTW: The alternating row colors also dissappear for me in firefox when I click "Add another.." </p> Results #13110: Multiple enclosures per feed's item Sat, 13 Mar 2010 23:31:22 GMT Piaume <p> For now, Feed.item_enclosure_url represents a single enclosure for an item. It should be nice to support many enclosures per item. Something like that: </p> <pre class="wiki">class ExampleFeed(Feed): def item_enclosure_url(self, item): return [video.url for video in item.videos] </pre> Results #13112: Customize map type in Sun, 14 Mar 2010 06:28:10 GMT nbv4 <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> Results #13117: Recenter OSMGeoAdmin widget with coordinates Mon, 15 Mar 2010 02:10:01 GMT anonymous <p> By default, all mapplets that gets created by the contrib.gis.admin.GeoModelAdmin and contrib.gis.admin.OSMGeoAdmin classes are centered at 0,0, which makes it tedious to enter geographic data with that widget when you have the lattitude and longitude coordinates in numeric form. </p> <p> There should be a textbox for centering the map to a set of coordinates. </p> Results #13161: Ticked 2514 and 5171, solution for using Django with other psycopg2 applications. Fri, 19 Mar 2010 21:53:04 GMT spoksss <p> Hi, </p> <p> I have some problem while I use Django connection based on psycopg2 in the same time while using some other database application. Because Django changes default psycopg2 settings (psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)), I get "psycopg2.InterfaceError: can't decode into unicode string from SQLASCII", when I try use my external database application which works with SQLASCII after import django settings. </p> <p> I think it isn't good way when Django changes default, global settings of psycopg2, because other application can have problems. I have read documentation of psycopg2, and it is possible to set that psycopg2.extensions.UNICODE just for custom connection or cursor, so I think it is good idea to use that feature in Django. <a class="ext-link" href=""><span class="icon">​</span></a> </p> <p> I have tested my changes with psycopg 2.0.8 and Django-1.2-beta-1 and everything work correctly. </p> Results #13163: Display link to change-form on inlines where model is registered in admin site Sat, 20 Mar 2010 00:13:32 GMT DrMeers <p> If an inline object has a <tt>get_absolute_url</tt> method, a 'View on site' link is displayed. </p> <p> Here I propose that if an inline object is registered in the same admin site, an 'Edit' link is displayed in a similar fashion. </p> <p> Why? </p> <ul><li>The inline may only display a subset of fields, so the user may wish to go to the full change form </li><li>'Recursive inlines' can be accessed more easily -- e.g. <tt>Household</tt> has <tt>Person</tt> inlines, and <tt>Person</tt> has <tt>Phone</tt> inlines, etc. </li></ul><p> The attached patch shows a draft implementation. </p> <p> Questions: </p> <ul><li>Do we need to check if the user has change permissions on that model before displaying the link? (in the unlikely event that the user has permission to change a model which displays the inlines of a model which they do not have change permissions for). Given that I cannot see a straightforward way of checking for this without the addition of a template tag/filter, and the rarity of such setups, I'd be happy to let the user click the link and get a permission denied page. </li><li>Do we need an <tt>InlineModelAdmin</tt> option for enabling/disabling this link? E.g. <tt>InlineModelAdmin.show_admin_link</tt>. Or are we happy to have it enabled globally? </li><li>Is <tt>[ Edit ]</tt> a sufficiently understandable link label? Would "Edit in Admin", or "Display full form" or something be more appropriate? </li></ul><p> I think the reciprocal of this would also be very useful -- <tt>ForeignKey</tt> widgets could display an <tt>[edit]</tt> link beside the "add new" (green +) link which links to the change form for the selected parent object. </p> Results