Development
BeautifulSoup - convert/decode HTML entity codes into regular python string
Dear BeautifulSoup users,
Use convertEntities=BeautifulSoup.HTML_ENTITIES to decode or convert HTML entity codes into regular python strings.
Example:
‘>’ converts to ‘>’
‘&’ decodes ‘&’.
Background
I am working with an XML feed that has HTML embedded in it. By default BeautifulSoup will encodes characters into SGML (or XML or HTML) entities.
This is the XML message I receive.
<message><strong>Hello</strong> world</message>
Since BeautifulSoup automatically encodes the contents of the message to be safe for XML the string you get will be different from the raw XML I expected.
What I wanted
<strong>Hello</strong> world
Instead I got
<strong>Hello</strong> world
Using convertEntites resolves the problem.
soup = BeautifulSoup(content, convertEntities=BeautifulSoup.HTML_ENTITIES)
Answer from StackOverflow
But available in BeautifulSoup Documentation I just didn’t understand their examples.
Access settings.py variables from Django Templates
My goal is to conditionally include google analytics tracking on my Django templates depending on whether settings.DEBUG is on or off as defined in my settings.py file. To accomplish you can write a template context processor that returns the variable with the request context which will make the variable values readable in your Django Templates.
First, add a context_processors.py to the folder for your app (my app is called auto)
Next, copy and paste the function into context_processors.py. As you can see we are simply stuffing the settings variable onto the request object.
def debug_mode(request):
from django.conf import settings
return {'debug_mode': settings.DEBUG}
Now, we add our context processor to the TEMPLATE_CONTEXT_PROCESSORS section in settings.py. If you do not have this section, add it. It won’t break anything.
TEMPLATE_CONTEXT_PROCESSORS = (
'auto.context_processors.debug_mode',
)
Next we have to use the RequestContext. Add this import statement to views.py.
from django.template import RequestContext
Now, set context_instance for all of your template render calls.
def detail(request, template_name="myview.html"):
return render_to_response(template_name, context, context_instance=RequestContext(request))
Finally, you can see if settings.DEBUG is True or False in your Django Templates!
{% if debug_mode %}
<h1>We are debugging!</h1>
{% endif %}
Reference: Django Tips: Template Context Processors
Optimizing Django
For future reference.
