Introducing break and continue in django template - django

Below part of code is copied from this snippet available at django snippet. This code may be working fine for given version but now i want to use it for latest version of django i.e 2.0 and with python-3. Below part of code snippet is given the error :
return template.mark_safe(''.join(map(template.force_unicode,
AttributeError: module 'django.template' has no attribute 'mark_safe'
def render(self, context):
return template.mark_safe(''.join(map(template.force_unicode,
_render_nodelist_items(self,context))))
template.NodeList.render = render
if possible make it working for django 2.0 as i need to use it at multiple place in my project.

Try the following
from django.utils.safestring import mark_safe
from django.utils.encoding import force_text
def render(self, context):
return mark_safe(
''.join(map(force_text(template.render()), _render_nodelist_items(self,context)))
)

Related

Get access to class attributes

import yaml
class Import_Yaml_Setting():
def __init__(self, path):
self.read_yaml(path)
def read_yaml(self, path):
stream = open(path, 'r')
self.settings = yaml.load(stream)
stream.close()
class MasterDef(Import_Yaml_Setting):
def __init__(self, path):
Import_Yaml_Setting.__init__(self, path)
def function_1():
path = 'path_to_settings\\yaml_file.yaml'
MasterDef(path)
def function_2():
MasterDef.settings
if __name__ == '__main__':
function_1()
function_2()
My plan is it to have a class Import_Yaml_Setting which imports settings from a yaml file. The class MasterDef inherits the class Import_Yaml_Setting.
After 'function_1' calls MasterDef in order to import the settings. I want to do this once in my program. After, I just want to get access to the imported settings
without import them again. This should do function_2.
My problem
I don't know how I have to call MasterDef at the first place. If I would create an instance of MasterDef them I wouldn't have access to this instance in function_2.
Also, I get an error that says MasterDef has no attribute settings.
What would be the right way to do this.
There are a few things incorrect, so lets start with the most obvious.
If you have a class MasterDef, calling MasterDef() creates an instance
of that class. If you don't assign that to a variable, that instance will
immediately disappear.
Doing MasterDef.settings later on could work if the class had a
class attribute or method called settings, but in that case you are not accessing
the settings attribute on an instance.
Typical such global settings are passed around, or implemented as a function object that
does the loading only once, or are made into a global variable (as
shown in the following example). Simplified you would do:
from __future__ import print_function, absolute_import, division, unicode_literals
class MasterDef(object):
def __init__(self):
self.settings = dict(some='setting')
master_def = None
def function_1():
global master_def
if master_def is None:
master_def = MasterDef()
def function_2():
print('master_def:', master_def.settings)
if __name__ == '__main__':
function_1()
function_2()
which gives:
master_def: {'some': 'setting'}
A few notes to the above:
If, for whatever reason, you are doing anything new on Python 2.7
make things more Python3 compatible by including the from
__future__ import as indicated. Even if you are just using the
print function (instead of the outdated print statement). It
will make transitioning easier (2.7 goes EOL in 2020)
Again in 2.7 make your base classes a subclass of object, that
makes it e.g. possible to have properties.
By testing that master_def is None you can invoke function_1 multiple
times
You should also be aware that PyYAML load, as is written in its
documentation, can be unsafe when you don't have full control over
your input. There is seldom need to use load() so use safe_load()
or upgrade to my ruamel.yaml package which implements the newer YAML
1.2 standard (released 2009, so there is no excuse for using PyYAML
that still doesn't support that).
As you also seem to be on Windows (assumed from you using \\), consider using raw strings
where you don't need to escape the backslash, using os.path.join(). I am leaving out
your path part in my full example as I am not on Windows:
from __future__ import print_function, absolute_import, division, unicode_literals
import ruamel.yaml
class Import_Yaml_Setting(object):
def __init__(self, path):
self._path = path # stored in case you want to write out the configuration
self.settings = self.read_yaml(path)
def read_yaml(self, path):
yaml = ruamel.yaml.YAML(typ='safe')
with open(path, 'r') as stream:
return yaml.load(stream)
class MasterDef(Import_Yaml_Setting):
def __init__(self, path):
Import_Yaml_Setting.__init__(self, path)
master_def = None
def function_1():
global master_def
path = 'yaml_file.yaml'
if master_def is None:
master_def = MasterDef(path)
def function_2():
print('master_def:', master_def.settings)
if __name__ == '__main__':
function_1()
function_2()
If your YAML file looks like:
example: file
very: simple
the output of the above program will be:
master_def: {'example': 'file', 'very': 'simple'}

How to fix circular importing?

It seems I have a circular importing error. I currently just struggling to fix it. Does anyone know what I should do?
In my models.py, containing ReservedItems & Order:
def reserveditem_pre_save_receiver(sender, instance, **kwargs):
if not instance.order_reference:
instance.order_reference = unique_order_reference_generator()
In my utils.py
from lumis.utils import get_random_string
from .models import Order, ReservedItem
def unique_order_reference_generator():
new_id = get_random_string(length=10)
reserved_item = ReservedItem.objects.filter(
order_reference=new_id
).exists()
order = Order.objects.filter(order_reference=new_id).exists()
if reserved_item or order:
return unique_order_reference_generator()
else:
return new_id
You can import modules locally in the body of the function, so:
from lumis.utils import get_random_string
def unique_order_reference_generator():
from .models import Order, ReservedItem
new_id = get_random_string(length=10)
reserved_item = ReservedItem.objects.filter(
order_reference=new_id
).exists()
order = Order.objects.filter(order_reference=new_id).exists()
if reserved_item or order:
return unique_order_reference_generator()
else:
return new_id
This thus means that the module is not loaded when Python loads the file, but when the function is actually called. As a result, we can load the unique_order_reference_generator function, without having to load a the module that actually depends on this function.
Note that, like #Alasdair says, signals are typically defined in a dedicated file (signals.py) for example which should be loaded in the ready() function of the app. But regardless how you structure code, frequently local imports should be used to avoid circular imports.
All the current suggestions are good. Move your signal handlers out of models. Models are prone to circular imports because they are used everywhere, so it is a good idea to keep only model code in models.py.
Personally, I don't like imports in the middle of the code
import-outside-toplevel / Import outside toplevel
Instead I use Django application API to load models without importing
from django.apps import apps
def signal_handler(instance, *args, **kwargs):
Order = apps.get_model('your_app', 'Order')
...

Importing Your Own Module Python Attribute Error

so I am trying to import my own python module into a new script that I have written. I get the error:
AttributeError: 'module' object has no attribute 'getSessionIds'
In my main file, I am importing as such:
import UnityAppSessionSummary
class ScheduledGenSummaries(DatabaseModule):
def __init__(self):
super(ScheduledGenSummaries, self).__init__()
def run(self):
... (some db connection stuff)
sessionIds = UnityAppSessionSummary.getSessionIds(db, user)
if __name__ == '__main__':
testrun = ScheduledGenSummaries()
testrun.run()
In my UnityAppSessionSummary.py file, I have something as such:
class UnityAppSessionSummary():
# This method is used to obtain a list of all session ID's for a certain user
def getSessionIds(self, db, user):
....code....
I am not sure why I am getting this error and I have looked at other previous posts. I have tried 'import UnityAppSessionSummary as app' and then app.(some function in UnityAppSessionSummary), but it still gives me the error. Thank you in advance.
You have a file UnityAppSessionSummary.py that is being imported when you run
import UnityAppSessionSummary
However, inside that .py file you have a class named UnityAppSessionSummary as well, and inside that is your getSessionIds() method. Try this:
from UnityAppSessionSummary import UnityAppSessionSummary as app
# ...
sessionIds = app.getSessionIds(db, user)

Django - Syntax highlighting with pygments

I'm currently working on my blog site. One of the most important thing in appearance is multi language syntax highlighter. So I decided to use Pygments library and I wrote some code:
from django import template
from pygments import highlight
from pygments.formatters.html import HtmlFormatter
from pygments.lexers import get_lexer_by_name, guess_lexer
from django.utils.safestring import mark_safe
from bs4 import BeautifulSoup
register = template.Library()
#register.filter(is_safe=True)
def highlighter(content):
soup = BeautifulSoup(unicode(content))
codeBlocks = soup.findAll(u'code')
for i,block in enumerate(codeBlocks):
if block.has_attr(u'class'):
language = block[u'class']
else:
language = u'text'
try:
lexer = get_lexer_by_name(language[0])
except ValueError:
try:
lexer = guess_lexer(unicode(block))
except ValueError:
lexer = get_lexer_by_name(language[0])
highlighting = highlight(unicode(block), lexer, HtmlFormatter())
block.replaceWith(highlighting)
return mark_safe(unicode(soup))
In my template i use somethink like this:
<p>{{ post.en_post_content|highlighter|safe|linebreaks}}</p>
Highlighting works well but I can't make it safe because this is what I receive:
http://i.gyazo.com/a2557c861e20a826b28cb5c261e6020f.png
I'm also worried about strange characters like "&#39"
I need advices on how to deal with it. Thanks in advance for reply.

How to use Pyquery with scrapy?

My objective is to use pyquery with scrapy, apparently from scrapy.selector import PyQuerySelector returns ImportError: cannot import name PyQuerySelector when I crawl the spider.
I followed this specific gist https://gist.github.com/joehillen/795180 to implement pyquery.
Any suggestions or tutorials that can help me get this job done?
You declare a class and make your rules and in the callback attribute of rule extractor give parse_item by default the scrapy goes parse() function
def parse_item(self, response):
pyquery_obj = PyQuery(response.body)
header = self.get_header(pyquery_obj)
return {
'header': header,
}
def get_header(self, pyquery_obj):
return pyquery_obj('#page_head').text()