Django Template Filter Replace
I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to. I want to change & amp. Replacing a character in Django template. From django import template register = template.Library() @register.filter def to_and. If I have a string in my django template that is formatted like: Line 1Line 2Line 3Line 4 And I want to format it like.
I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input. Spherical water tank. WikiLink is defined as: ThisIsAWikiLink This is the alt text Here's a working example that does not query the database: from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library @register.filter @stringfilter def wikilink(value): return re.sub(r' ?(.?)?
?(.?)? ', r' 2', value) wikilink.issafe = True The input ( value) is a multi-line string, containing HTML and many WikiLinks. The expected output is substituting ThisIsAWikiLink This is the alt text with. This is the alt text or if 'ThisIsAWikiLink' doesn't exist in the database:.
This is the alt text and returning value. Here's the non-working code (edited in response to comments/answers): from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library @register.filter @stringfilter def wikilink(value): m = re.match(r' ?(.?)? ?(.?)? ', value) if(m): pagealias = m.group(2) pagetitle = m.group(3) try: page = Page.objects.get(alias=pagealias) return re.sub(r'( )(.) (.)( )', r' 3', value) except Page.DoesNotExist: return re.sub(r'( )(.) (.)( )', r' 3', value) else: return value wikilink.issafe = True What the code needs to do is:. extract all the WikiLinks in value. query the Page model to see if the page exists. substitute all the WikiLinks with normal links, styled dependent on each wikipage existence.
return the altered value The updated question is: What regular expression (method) can return a python List of WikiLinks, which can be altered and used to substitute the original matches (after being altered). Edit: I'd like to do something like this: def wikilink(value): regex = re.magicmethod(r' ?(.?)?
?(.?)? ', value) foreach wikilink in regex: alias = wikilink.group(0) text = wikilink.group(1) if(alias exists in Page): regex.sub('+ text +') else: regex.sub('+ text +') return value. If your string contains other text in addition to the wiki-link, your filter won't work because you are using re.match instead of re.search. Re.match matches at the beginning of the string.
Re.search matches anywhere in the string. Also, your regex uses the greedy., so it won't work if one line contains multiple wiki-links. Instead to make it non-greedy: re.search(r' (.?) (.?) ', value) Edit: As for tips on how to fix your code, I suggest that you use. The advantages are:. It works correctly if you have multiple wiki-links in the same line. One pass over the string is enough.
You don't need a pass to find wiki-links, and another one to do the replacement. Here is a sketch of the implmentation: import re WIKILINKRE = re.compile(r' (.?) (.?) ') def wikilink(value): def wikilinksubcallback(matchobj): alias = matchobj.group(1).strip text = matchobj.group(2).strip if(alias exists in Page): classattr = ' else: classattr = ' class='redlink' return '%s'% (alias, classattr, text) return WIKILINKRE.sub(wikilinksubcallback, value).
This is the type of problem that falls quickly to a small set of unit tests. Pieces of the filter that can be tested in isolation (with a bit of code restructuring):. Determining whether or not value contains the pattern you're looking for. What string gets generated if there is a matching Page. What string gets generated is there isn't a matching Page That would help you isolate where things are going wrong. You'll probably find that you'll need to rewire the regexps to account for optional spaces around the.
Also, on first glance it looks like your filter is exploitable. You're claiming the result is safe, but you haven't filtered the alt text for nasties like script tags. This is the working code in case someone needs it: from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library @register.filter @stringfilter def wikilink(value): WIKILINKRE = re.compile(r' ?(.?)? ?(.?)? ') def wikilinksubcallback(matchobj): alias = matchobj.group(1).strip text = matchobj.group(2).strip classattr = ' try: Page.objects.get(alias=alias) except Page.DoesNotExist: classattr = ' class='redlink' return '%s'% (alias, classattr, text) return WIKILINKRE.sub(wikilinksubcallback, value) wikilink.issafe = True Many thanks for all the answers!
Overview The biggest new feature in Django 1.4 is when handling date/times. When enabled, this Django will store date/times in UTC, use timezone-aware objects internally, and translate them to users’ local timezones for display.
If you’re upgrading an existing project to Django 1.4, switching to the timezone aware mode may take some care: the new mode disallows some rather sloppy behavior that used to be accepted. We encourage anyone who’s upgrading to check out the and the for useful pointers. Other notable new features in Django 1.4 include:. A number of ORM improvements, including, the ability to large datasets for improved performance, and, a method to batch-load related objects in areas where doesn’t work. Some nice security additions, including (featuring and support), new, several, and. An that removes the “magic” from prior versions.
And for those who don’t like the new layout, you can use instead!. and a whole lot more;! Wherever possible we try to introduce new features in a backwards-compatible manner per policy. However, as with previous releases, Django 1.4 ships with some minor; people upgrading from previous versions of Django should read that list carefully. Python compatibility Django 1.4 has dropped support for Python 2.4. Python 2.5 is now the minimum required Python version.
Django is tested and supported on Python 2.5, 2.6 and 2.7. This change should affect only a small number of Django users, as most operating-system vendors today are shipping Python 2.5 or newer as their default version.
If you’re still using Python 2.4, however, you’ll need to stick to Django 1.3 until you can upgrade. Per, Django 1.3 will continue to receive security support until the release of Django 1.5. Django does not support Python 3.x at this time. At some point before the release of Django 1.4, we plan to publish a document outlining our full timeline for deprecating Python 2.x and moving to Python 3.x. Support for time zones In previous versions, Django used “naive” date/times (that is, date/times without an associated time zone), leaving it up to each developer to interpret what a given date/time “really means”.
This can cause all sorts of subtle timezone-related bugs. In Django 1.4, you can now switch Django into a more correct, time-zone aware mode.
In this mode, Django stores date and time information in UTC in the database, uses time-zone-aware datetime objects internally and translates them to the end user’s time zone in templates and forms. Reasons for using this feature include:. Customizing date and time display for users around the world. Storing datetimes in UTC for database portability and interoperability. (This argument doesn’t apply to PostgreSQL, because it already stores timestamps with time zone information in Django 1.3.). Avoiding data corruption problems around DST transitions. Time zone support is enabled by default in new projects created with.
If you want to use this feature in an existing project, read the. If you encounter problems, there’s a helpful. Updated default project layout and manage.py Django 1.4 ships with an updated default project layout and manage.py file for the management command. These fix some issues with the previous manage.py handling of Python import paths that caused double imports, trouble moving from development to deployment, and other difficult-to-debug path issues. The previous manage.py called functions that are now deprecated, and thus projects upgrading to Django 1.4 should update their manage.py. (The old-style manage.py will continue to work as before until Django 1.6. In 1.5 it will raise DeprecationWarning).
The new recommended manage.py file should look like this. QuerySet.prefetchrelated Similar to but with a different strategy and broader scope, has been added to. This method returns a new QuerySet that will prefetch each of the specified related lookups in a single batch as soon as the query begins to be evaluated.
Unlike selectrelated, it does the joins in Python, not in the database, and supports many-to-many relationships, GenericForeignKey and more. This allows you to fix a very common performance problem in which your code ends up doing O(n) database queries (or worse) if objects on your primary QuerySet each have many related objects that you also need to fetch.
Django Template Filter Date
No wrapping of exceptions in TEMPLATEDEBUG mode In previous versions of Django, whenever the TEMPLATEDEBUG setting was True, any exception raised during template rendering (even exceptions unrelated to template syntax) were wrapped in TemplateSyntaxError and re-raised. This was done in order to provide detailed template source location information in the debug 500 page. In Django 1.4, exceptions are no longer wrapped. Instead, the original exception is annotated with the source information. This means that catching exceptions from template rendering is now consistent regardless of the value of TEMPLATEDEBUG, and there’s no need to catch and unwrap TemplateSyntaxError in order to catch other errors. Error report filtering We added two function decorators, and, to allow designating the local variables and POST parameters that may contain sensitive information and should be filtered out of error reports. All POST parameters are now systematically filtered out of error reports for certain views ( login, passwordresetconfirm, passwordchange and addview in, as well as userchangepassword in the admin app) to prevent the leaking of sensitive information such as user passwords.
You can override or customize the default filtering by writing a. For more information see the docs on. Django.contrib.admin The included administration app django.contrib.admin has for a long time shipped with a default set of static files such as JavaScript, images and stylesheets. Django 1.3 added a new contrib app django.contrib.staticfiles to handle such files in a generic way and defined conventions for static files included in apps.
Starting in Django 1.4, the admin’s static files also follow this convention, to make the files easier to deploy. In previous versions of Django, it was also common to define an ADMINMEDIAPREFIX setting to point to the URL where the admin’s static files live on a Web server. This setting has now been deprecated and replaced by the more general setting. Django will now expect to find the admin static files under the URL /admin/. If you’ve previously used a URL path for ADMINMEDIAPREFIX (e.g.
/media/) simply make sure and are configured and your Web server serves those files correctly. The development server continues to serve the admin files just like before.
Read the for more details. If your ADMINMEDIAPREFIX is set to an specific domain (e.g. Make sure to also set your setting to the correct URL – for example, http://media.example.com/. Supported browsers for the admin Django hasn’t had a clear policy on which browsers are supported by the admin app. Our new policy formalizes existing practices: browsers should provide a fully-functional admin experience, with the notable exception of Internet Explorer 6, which is no longer supported.
Released over 10 years ago, IE6 imposes many limitations on modern Web development. The practical implications of this policy are that contributors are free to improve the admin without consideration for these limitations. Obviously, this new policy has no impact on sites you develop using Django. It only applies to the Django admin.
Feel free to develop apps compatible with any range of browsers. Removed admin icons As part of an effort to improve the performance and usability of the admin’s change-list sorting interface and and “filter” widgets, some icon files were removed and grouped into two sprite files. Specifically: selector-add.gif, selector-addall.gif, selector-remove.gif, selector-removeall.gif, selectorstacked-add.gif and selectorstacked-remove.gif were combined into selector-icons.gif; and arrow-up.gif and arrow-down.gif were combined into sorting-icons.gif. If you used those icons to customize the admin, then you’ll need to replace them with your own icons or get the files from a previous release. Compatibility with old signed data Django 1.3 changed the cryptographic signing mechanisms used in a number of places in Django.
While Django 1.3 kept fallbacks that would accept hashes produced by the previous methods, these fallbacks are removed in Django 1.4. So, if you upgrade to Django 1.4 directly from 1.2 or earlier, you may lose/invalidate certain pieces of data that have been cryptographically signed using an old method. To avoid this, use Django 1.3 first for a period of time to allow the signed data to expire naturally. The affected parts are detailed below, with 1) the consequences of ignoring this advice and 2) the amount of time you need to run Django 1.3 for the data to expire or become irrelevant. contrib.sessions data integrity check.
Consequences: The user will be logged out, and session data will be lost. Time period: Defined. contrib.auth password reset hash.
Consequences: Password reset links from before the upgrade will not work. Time period: Defined. Form-related hashes: these have a are much shorter lifetime and are relevant only for the short window where a user might fill in a form generated by the pre-upgrade Django instance and try to submit it to the upgraded Django instance:. contrib.comments form security hash. Consequences: The user will see the validation error “Security hash failed.”.
Time period: The amount of time you expect users to take filling out comment forms. FormWizard security hash. Consequences: The user will see an error about the form having expired and will be sent back to the first page of the wizard, losing the data entered so far. Time period: The amount of time you expect users to take filling out the affected forms.
CSRF check. Note: This is actually a Django 1.1 fallback, not Django 1.2, and it applies only if you’re upgrading from 1.1. Consequences: The user will see a 403 error with any CSRF-protected POST form. Time period: The amount of time you expect user to take filling out such forms. contrib.auth user password hash-upgrade sequence. Consequences: Each user’s password will be updated to a stronger password hash when it’s written to the database in 1.4. This means that if you upgrade to 1.4 and then need to downgrade to 1.3, version 1.3 won’t be able to read the updated passwords.
Remedy: Set to use your original password hashing when you initially upgrade to 1.4. After you confirm your app works well with Django 1.4 and you won’t have to roll back to 1.3, enable the new password hashes. Serialization of and As a consequence of time-zone support, and according to the ECMA-262 specification, we made changes to the JSON serializer:. It includes the time zone for aware datetime objects. It raises an exception for aware time objects.
It includes milliseconds for datetime and time objects. There is still some precision loss, because Python stores microseconds (6 digits) and JSON only supports milliseconds (3 digits). However, it’s better than discarding microseconds entirely. We changed the XML serializer to use the ISO8601 format for datetimes. The letter T is used to separate the date part from the time part, instead of a space. Time zone information is included in the +-HH:MM format. Though the serializers now use these new formats when creating fixtures, they can still load fixtures that use the old format.
Supportstimezone changed to False for SQLite The database feature supportstimezone used to be True for SQLite. Indeed, if you saved an aware datetime object, SQLite stored a string that included an UTC offset. However, this offset was ignored when loading the value back from the database, which could corrupt the data. In the context of time-zone support, this flag was changed to False, and datetimes are now stored without time-zone information in SQLite. When is False, if you attempt to save an aware datetime object, Django raises an exception. Database connection’s thread-locality DatabaseWrapper objects (i.e. The connection objects referenced by django.db.connection and django.db.connections'somealias') used to be thread-local.
They are now global objects in order to be potentially shared between multiple threads. While the individual connection objects are now global, the django.db.connections dictionary referencing those objects is still thread-local. Therefore if you just use the ORM or DatabaseWrapper.cursor then the behavior is still the same as before. Note, however, that django.db.connection does not directly reference the default DatabaseWrapper object anymore and is now a proxy to access that object’s attributes. If you need to access the actual DatabaseWrapper object, use django.db.connectionsDEFAULTDBALIAS instead. As part of this change, all underlying SQLite connections are now enabled for potential thread-sharing (by passing the checksamethread=False attribute to pysqlite). DatabaseWrapper however preserves the previous behavior by disabling thread-sharing by default, so this does not affect any existing code that purely relies on the ORM or on DatabaseWrapper.cursor.
Finally, while it’s now possible to pass connections between threads, Django doesn’t make any effort to synchronize access to the underlying backend. Concurrency behavior is defined by the underlying backend implementation. Check their documentation for details.
From django.conf import settings from django.contrib.comments.managers import CommentManager class BanningCommentManager ( CommentManager ): def getqueryset ( self ): qs = super. Getqueryset if getattr ( settings, 'COMMENTSBANNEDUSERSGROUP', None ): where = 'userid NOT IN (SELECT userid FROM authusergroups WHERE groupid =%s )' params = settings. COMMENTSBANNEDUSERSGROUP qs = qs. Extra ( where = where, params = params ) return qs Save this model manager in your custom comment app (e.g., in mycommentsapp/managers.py) and add it your custom comment app model. IGNORABLE404STARTS = ( '/cgi-bin/', '/vtibin', '/vtiinf' ) IGNORABLE404ENDS = ( 'mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi', 'favicon.ico', '.php' ) It’s not Django’s role to decide if your website has a legacy /cgi-bin/ section or a favicon.ico. As a consequence, the default values of, IGNORABLE404STARTS, and IGNORABLE404ENDS are all now empty.
See More On Stackoverflow
If you have customized IGNORABLE404STARTS or IGNORABLE404ENDS, or if you want to keep the old default value, you should add the following lines in your settings file. Database connections after running the test suite The default test runner no longer restores the database connections after tests’ execution. This prevents the production database from being exposed to potential threads that would still be running and attempting to create new connections. If your code relied on connections to the production database being created after tests’ execution, then you can restore the previous behavior by subclassing DjangoTestRunner and overriding its teardowndatabases method. Request exceptions are now always logged When we added in Django in 1.3, the admin error email support was moved into the, attached to the 'django.request' logger. In order to maintain the established behavior of error emails, the 'django.request' logger was called only when was False. To increase the flexibility of error logging for requests, the 'django.request' logger is now called regardless of the value of, and the default settings file for new projects now includes a separate filter attached to to prevent admin error emails in DEBUG mode.