check number even or odd in template
{% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}
check if file is readable
import glob, os
try:
for file in glob.glob("\\*.txt"):
with open(file) as fp:
# do something with file
except IOError:
print("could not read", file)
Or we can also rely on the default exception of python
check if the file exists
os.path.exist(path)
timeout in django/python
import time
time.sleep(secs) # secs is the number of seconds to wait
django form set initial value
def __init__(self, *args, **kwargs):
instance = kwargs.get('instance', None)
kwargs.update(initial={
# 'field': 'value'
'km_partida': '1020'
})
super(ViagemForm, self).__init__(*args, **kwargs)
or
super(ViagemForm, self).__init__(*args, **kwargs)
if field_value:
#self.initial[field_name] = field_value
self.fields[field_name].initial = field_value
Add new field in admin form
from django import forms
from yourapp.models import YourModel
class YourModelForm(forms.ModelForm):
extra_field = forms.CharField()
def save(self, commit=True):
extra_field = self.cleaned_data.get('extra_field', None)
# ...do something with extra_field here...
return super(YourModelForm, self).save(commit=commit)
class Meta:
model = YourModel
replace special characters
removeSpecialChars = z.translate ({ord(c): " " for c in "!@#$%^&*()[]{};:,./<>?\|`~-=_+"})
return unauthorized page and not found page
return HttpResponse('Unauthorized', status=401) # unauthorised page
return HttpResponseNotFound(“hello”) # return not found page