I'm wondering what the "best practice" is for storing medium length strings to be used in a UI in Python/Django.
Example:
I have an error.html
template that takes an error_description
field. This is a few sentences explaining to the user what went wrong, and what they might do to address it. It may be different for different error pages, but remains fairly stable in the code(there's no reason that someone who can't push source code should be able to modify it), and can easily be held in memory, so I don't think it's the sort of thing that should be kept in the database.
My current idea is that I should just create some kind of messages.py
file that has a bunch of string constants like this:
ERROR_UNAUTHENTICATED_AJAX_EXPLANATION = "Hello, so the only way that this error should occur is if someone attempts to directly call our AJAX endpoint without having the verification code. Please don't do this, it's against the principles of this art projects."
In general, is there some canonical way to store strings that are "too flexible to be hard coded in", but "too small and static for databases"(and don't scale with your usage)? I'm thinking of the sort of thing that would be in a strings.xml
file in an Android project.
Other possibilities I'm juggling include a text file that views.py reads and stores as constants, actually just hardcoding them, and sticking them in template files.
There's a lot of ways to do this, and it's not a very complicated thing, I just want to know which one is the most 'right'.
Thanks! And let me know if you need more info!
For this, Django provides full support for cookie- and session-based messaging, for both anonymous and authenticated users. The messages framework allows you to temporarily store messages in one request and retrieve them for display in a subsequent request (usually the next one).
Import messages from django. contrib at the top of the file then go to the view function where you wish to add the message(s). In this case, it's a contact view that needs a Django success message and a Django error message. Add a success message just before the return redirect ("main:homepage") stating "Message sent."
Django uses request and response objects to pass state through the system. When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function.
If you are absolutely sure, these strings never need to become dynamic just create a strings.py
module and drop the strings there as variables ("constants")
However, as the messages are user visible, you will most likely need to localize them at some point in your application's lifetime. Consequently, please make use of Django's excellent gettext support:
https://docs.djangoproject.com/en/1.7/topics/i18n/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With