Django custom template tag problem - django

This is my python code for 'box':
register = Library()
class KeyNode(Node):
def __init__(self, _node):
self._node = _node,
def render(self, context):
try:
#content = "this works!"
content = self._node.render(context)
return content
except:
bilogger.exception('KeyNode')
return ''
#register.tag('box')
def wrapper(parser, token):
try:
#fn, _option = token.split_contents()
node = parser.parse(('endbox',))
parser.delete_first_token()
except ValueError:
raise TemplateSyntaxError("INVALID FORMAT PROVIDED FOR BOX")
return KeyNode(node)
self._node.render(context) is an empty string, and nothing is returned back. However, content = "this works!", works.
Whats wrong here?

Related

How to add list datatype in Django model?

This is how my model.py looks like. The third field (label) should contain more than one value (as a news post can have more than one label) like a list. How to achieve that?
from django.db import
class News(models.Model)
heading=models.CharField(max_length=50)
post_date=models.DateTimeField('Date Posted')
labels=models.???
Django not provide default list field, so that you have to create your own list field from inherit TextField, I am posting one of the example code have a look.
class ListField(models.TextField, metaclass=models.SubfieldBase):
description = "ListField store List of element"
SPLIT_CHAR= ';'
def __init__(self, *args, list_choices=None, **kwargs):
super(ListField, self).__init__(*args, **kwargs)
if list_choices is None:
list_choices = []
self.list_choices = list_choices
def to_python(self, value):
res = []
if value is None:
res = []
if isinstance(value, list):
res = value
if isinstance(value, builtins.str):
res = value.split(self.SPLIT_CHAR)
try:
if "[" in value and "]" in value:
res = eval(value)
except:
pass
return res
def get_prep_value(self, value):
if value is None or value == "":
return None
res = self.SPLIT_CHAR.join(value)
return res
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
def formfield(self, **kwargs):
return forms.MultipleChoiceField(choices=self.list_choices)
Then create List field like this one.
from django.db import
class News(models.Model)
heading=models.CharField(max_length=50)
post_date=models.DateTimeField('Date Posted')
labels=ListField()

Flask login 'function' object has no attribute 'is_active'

I try to use flask login in may app:
My controller:
#app.route("/process_log", methods=['POST'])
def process_login():
filled_form = LoginForm(request.form)
if filled_form.validate():
phone = filled_form.phone.data
password = filled_form.password.data
if User.phone_exists(phone) and User.pass_match(phone, password):
user = User.get_by_phone(phone)
login_user(user.get_id)
return redirect(url_for("index"))
else:
return render_template("login.html", form = filled_form, error = u"Не верный логин или пароль")
else:
return render_template("home.html", form = filled_form)
and I have some class with defined functions which required for API of flask login
My User class:
from pymongo import MongoClient
from bson.objectid import ObjectId
class User():
client = MongoClient()
db = client['test']
col = db['user']
user_id = None
def __init__(self, dic):
self.dic = dic
def is_authenticated():
return True
def is_anonymous():
return False
def is_active():
return True
def get_id(self):
return unicode(str(self.user_id))
def save(self):
self.user_id = self.col.insert(self.dic)
print "Debug:" + str(self.user_id)
#staticmethod
def _get_col():
client = MongoClient()
db = client['test']
col = db['user']
return col
#staticmethod
def phone_exists(phone):
col = User._get_col()
if col.find_one({'phone': phone}) != None:
return True
else:
return False
#staticmethod
def pass_match(phone, password):
col = User._get_col()
if col.find_one({'phone': phone})['password'] == password:
return True
else:
return False
#staticmethod
def get(userid):
col = User._get_col()
return col.find_one({'_id':userid})
#staticmethod
def get_by_phone(phone):
col = User._get_col()
dic = col.find_one({'phone': phone})
print dic['password']
return User(dic)
As you see function is_active is defined(Note:I also tried to pass refference with self)
But I still have this error AttributeError: 'function' object has no attribute 'is_active'
I am sorry for too much code here, but it should be pretty straightforward.
Note: I am using mongodb for my project.
Please help me to find my error. Thank you too much
One more thing:
Should I provide login_user(....) with Id or with my user object?
You must sent to login_user User instance (not id), see: https://github.com/maxcountryman/flask-login/blob/master/flask_login.py#L576.
So next code must work:
user = User.get_by_phone(phone)
login_user(user)

Django sitemap for static pages

I'm in the progress of creating a sitemap for my new site.
the site only contains static pages.
I'm trying to get this snippet working:
class StaticSitemap(sitemaps.Sitemap):
"""Return the static sitemap items"""
priority = 0.5
def __init__(self, patterns):
self.patterns = patterns
self._items = {}
self._initialize()
def _initialize(self):
for p in self.patterns:
if getattr(p, 'name', None) is not None:
print p.name
self._items[p.name] = self._get_modification_date(p)
def _get_modification_date(self, p):
template = getattr(p, 'template', None)
template_path = self._get_template_path(template)
mtime = os.stat(template_path).st_mtime
return datetime.datetime.fromtimestamp(mtime)
def _get_template_path(self, template_path):
for template_dir in settings.TEMPLATE_DIRS:
path = os.path.join(template_dir, template_path)
if os.path.exists(path):
return path
return None
def items(self):
return self._items.keys()
def changefreq(self, obj):
return 'monthly'
def lastmod(self, obj):
return self._items[obj]
def location(self, obj):
return reverse(obj)
and I'm getting this KeyError on template from this line: template = p.default_args['template']
How can I get template name?
got it working.
Just added template to kwargs of each url

ZeroDivisionError on GET parameter django

middleware.py
def get_perpage(self):
try:
self.session['perpage'] = int(self.REQUEST['perpage'])
return self.session['perpage']
except (KeyError, ValueError, TypeError):
pass
try:
return int(self.session['perpage'])
except (KeyError, ValueError, TypeError):
return DEFAULT_PAGINATION
I have a problem: when i want to turn zero into URL as GET parameter (?perpage=0), it shows me ZeroDivisionError float division by zero. I need to take ALL objects on page without pagination when perpage=0. How can I do this? What is must be in view.py?
def render(self, context):
key = self.queryset_var.var
value = self.queryset_var.resolve(context)
if (self.paginate_by == None):
paginate_by = int(context['request'].perpage)
else:
paginate_by = self.paginate_by.resolve(context)
if (paginate_by == 0): #HERE
context['page_obj'] = value # IS
return u'' #SOLUTION
print (paginate_by)
paginator = Paginator(value, paginate_by, self.orphans)
try:
page_obj = paginator.page(context['request'].page)
except InvalidPage:
if INVALID_PAGE_RAISES_404:
raise Http404('Invalid page requested. If DEBUG were set to ' +
'False, an HTTP 404 page would have been shown instead.')
context[key] = []
context['invalid_page'] = True
return u''
if self.context_var is not None:
context[self.context_var] = page_obj.object_list
else:
context[key] = page_obj.object_list
context['paginator'] = paginator
context['page_obj'] = page_obj
return u''
when my view gets perpage=0, it returns pure object list (value) without Pagination to template

how to work with modelform and multiwidget

Newbie to all this! i'm working on displaying phone field displayed as (xxx)xxx-xxxx on front end.below is my code. My question is 1. all fields are mandatory, for some reason,phone is not behaving as expected.Even if it is left blank its not complaining and 2.how can i test this widget's functionality
class USPhoneNumberWidget(forms.MultiWidget):
def __init__(self,attrs=None):
widgets = (forms.TextInput(attrs={'size':'3','maxlength':'3'}),forms.TextInput(attrs={'size':'3','maxlength':'3'}),forms.TextInput(attrs={'size':'3','maxlength':'4'}))
super(USPhoneNumberWidget,self).__init__(widgets,attrs=attrs)
def decompress(self, value):
if value:
val = value.split('-')
return [val[0],val[1],val[2]]
return [None,None,None]
def compress(self, data_list):
if data_list[0] and data_list[1] and data_list[2]:
ph1 = self.check_value(data_list[0])
ph2 = self.check_value(data_list[1])
ph3 = self.check_value(data_list[2])
return '%s''%s''%s' %(ph1,ph2,ph3)
else:
return None
def check_value(self,val):
try:
if val.isdigit():
return val
except:
raise forms.ValidationError('This Field has to be a number!')
def clean(self, value):
try:
value = re.sub('(\(|\)|\s+)','',smart_unicode(value))
m = phone_digits_re.search(value)
if m:
return u'%s%s%s' % (m.group(1),m.group(2),m.group(3))
except:
raise ValidationError('Phone Number is required.')
def value_from_datadict(self,data,files,name):
val_list = [widget.value_from_datadict(data,files,name+'_%s' %i) for i,widget in enumerate(self.widgets)]
try:
return val_list
except ValueError:
return ''
def format_output(self,rendered_widgets):
return '('+rendered_widgets[0]+')'+rendered_widgets[1]+'-'+rendered_widgets[2]
class CustomerForm(ModelForm):
phone = forms.CharField(required=True,widget=USPhoneNumberWidget())
class Meta:
model = Customer
fields = ('fname','lname','address1','address2','city','state','zipcode','phone')
In models blank and null are not true.
Any input it highly appreciated.Thanks
Here is the phone field:
phone = forms.CharField(label = 'Phone',widget=USPhoneNumberWidget()
class USPhoneNumberWidget(forms.MultiWidget):
"""
A widget that splits phone number into areacode/next3/last4 with textinput.
"""
def __init__(self,attrs=None):
widgets = (forms.TextInput(attrs={'size':'3','maxlength':'3'}),forms.TextInput(attrs={'size':'3','maxlength':'3'}),forms.TextInput(attrs={'size':'4','maxlength':'4'}))
super(USPhoneNumberWidget,self).__init__(widgets,attrs=attrs)
def decompress(self, value):
if value:
val = value
return val[:3],val[3:6],val[6:]
return None,None,None
def compress(self, data_list):
if data_list[0] and data_list[1] and data_list[2]:
return '%s''%s''%s' %(data_list[0],data_list[1],data_list[2])
else:
return None
def value_from_datadict(self,data,files,name):
val_list = [widget.value_from_datadict(data,files,name+'_%s' %i) for i,widget in enumerate(self.widgets)]
if val_list:
return '%s''%s''%s' %(val_list[0],val_list[1],val_list[2])
def format_output(self,rendered_widgets):
return '( '+rendered_widgets[0]+' )'+rendered_widgets[1]+' - '+rendered_widgets[2]
But depending on how you store the phone# in db 'return' line is to be changed. here I'm accepting it as (xxx)-xxx-xxxx format.In compress it receives ph_0(areacode),ph_1(next 3),ph_2(last4) in that order.but I'm storing it as xxxxxxxxxx.
Firebug helped me understand better about what return values should be. I'll update the answer when i come to know how testing could be done.