Skip to content

Instantly share code, notes, and snippets.

@develmaycare
develmaycare / django-script.py
Created May 7, 2018 13:40
Standalone Django scripting.
#! /usr/bin/env python
import os
import sys
# Define the path to the project.
PROJECT_PATH = os.path.abspath(os.path.join("example", "source"))
# Let Django know where things are.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings")
@develmaycare
develmaycare / django.html
Last active March 18, 2018 18:42
Twitter Bootstrap Row Cycles in Django and Jinja
{# Assuming a page object with one or more instances of a content block: #}
{% for block in page.blocks %}
{# Start a new row every third block. #}
{% cycle '<div class="row">' "" "" %}
<div class="col-md-4">
{{ block }}
</div>
{# End every third row. #}
{% cycle "" "" '</div>' %}
{% endfor %}
@develmaycare
develmaycare / duration_display.py
Created September 30, 2017 19:47
Human Friendly Duration Display
# Avoid magic numbers.
seconds_per_hour = 3600
minutes_per_hour = 60
# Duration is a total number of seconds, but get be derived from timedelta.total_seconds().
t = timedelta(hours=2, minutes=15)
total_seconds = t.total_seconds()
# Store output in a list.
a = list()
@develmaycare
develmaycare / forms.py
Created April 11, 2017 17:51
Override Django's PasswordResetForm to process only one user email at a time and return the token and uid to the view.
from django.contrib.auth.forms import PasswordResetForm as BasePasswordResetForm
# noinspection PyClassHasNoInit
class PasswordResetForm(BasePasswordResetForm):
"""A self-reset form for users."""
def save(self, domain_override=None, subject_template_name='accounts/password_reset_subject.txt',
email_template_name='accounts/password_reset_email.txt', use_https=False,
token_generator=default_token_generator, from_email=None, request=None, html_email_template_name=None,
extra_email_context=None):
@develmaycare
develmaycare / parse_template.py
Created March 12, 2017 23:02
An example of how to use Jinja as a standalone parser. This is especially useful for command line packages.
# Perhaps there is a better way to do this, but this worked for parsing templates in pyprojectutils.
def parse_jinja_template(path, context):
# The path is the path to the template. One directory up becomes the search path.
search_path = os.path.dirname(path)
env = Environment(loader=FileSystemLoader(search_path))
# The template name is at the end of the path in this case.
template_name = os.path.basename(path)
template = env.get_template(template_name)
@develmaycare
develmaycare / command.py
Created December 11, 2016 15:55
Using Python argparse to create subparsers, allowing sub commands similar to pip, git, and brew.
import argparse
def main():
"""Do something important."""
parser = argparse.ArgumentParser(description=main.__doc__)
subparsers = parser.add_subparsers(
dest="subcommand",
@develmaycare
develmaycare / multi-select-dialog.js
Last active May 24, 2018 13:36
A dialog for Google Sheets for selecting multiple elements in a validation lookup.
/* To use this in a Google Sheet:
1. Go to Tools > Script Editor.
2. Paste this script and click on the bug symbol.
3. Create an HTML page and paste the contents of page.html into the editor.
4. Authorize the script.
5. Refresh the sheet.
*/
/* Set up multi-select validation. Sort of. There will be a validation error,
but this does allow you to select multiple items.
@develmaycare
develmaycare / duplicate-row.js
Last active September 22, 2023 11:34
Duplicate a row in Google Sheets.
/* To use this in a Google Sheet:
1. Go to Tools > Script Editor.
2. Save the script.
3. Paste this script and click on the bug symbol.
4. Authorize the script.
5. Refresh the sheet.
*/
// global
var ss = SpreadsheetApp.getActive();
@develmaycare
develmaycare / olp-models2.py
Created September 20, 2013 15:29
This example demonstrates an ad-hoc system for object-level-permissions. See https://gist.github.com/bogeymin/6639176 for a django-guardian example. This example uses djorm and the array field for Postgres, so it is not portable, and comes with additional package requirements. But it should be much faster with few queries than with django-guardian.
class PermissionsModel(models.Model):
"""In this approach, permissions may be filtered directly using a queryset.
"""
objects = ExpressionManager()
groups = ArrayField(dbtype="int", null=True)
users = ArrayField(dbtype="int", null=True)
@develmaycare
develmaycare / olp-models1.py
Created September 20, 2013 15:22
This is an example of complex object-level permissions using django-guardian. This is from a real-world project, and the problem that I see is the large number of queries required to assign permissions. See https://gist.github.com/bogeymin/6639293 for an example of solving this in a somewhat unorthodox, but simple way.
class Project(models.Model):
added_by = models.ForeignKey(User, related_name="added_by_projects")
assigned_to = models.ForeignKey(User, related_name="assigned_to_projects")
owned_by = models.ForeignKey(User, related_name="owned_by_projects")
is_private = models.BooleanField()
all_access = models.BooleanField()
departments = models.ForeignKey(Department)
restrict_access_by_default = models.BooleanField()