Opened 7 years ago

Last modified 7 years ago

#28295 closed Cleanup/optimization

ModelAdmin.prepopulated_fields generates a string with a trailing hyphen — at Version 2

Reported by: monotonee Owned by: monotonee
Component: contrib.admin Version: 1.11
Severity: Normal Keywords: admin, ModelAdmin, prepopulated_fields, urlify, slug
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: yes Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by monotonee)

ModelAdmin.prepopulated_fields

After concatenating the contents of all the source fields, the JavaScript behind ModelAdmin.prepopulated_fields enforces the output string's maximum length according to the max_length of the destination field, if defined. Unfortunately, the truncation operation currently occurs after converting the source string into URL-safe characters and replacing whitespace with hyphen characters. When the source string is truncated at an index immediately following a hyphen (formerly a whitespace character), the string returned by ModelAdmin.prepopulated_fields contains a single, trailing hyphen that is unnecessary, meaningless, unsightly, and possibly problematic.

Example of current behavior using URLify from django/contrib/admin/static/admin/js/urlify.js:

// source_string.length === 57
source_string = 'Reading Chicken Entrails For Project Completion Estimates';

// This length will result in source_string truncation to: 'Reading Chicken Entrails For Project Completion '
max_length = 48; 

// Outputs string 'reading-chicken-entrails-for-project-completion-'
// Note trailing hyphen.
console.log(URLify(source_string, max_length, false));

Example of new, desired behavior:

// source_string.length === 57
source_string = 'Reading Chicken Entrails For Project Completion Estimates';

// This length will result in source_string truncation to: 'Reading Chicken Entrails For Project Completion '
max_length = 48; 

// Outputs string 'reading-chicken-entrails-for-project-completion'
// Note omission of trailing hyphen.
console.log(URLify(source_string, max_length, false));

This issue can, of course, be solved by custom form field validation but, given the spirit and purpose behind ModelAdmin.prepopulated_fields (slug generation and convenience), I believe the returns are worth the effort to ensure that the JavaScript does not return trailing hyphens.

Change History (2)

comment:1 by monotonee, 7 years ago

Has patch: set
Last edited 7 years ago by Tim Graham (previous) (diff)

comment:2 by monotonee, 7 years ago

Description: modified (diff)

Converted Python-style Boolean values to those of JavaScript.

Note: See TracTickets for help on using tickets.
Back to Top