text
stringlengths
0
1.05M
meta
dict
"""adjacency_blockgroups.py Script to compute the adjacency list for the blockgroups in all MSA """ import csv import sys import itertools import fiona from shapely.geometry import shape csv.field_size_limit(sys.maxsize) # # Import list of cities # msa = {} with open('data/names/msa.csv', 'r') as source: reader = csv.reader(source, delimiter='\t') reader.next() for rows in reader: msa[rows[0]] = rows[1] # # Compute the adjacency list # for i,city in enumerate(msa): print "Adjacency %s (%s/%s)"%(msa[city], i+1, len(msa)) ## Import blockgroups blocks = {} with fiona.open('data/shp/msa/%s/blockgroups.shp'%city, 'r', 'ESRI Shapefile') as source: for f in source: blocks[f['properties']['BKGPIDFP00']] = shape(f['geometry']) ## Compute adjacency list adjacency = {b:[] for b in blocks} for b0,b1 in itertools.permutations(blocks, 2): if blocks[b1].touches(blocks[b0]): adjacency[b0].append(b1) ## Save data with open('extr/adjacency_bg/msa/%s.csv'%city, 'w') as output: output.write("BLOCKGROUP FIP\tNEIGHBOURS FIP (list)\n") for b0 in adjacency: output.write("%s"%b0) for b1 in adjacency[b0]: output.write("\t%s"%b1) output.write("\n")
{ "repo_name": "rlouf/patterns-of-segregation", "path": "bin/data_prep/adjacency_blockgroups.py", "copies": "1", "size": "1311", "license": "bsd-3-clause", "hash": 8153133685147501000, "line_mean": 23.7358490566, "line_max": 93, "alpha_frac": 0.6178489703, "autogenerated": false, "ratio": 3.1214285714285714, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9139314143343921, "avg_score": 0.019992679676930164, "num_lines": 53 }
# Adjacency List Graph Class class ListGraph: # Constructor def __init__(self, nodes): self.data = {} for node in nodes: self.data[node] = [] # Add the vertex in the Graph def add_vertex(self, u, v): self.data[u].append(v) # Print graph def print_graph(self): print self.data # BFS def bfs(self, source, visited, in_degree): path = [] q = [source] visited[source] = 1 path.append(source) while len(q) > 0: v = q.pop(0) for i in xrange(len(self.data[v])): in_degree[self.data[v][i]] -= 1 if visited[self.data[v][i]] == 0 and in_degree[self.data[v][i]] == 0: q.append(self.data[v][i]) visited[self.data[v][i]] = 1 path.append(self.data[v][i]) return path # Find the connected group def find_group(self, source, visited, in_degree): return len(self.bfs(source, visited, in_degree)) def topologicalSortUtil(self, v, visited, stack): # Mark the current node as visited. visited[v] = True # Recur for all the vertices adjacent to this vertex if v in self.graph.keys(): for node, weight in self.graph[v]: if visited[node] == False: self.topologicalSortUtil(node, visited, stack) # Push current vertex to stack which stores topological sort stack.append(v) def shortestPath(self, s): visited = {} for node in nodes: visited[node] = 0 stack = [] # Call the recursive helper function to store Topological # Sort starting from source vertice for i in range(self.V): if visited[i] == False: self.topologicalSortUtil(s, visited, stack) # Initialize distances to all vertices as infinite and # distance to source as 0 dist = [float("Inf")] * (self.V) dist[s] = 0 # Process vertices in topological order while stack: # Get the next vertex from topological order i = stack.pop() # Update distances of all adjacent vertices for node, weight in self.graph[i]: if dist[node] > dist[i] + weight: dist[node] = dist[i] + weight # Print the calculated shortest distances for i in range(self.V): print ("%d" % dist[i]) if dist[i] != float("Inf") else "Inf", f = open('sample-input.txt') o = open('sample-output.txt', 'w') t = int(f.readline().strip()) n = f.readline() for i in xrange(1, t + 1): o.write("Case #{}: ".format(i)) nodes = set() edges = [] while True: n = f.readline().strip() if n == '': break x = [int(j) for j in n.split()] edges.append(x) nodes.add(x[0]) nodes.add(x[1]) AdjacencyMatrixGraph = ListGraph(nodes) visited = {} in_degree = {} for node in nodes: visited[node] = 0 in_degree[node] = 0 for edge in edges: AdjacencyMatrixGraph.add_vertex(edge[0], edge[1]) in_degree[edge[1]] += 1 ans = [] for node in nodes: if visited[node] == 0 and in_degree[node] == 0: ans.append(AdjacencyMatrixGraph.find_group(node, visited, in_degree)) print("\n") o.write("{}".format(max(ans))) o.write("\n")
{ "repo_name": "manishbisht/Competitive-Programming", "path": "Hiring Challenges/Google/Software Engineer University Graduate - Tokyo 2019/Round 1 - Online Challenge/Problem 2/Solution.py", "copies": "1", "size": "3479", "license": "mit", "hash": 8581143925717552000, "line_mean": 29.252173913, "line_max": 85, "alpha_frac": 0.5340615119, "autogenerated": false, "ratio": 3.744886975242196, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9774534431171504, "avg_score": 0.0008828111941382305, "num_lines": 115 }
"""Adjacency List""" from django.core import serializers from django.db import connection, models, transaction from django.utils.translation import ugettext_noop as _ from treebeard.exceptions import InvalidMoveToDescendant from treebeard.models import Node class AL_NodeManager(models.Manager): """Custom manager for nodes in an Adjacency List tree.""" def get_query_set(self): """Sets the custom queryset as the default.""" if self.model.node_order_by: order_by = ['parent'] + list(self.model.node_order_by) else: order_by = ['parent', 'sib_order'] return super(AL_NodeManager, self).get_query_set().order_by(*order_by) class AL_Node(Node): """Abstract model to create your own Adjacency List Trees.""" objects = AL_NodeManager() node_order_by = None @classmethod def add_root(cls, **kwargs): """Adds a root node to the tree.""" newobj = cls(**kwargs) newobj._cached_depth = 1 if not cls.node_order_by: try: max = cls.objects.filter(parent__isnull=True).order_by( 'sib_order').reverse()[0].sib_order except IndexError: max = 0 newobj.sib_order = max + 1 newobj.save() transaction.commit_unless_managed() return newobj @classmethod def get_root_nodes(cls): """:returns: A queryset containing the root nodes in the tree.""" return cls.objects.filter(parent__isnull=True) def get_depth(self, update=False): """ :returns: the depth (level) of the node Caches the result in the object itself to help in loops. :param update: Updates the cached value. """ if self.parent_id is None: return 1 try: if update: del self._cached_depth else: return self._cached_depth except AttributeError: pass depth = 0 node = self while node: node = node.parent depth += 1 self._cached_depth = depth return depth def get_children(self): """:returns: A queryset of all the node's children""" return self.__class__.objects.filter(parent=self) def get_parent(self, update=False): """:returns: the parent node of the current node object.""" return self.parent def get_ancestors(self): """ :returns: A *list* containing the current node object's ancestors, starting by the root node and descending to the parent. """ ancestors = [] node = self.parent while node: ancestors.insert(0, node) node = node.parent return ancestors def get_root(self): """:returns: the root node for the current node object.""" ancestors = self.get_ancestors() if ancestors: return ancestors[0] return self def is_descendant_of(self, node): """ :returns: ``True`` if the node if a descendant of another node given as an argument, else, returns ``False`` """ return self.pk in [obj.pk for obj in node.get_descendants()] @classmethod def dump_bulk(cls, parent=None, keep_ids=True): """Dumps a tree branch to a python data structure.""" serializable_cls = cls._get_serializable_model() if ( parent and serializable_cls != cls and parent.__class__ != serializable_cls ): parent = serializable_cls.objects.get(pk=parent.pk) # a list of nodes: not really a queryset, but it works objs = serializable_cls.get_tree(parent) ret, lnk = [], {} for node, pyobj in zip(objs, serializers.serialize('python', objs)): depth = node.get_depth() # django's serializer stores the attributes in 'fields' fields = pyobj['fields'] del fields['parent'] # non-sorted trees have this if 'sib_order' in fields: del fields['sib_order'] if 'id' in fields: del fields['id'] newobj = {'data': fields} if keep_ids: newobj['id'] = pyobj['pk'] if (not parent and depth == 1) or\ (parent and depth == parent.get_depth()): ret.append(newobj) else: parentobj = lnk[node.parent_id] if 'children' not in parentobj: parentobj['children'] = [] parentobj['children'].append(newobj) lnk[node.pk] = newobj return ret def add_child(self, **kwargs): """Adds a child to the node.""" newobj = self.__class__(**kwargs) try: newobj._cached_depth = self._cached_depth + 1 except AttributeError: pass if not self.__class__.node_order_by: try: max = self.__class__.objects.filter(parent=self).reverse( )[0].sib_order except IndexError: max = 0 newobj.sib_order = max + 1 newobj.parent = self newobj.save() transaction.commit_unless_managed() return newobj @classmethod def _get_tree_recursively(cls, results, parent, depth): if parent: nodes = parent.get_children() else: nodes = cls.get_root_nodes() for node in nodes: node._cached_depth = depth results.append(node) cls._get_tree_recursively(results, node, depth + 1) @classmethod def get_tree(cls, parent=None): """ :returns: A list of nodes ordered as DFS, including the parent. If no parent is given, the entire tree is returned. """ if parent: depth = parent.get_depth() + 1 results = [parent] else: depth = 1 results = [] cls._get_tree_recursively(results, parent, depth) return results def get_descendants(self): """ :returns: A *list* of all the node's descendants, doesn't include the node itself """ return self.__class__.get_tree(parent=self)[1:] def get_descendant_count(self): """:returns: the number of descendants of a nodee""" return len(self.get_descendants()) def get_siblings(self): """ :returns: A queryset of all the node's siblings, including the node itself. """ if self.parent: return self.__class__.objects.filter(parent=self.parent) return self.__class__.get_root_nodes() def add_sibling(self, pos=None, **kwargs): """Adds a new node as a sibling to the current node object.""" pos = self._prepare_pos_var_for_add_sibling(pos) newobj = self.__class__(**kwargs) if not self.node_order_by: newobj.sib_order = self.__class__._get_new_sibling_order(pos, self) newobj.parent_id = self.parent_id newobj.save() transaction.commit_unless_managed() return newobj @classmethod def _is_target_pos_the_last_sibling(cls, pos, target): return pos == 'last-sibling' or ( pos == 'right' and target == target.get_last_sibling()) @classmethod def _make_hole_in_db(cls, min, target_node): qset = cls.objects.filter(sib_order__gte=min) if target_node.is_root(): qset = qset.filter(parent__isnull=True) else: qset = qset.filter(parent=target_node.parent) qset.update(sib_order=models.F('sib_order') + 1) @classmethod def _make_hole_and_get_sibling_order(cls, pos, target_node): siblings = target_node.get_siblings() siblings = { 'left': siblings.filter(sib_order__gte=target_node.sib_order), 'right': siblings.filter(sib_order__gt=target_node.sib_order), 'first-sibling': siblings }[pos] sib_order = { 'left': target_node.sib_order, 'right': target_node.sib_order + 1, 'first-sibling': 1 }[pos] try: min = siblings.order_by('sib_order')[0].sib_order except IndexError: min = 0 if min: cls._make_hole_in_db(min, target_node) return sib_order @classmethod def _get_new_sibling_order(cls, pos, target_node): if cls._is_target_pos_the_last_sibling(pos, target_node): sib_order = target_node.get_last_sibling().sib_order + 1 else: sib_order = cls._make_hole_and_get_sibling_order(pos, target_node) return sib_order def move(self, target, pos=None): """ Moves the current node and all it's descendants to a new position relative to another node. """ pos = self._prepare_pos_var_for_move(pos) sib_order = None parent = None if pos in ('first-child', 'last-child', 'sorted-child'): # moving to a child if not target.is_leaf(): target = target.get_last_child() pos = {'first-child': 'first-sibling', 'last-child': 'last-sibling', 'sorted-child': 'sorted-sibling'}[pos] else: parent = target if pos == 'sorted-child': pos = 'sorted-sibling' else: pos = 'first-sibling' sib_order = 1 if target.is_descendant_of(self): raise InvalidMoveToDescendant( _("Can't move node to a descendant.")) if self == target and ( (pos == 'left') or (pos in ('right', 'last-sibling') and target == target.get_last_sibling()) or (pos == 'first-sibling' and target == target.get_first_sibling())): # special cases, not actually moving the node so no need to UPDATE return if pos == 'sorted-sibling': if parent: self.parent = parent else: self.parent = target.parent else: if sib_order: self.sib_order = sib_order else: self.sib_order = self.__class__._get_new_sibling_order(pos, target) if parent: self.parent = parent else: self.parent = target.parent self.save() transaction.commit_unless_managed() class Meta: """Abstract model.""" abstract = True
{ "repo_name": "suziesparkle/wagtail", "path": "wagtail/vendor/django-treebeard/treebeard/al_tree.py", "copies": "4", "size": "10972", "license": "bsd-3-clause", "hash": 1255182717581396200, "line_mean": 31.8502994012, "line_max": 78, "alpha_frac": 0.5328107911, "autogenerated": false, "ratio": 4.260970873786408, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6793781664886409, "avg_score": null, "num_lines": null }
"""Adjacency List""" from django.core import serializers from django.db import models from django.utils.translation import gettext_noop as _ from treebeard.exceptions import InvalidMoveToDescendant, NodeAlreadySaved from treebeard.models import Node def get_result_class(cls): """ For the given model class, determine what class we should use for the nodes returned by its tree methods (such as get_children). Usually this will be trivially the same as the initial model class, but there are special cases when model inheritance is in use: * If the model extends another via multi-table inheritance, we need to use whichever ancestor originally implemented the tree behaviour (i.e. the one which defines the 'parent' field). We can't use the subclass, because it's not guaranteed that the other nodes reachable from the current one will be instances of the same subclass. * If the model is a proxy model, the returned nodes should also use the proxy class. """ base_class = cls._meta.get_field('parent').model if cls._meta.proxy_for_model == base_class: return cls else: return base_class class AL_NodeManager(models.Manager): """Custom manager for nodes in an Adjacency List tree.""" def get_queryset(self): """Sets the custom queryset as the default.""" if self.model.node_order_by: order_by = ['parent'] + list(self.model.node_order_by) else: order_by = ['parent', 'sib_order'] return super().get_queryset().order_by(*order_by) class AL_Node(Node): """Abstract model to create your own Adjacency List Trees.""" objects = AL_NodeManager() node_order_by = None @classmethod def add_root(cls, **kwargs): """Adds a root node to the tree.""" if len(kwargs) == 1 and 'instance' in kwargs: # adding the passed (unsaved) instance to the tree newobj = kwargs['instance'] if not newobj._state.adding: raise NodeAlreadySaved("Attempted to add a tree node that is "\ "already in the database") else: newobj = cls(**kwargs) newobj._cached_depth = 1 if not cls.node_order_by: try: max = get_result_class(cls).objects.filter( parent__isnull=True).order_by( 'sib_order').reverse()[0].sib_order except IndexError: max = 0 newobj.sib_order = max + 1 newobj.save() return newobj @classmethod def get_root_nodes(cls): """:returns: A queryset containing the root nodes in the tree.""" return get_result_class(cls).objects.filter(parent__isnull=True) def get_depth(self, update=False): """ :returns: the depth (level) of the node Caches the result in the object itself to help in loops. :param update: Updates the cached value. """ if self.parent_id is None: return 1 try: if update: del self._cached_depth else: return self._cached_depth except AttributeError: pass depth = 0 node = self while node: node = node.parent depth += 1 self._cached_depth = depth return depth def get_children(self): """:returns: A queryset of all the node's children""" return get_result_class(self.__class__).objects.filter(parent=self) def get_parent(self, update=False): """:returns: the parent node of the current node object.""" if self._meta.proxy_for_model: # the current node is a proxy model; the returned parent # should be the same proxy model, so we need to explicitly # fetch it as an instance of that model rather than simply # following the 'parent' relation if self.parent_id is None: return None else: return self.__class__.objects.get(pk=self.parent_id) else: return self.parent def get_ancestors(self): """ :returns: A *list* containing the current node object's ancestors, starting by the root node and descending to the parent. """ ancestors = [] if self._meta.proxy_for_model: # the current node is a proxy model; our result set # should use the same proxy model, so we need to # explicitly fetch instances of that model # when following the 'parent' relation cls = self.__class__ node = self while node.parent_id: node = cls.objects.get(pk=node.parent_id) ancestors.insert(0, node) else: node = self.parent while node: ancestors.insert(0, node) node = node.parent return ancestors def get_root(self): """:returns: the root node for the current node object.""" ancestors = self.get_ancestors() if ancestors: return ancestors[0] return self def is_descendant_of(self, node): """ :returns: ``True`` if the node if a descendant of another node given as an argument, else, returns ``False`` """ return self.pk in [obj.pk for obj in node.get_descendants()] @classmethod def dump_bulk(cls, parent=None, keep_ids=True): """Dumps a tree branch to a python data structure.""" serializable_cls = cls._get_serializable_model() if ( parent and serializable_cls != cls and parent.__class__ != serializable_cls ): parent = serializable_cls.objects.get(pk=parent.pk) # a list of nodes: not really a queryset, but it works objs = serializable_cls.get_tree(parent) ret, lnk = [], {} pk_field = cls._meta.pk.attname for node, pyobj in zip(objs, serializers.serialize('python', objs)): depth = node.get_depth() # django's serializer stores the attributes in 'fields' fields = pyobj['fields'] del fields['parent'] # non-sorted trees have this if 'sib_order' in fields: del fields['sib_order'] if pk_field in fields: del fields[pk_field] newobj = {'data': fields} if keep_ids: newobj[pk_field] = pyobj['pk'] if (not parent and depth == 1) or\ (parent and depth == parent.get_depth()): ret.append(newobj) else: parentobj = lnk[node.parent_id] if 'children' not in parentobj: parentobj['children'] = [] parentobj['children'].append(newobj) lnk[node.pk] = newobj return ret def add_child(self, **kwargs): """Adds a child to the node.""" cls = get_result_class(self.__class__) if len(kwargs) == 1 and 'instance' in kwargs: # adding the passed (unsaved) instance to the tree newobj = kwargs['instance'] if not newobj._state.adding: raise NodeAlreadySaved("Attempted to add a tree node that is "\ "already in the database") else: newobj = cls(**kwargs) try: newobj._cached_depth = self._cached_depth + 1 except AttributeError: pass if not cls.node_order_by: try: max = cls.objects.filter(parent=self).reverse( )[0].sib_order except IndexError: max = 0 newobj.sib_order = max + 1 newobj.parent = self newobj.save() return newobj @classmethod def _get_tree_recursively(cls, results, parent, depth): if parent: nodes = parent.get_children() else: nodes = cls.get_root_nodes() for node in nodes: node._cached_depth = depth results.append(node) cls._get_tree_recursively(results, node, depth + 1) @classmethod def get_tree(cls, parent=None): """ :returns: A list of nodes ordered as DFS, including the parent. If no parent is given, the entire tree is returned. """ if parent: depth = parent.get_depth() + 1 results = [parent] else: depth = 1 results = [] cls._get_tree_recursively(results, parent, depth) return results def get_descendants(self): """ :returns: A *list* of all the node's descendants, doesn't include the node itself """ return self.__class__.get_tree(parent=self)[1:] def get_descendant_count(self): """:returns: the number of descendants of a nodee""" return len(self.get_descendants()) def get_siblings(self): """ :returns: A queryset of all the node's siblings, including the node itself. """ if self.parent: return get_result_class(self.__class__).objects.filter( parent=self.parent) return self.__class__.get_root_nodes() def add_sibling(self, pos=None, **kwargs): """Adds a new node as a sibling to the current node object.""" pos = self._prepare_pos_var_for_add_sibling(pos) if len(kwargs) == 1 and 'instance' in kwargs: # adding the passed (unsaved) instance to the tree newobj = kwargs['instance'] if not newobj._state.adding: raise NodeAlreadySaved("Attempted to add a tree node that is "\ "already in the database") else: # creating a new object newobj = get_result_class(self.__class__)(**kwargs) if not self.node_order_by: newobj.sib_order = self.__class__._get_new_sibling_order(pos, self) newobj.parent_id = self.parent_id newobj.save() return newobj @classmethod def _is_target_pos_the_last_sibling(cls, pos, target): return pos == 'last-sibling' or ( pos == 'right' and target == target.get_last_sibling()) @classmethod def _make_hole_in_db(cls, min, target_node): qset = get_result_class(cls).objects.filter(sib_order__gte=min) if target_node.is_root(): qset = qset.filter(parent__isnull=True) else: qset = qset.filter(parent=target_node.parent) qset.update(sib_order=models.F('sib_order') + 1) @classmethod def _make_hole_and_get_sibling_order(cls, pos, target_node): siblings = target_node.get_siblings() siblings = { 'left': siblings.filter(sib_order__gte=target_node.sib_order), 'right': siblings.filter(sib_order__gt=target_node.sib_order), 'first-sibling': siblings }[pos] sib_order = { 'left': target_node.sib_order, 'right': target_node.sib_order + 1, 'first-sibling': 1 }[pos] try: min = siblings.order_by('sib_order')[0].sib_order except IndexError: min = 0 if min: cls._make_hole_in_db(min, target_node) return sib_order @classmethod def _get_new_sibling_order(cls, pos, target_node): if cls._is_target_pos_the_last_sibling(pos, target_node): sib_order = target_node.get_last_sibling().sib_order + 1 else: sib_order = cls._make_hole_and_get_sibling_order(pos, target_node) return sib_order def move(self, target, pos=None): """ Moves the current node and all it's descendants to a new position relative to another node. """ pos = self._prepare_pos_var_for_move(pos) sib_order = None parent = None if pos in ('first-child', 'last-child', 'sorted-child'): # moving to a child if not target.is_leaf(): target = target.get_last_child() pos = {'first-child': 'first-sibling', 'last-child': 'last-sibling', 'sorted-child': 'sorted-sibling'}[pos] else: parent = target if pos == 'sorted-child': pos = 'sorted-sibling' else: pos = 'first-sibling' sib_order = 1 if target.is_descendant_of(self): raise InvalidMoveToDescendant( _("Can't move node to a descendant.")) if self == target and ( (pos == 'left') or (pos in ('right', 'last-sibling') and target == target.get_last_sibling()) or (pos == 'first-sibling' and target == target.get_first_sibling())): # special cases, not actually moving the node so no need to UPDATE return if pos == 'sorted-sibling': if parent: self.parent = parent else: self.parent = target.parent else: if sib_order: self.sib_order = sib_order else: self.sib_order = self.__class__._get_new_sibling_order(pos, target) if parent: self.parent = parent else: self.parent = target.parent self.save() class Meta: """Abstract model.""" abstract = True
{ "repo_name": "django-treebeard/django-treebeard", "path": "treebeard/al_tree.py", "copies": "2", "size": "13940", "license": "apache-2.0", "hash": 5023894341779963000, "line_mean": 33.4197530864, "line_max": 79, "alpha_frac": 0.543472023, "autogenerated": false, "ratio": 4.3251628917157925, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5868634914715792, "avg_score": null, "num_lines": null }
"Adjacency List" from django.core import serializers from django.db import models, transaction, connection from treebeard.models import Node from treebeard.exceptions import InvalidMoveToDescendant class AL_NodeManager(models.Manager): "Custom manager for nodes." def get_query_set(self): "Sets the custom queryset as the default." qset = super(AL_NodeManager, self).get_query_set() if self.model.node_order_by: order_by = ['parent'] + list(self.model.node_order_by) else: order_by = ['parent', 'sib_order'] return qset.order_by(*order_by) class AL_Node(Node): "Abstract model to create your own Adjacency List Trees." objects = AL_NodeManager() node_order_by = None @classmethod def add_root(cls, **kwargs): "Adds a root node to the tree." newobj = cls(**kwargs) newobj._cached_depth = 1 if not cls.node_order_by: try: max = cls.objects.filter(parent__isnull=True).order_by( 'sib_order').reverse()[0].sib_order except IndexError: max = 0 newobj.sib_order = max + 1 # saving the instance before returning it newobj.save() transaction.commit_unless_managed() return newobj @classmethod def get_root_nodes(cls): ":returns: A queryset containing the root nodes in the tree." return cls.objects.filter(parent__isnull=True) def get_depth(self, update=False): """ :returns: the depth (level) of the node Caches the result in the object itself to help in loops. :param update: Updates the cached value. """ if self.parent_id is None: return 1 try: if update: del self._cached_depth else: return self._cached_depth except AttributeError: pass depth = 0 node = self while node: node = node.parent depth += 1 self._cached_depth = depth return depth def get_children(self): ":returns: A queryset of all the node's children" return self.__class__.objects.filter(parent=self) def get_parent(self, update=False): ":returns: the parent node of the current node object." return self.parent def get_ancestors(self): """ :returns: A *list* containing the current node object's ancestors, starting by the root node and descending to the parent. """ ancestors = [] node = self.parent while node: ancestors.append(node) node = node.parent ancestors.reverse() return ancestors def get_root(self): ":returns: the root node for the current node object." ancestors = self.get_ancestors() if ancestors: return ancestors[0] return self def is_descendant_of(self, node): """ :returns: ``True`` if the node if a descendant of another node given as an argument, else, returns ``False`` """ return self.pk in [obj.pk for obj in node.get_descendants()] @classmethod def dump_bulk(cls, parent=None, keep_ids=True): "Dumps a tree branch to a python data structure." serializable_cls = cls._get_serializable_model() if parent and serializable_cls != cls and \ parent.__class__ != serializable_cls: parent = serializable_cls.objects.get(pk=parent.pk) # a list of nodes: not really a queryset, but it works objs = serializable_cls.get_tree(parent) ret, lnk = [], {} for node, pyobj in zip(objs, serializers.serialize('python', objs)): depth = node.get_depth() # django's serializer stores the attributes in 'fields' fields = pyobj['fields'] del fields['parent'] # non-sorted trees have this if 'sib_order' in fields: del fields['sib_order'] if 'id' in fields: del fields['id'] newobj = {'data': fields} if keep_ids: newobj['id'] = pyobj['pk'] if (not parent and depth == 1) or \ (parent and depth == parent.get_depth()): ret.append(newobj) else: parentobj = lnk[node.parent_id] if 'children' not in parentobj: parentobj['children'] = [] parentobj['children'].append(newobj) lnk[node.id] = newobj return ret def add_child(self, **kwargs): "Adds a child to the node." newobj = self.__class__(**kwargs) try: newobj._cached_depth = self._cached_depth + 1 except AttributeError: pass if not self.__class__.node_order_by: try: max = self.__class__.objects.filter(parent=self).reverse( )[0].sib_order except IndexError: max = 0 newobj.sib_order = max + 1 # saving the instance before returning it newobj.parent = self newobj.save() transaction.commit_unless_managed() return newobj @classmethod def _get_tree_recur(cls, ret, parent, depth): if parent: qset = cls.objects.filter(parent=parent) else: qset = cls.get_root_nodes() for node in qset: node._cached_depth = depth ret.append(node) cls._get_tree_recur(ret, node, depth + 1) @classmethod def get_tree(cls, parent=None): """ :returns: A list of nodes ordered as DFS, including the parent. If no parent is given, the entire tree is returned. """ if parent: depth = parent.get_depth() + 1 ret = [parent] else: depth = 1 ret = [] cls._get_tree_recur(ret, parent, depth) return ret def get_descendants(self): """ :returns: A *list* of all the node's descendants, doesn't include the node itself """ return self.__class__.get_tree(parent=self)[1:] def get_descendant_count(self): ":returns: the number of descendants of a nodee" return len(self.get_descendants()) def get_siblings(self): """ :returns: A queryset of all the node's siblings, including the node itself. """ if self.parent: return self.__class__.objects.filter(parent=self.parent) return self.__class__.get_root_nodes() def add_sibling(self, pos=None, **kwargs): "Adds a new node as a sibling to the current node object." pos = self._fix_add_sibling_opts(pos) stmts = [] # creating a new object newobj = self.__class__(**kwargs) if not self.node_order_by: newobj.sib_order = self.__class__._move_add_sibling_aux(pos, self, stmts) if self.parent_id: newobj.parent_id = self.parent_id cursor = connection.cursor() for sql, vals in stmts: cursor.execute(sql, vals) # saving the instance before returning it newobj.save() transaction.commit_unless_managed() return newobj @classmethod def _move_add_sibling_aux(cls, pos, target, stmts): """ helper that makes a hole between siblings for a new node (only for not sorted trees) """ sib_order = target.sib_order if pos == 'last-sibling' \ or (pos == 'right' and target == target.get_last_sibling()): sib_order = target.get_last_sibling().sib_order + 1 else: siblings = target.get_siblings() siblings = {'left': siblings.filter( sib_order__gte=target.sib_order), 'right': siblings.filter( sib_order__gt=target.sib_order), 'first-sibling': siblings}[pos] sib_order = {'left': sib_order, 'right': sib_order + 1, 'first-sibling': 1}[pos] try: min = siblings.order_by('sib_order')[0].sib_order except IndexError: min = 0 if min: sql = 'UPDATE %(table)s' \ ' SET sib_order=sib_order+1' \ ' WHERE sib_order >= %%s' \ ' AND ' % {'table': connection.ops.quote_name(cls._meta.db_table)} params = [min] if target.is_root(): sql += 'parent_id IS NULL' else: sql += 'parent_id=%s' params.append(target.parent_id) stmts.append((sql, params)) return sib_order def move(self, target, pos=None): """ Moves the current node and all it's descendants to a new position relative to another node. """ pos = self._fix_move_opts(pos) stmts = [] sib_order = None parent = None if pos in ('first-child', 'last-child', 'sorted-child'): # moving to a child if not target.is_leaf(): target = target.get_last_child() pos = {'first-child': 'first-sibling', 'last-child': 'last-sibling', 'sorted-child': 'sorted-sibling'}[pos] else: parent = target if pos == 'sorted-child': pos = 'sorted-sibling' else: pos = 'first-sibling' sib_order = 1 if target.is_descendant_of(self): raise InvalidMoveToDescendant("Can't move node to a descendant.") if self == target and ( (pos == 'left') or \ (pos in ('right', 'last-sibling') and \ target == target.get_last_sibling()) or \ (pos == 'first-sibling' and \ target == target.get_first_sibling())): # special cases, not actually moving the node so no need to UPDATE return if pos == 'sorted-sibling': # easy, just change the parent if parent: self.parent = parent else: self.parent = target.parent else: if sib_order: self.sib_order = sib_order else: self.sib_order = self.__class__._move_add_sibling_aux(pos, target, stmts) if parent: self.parent = parent else: self.parent = target.parent if stmts: cursor = connection.cursor() for sql, vals in stmts: cursor.execute(sql, vals) self.save() transaction.commit_unless_managed() class Meta: "Abstract model." abstract = True
{ "repo_name": "Ernsting/django-treebeard", "path": "treebeard/al_tree.py", "copies": "1", "size": "11366", "license": "apache-2.0", "hash": 3537656943557977600, "line_mean": 30.9269662921, "line_max": 78, "alpha_frac": 0.5146929439, "autogenerated": false, "ratio": 4.398606811145511, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5413299755045511, "avg_score": null, "num_lines": null }
"""Adjacency List""" from django.core import serializers from django.db import models, transaction from django.utils.translation import ugettext_noop as _ from treebeard.exceptions import InvalidMoveToDescendant, NodeAlreadySaved from treebeard.models import Node def get_result_class(cls): """ For the given model class, determine what class we should use for the nodes returned by its tree methods (such as get_children). Usually this will be trivially the same as the initial model class, but there are special cases when model inheritance is in use: * If the model extends another via multi-table inheritance, we need to use whichever ancestor originally implemented the tree behaviour (i.e. the one which defines the 'parent' field). We can't use the subclass, because it's not guaranteed that the other nodes reachable from the current one will be instances of the same subclass. * If the model is a proxy model, the returned nodes should also use the proxy class. """ base_class = cls._meta.get_field('parent').model if cls._meta.proxy_for_model == base_class: return cls else: return base_class class AL_NodeManager(models.Manager): """Custom manager for nodes in an Adjacency List tree.""" def get_queryset(self): """Sets the custom queryset as the default.""" if self.model.node_order_by: order_by = ['parent'] + list(self.model.node_order_by) else: order_by = ['parent', 'sib_order'] return super(AL_NodeManager, self).get_queryset().order_by(*order_by) class AL_Node(Node): """Abstract model to create your own Adjacency List Trees.""" objects = AL_NodeManager() node_order_by = None @classmethod def add_root(cls, **kwargs): """Adds a root node to the tree.""" if len(kwargs) == 1 and 'instance' in kwargs: # adding the passed (unsaved) instance to the tree newobj = kwargs['instance'] if newobj.pk: raise NodeAlreadySaved("Attempted to add a tree node that is "\ "already in the database") else: newobj = cls(**kwargs) newobj._cached_depth = 1 if not cls.node_order_by: try: max = get_result_class(cls).objects.filter( parent__isnull=True).order_by( 'sib_order').reverse()[0].sib_order except IndexError: max = 0 newobj.sib_order = max + 1 newobj.save() return newobj @classmethod def get_root_nodes(cls): """:returns: A queryset containing the root nodes in the tree.""" return get_result_class(cls).objects.filter(parent__isnull=True) def get_depth(self, update=False): """ :returns: the depth (level) of the node Caches the result in the object itself to help in loops. :param update: Updates the cached value. """ if self.parent_id is None: return 1 try: if update: del self._cached_depth else: return self._cached_depth except AttributeError: pass depth = 0 node = self while node: node = node.parent depth += 1 self._cached_depth = depth return depth def get_children(self): """:returns: A queryset of all the node's children""" return get_result_class(self.__class__).objects.filter(parent=self) def get_parent(self, update=False): """:returns: the parent node of the current node object.""" if self._meta.proxy_for_model: # the current node is a proxy model; the returned parent # should be the same proxy model, so we need to explicitly # fetch it as an instance of that model rather than simply # following the 'parent' relation if self.parent_id is None: return None else: return self.__class__.objects.get(pk=self.parent_id) else: return self.parent def get_ancestors(self): """ :returns: A *list* containing the current node object's ancestors, starting by the root node and descending to the parent. """ ancestors = [] if self._meta.proxy_for_model: # the current node is a proxy model; our result set # should use the same proxy model, so we need to # explicitly fetch instances of that model # when following the 'parent' relation cls = self.__class__ node = self while node.parent_id: node = cls.objects.get(pk=node.parent_id) ancestors.insert(0, node) else: node = self.parent while node: ancestors.insert(0, node) node = node.parent return ancestors def get_root(self): """:returns: the root node for the current node object.""" ancestors = self.get_ancestors() if ancestors: return ancestors[0] return self def is_descendant_of(self, node): """ :returns: ``True`` if the node if a descendant of another node given as an argument, else, returns ``False`` """ return self.pk in [obj.pk for obj in node.get_descendants()] @classmethod def dump_bulk(cls, parent=None, keep_ids=True): """Dumps a tree branch to a python data structure.""" serializable_cls = cls._get_serializable_model() if ( parent and serializable_cls != cls and parent.__class__ != serializable_cls ): parent = serializable_cls.objects.get(pk=parent.pk) # a list of nodes: not really a queryset, but it works objs = serializable_cls.get_tree(parent) ret, lnk = [], {} for node, pyobj in zip(objs, serializers.serialize('python', objs)): depth = node.get_depth() # django's serializer stores the attributes in 'fields' fields = pyobj['fields'] del fields['parent'] # non-sorted trees have this if 'sib_order' in fields: del fields['sib_order'] if 'id' in fields: del fields['id'] newobj = {'data': fields} if keep_ids: newobj['id'] = pyobj['pk'] if (not parent and depth == 1) or\ (parent and depth == parent.get_depth()): ret.append(newobj) else: parentobj = lnk[node.parent_id] if 'children' not in parentobj: parentobj['children'] = [] parentobj['children'].append(newobj) lnk[node.pk] = newobj return ret def add_child(self, **kwargs): """Adds a child to the node.""" cls = get_result_class(self.__class__) if len(kwargs) == 1 and 'instance' in kwargs: # adding the passed (unsaved) instance to the tree newobj = kwargs['instance'] if newobj.pk: raise NodeAlreadySaved("Attempted to add a tree node that is "\ "already in the database") else: newobj = cls(**kwargs) try: newobj._cached_depth = self._cached_depth + 1 except AttributeError: pass if not cls.node_order_by: try: max = cls.objects.filter(parent=self).reverse( )[0].sib_order except IndexError: max = 0 newobj.sib_order = max + 1 newobj.parent = self newobj.save() return newobj @classmethod def _get_tree_recursively(cls, results, parent, depth): if parent: nodes = parent.get_children() else: nodes = cls.get_root_nodes() for node in nodes: node._cached_depth = depth results.append(node) cls._get_tree_recursively(results, node, depth + 1) @classmethod def get_tree(cls, parent=None): """ :returns: A list of nodes ordered as DFS, including the parent. If no parent is given, the entire tree is returned. """ if parent: depth = parent.get_depth() + 1 results = [parent] else: depth = 1 results = [] cls._get_tree_recursively(results, parent, depth) return results def get_descendants(self): """ :returns: A *list* of all the node's descendants, doesn't include the node itself """ return self.__class__.get_tree(parent=self)[1:] def get_descendant_count(self): """:returns: the number of descendants of a nodee""" return len(self.get_descendants()) def get_siblings(self): """ :returns: A queryset of all the node's siblings, including the node itself. """ if self.parent: return get_result_class(self.__class__).objects.filter( parent=self.parent) return self.__class__.get_root_nodes() def add_sibling(self, pos=None, **kwargs): """Adds a new node as a sibling to the current node object.""" pos = self._prepare_pos_var_for_add_sibling(pos) if len(kwargs) == 1 and 'instance' in kwargs: # adding the passed (unsaved) instance to the tree newobj = kwargs['instance'] if newobj.pk: raise NodeAlreadySaved("Attempted to add a tree node that is "\ "already in the database") else: # creating a new object newobj = get_result_class(self.__class__)(**kwargs) if not self.node_order_by: newobj.sib_order = self.__class__._get_new_sibling_order(pos, self) newobj.parent_id = self.parent_id newobj.save() return newobj @classmethod def _is_target_pos_the_last_sibling(cls, pos, target): return pos == 'last-sibling' or ( pos == 'right' and target == target.get_last_sibling()) @classmethod def _make_hole_in_db(cls, min, target_node): qset = get_result_class(cls).objects.filter(sib_order__gte=min) if target_node.is_root(): qset = qset.filter(parent__isnull=True) else: qset = qset.filter(parent=target_node.parent) qset.update(sib_order=models.F('sib_order') + 1) @classmethod def _make_hole_and_get_sibling_order(cls, pos, target_node): siblings = target_node.get_siblings() siblings = { 'left': siblings.filter(sib_order__gte=target_node.sib_order), 'right': siblings.filter(sib_order__gt=target_node.sib_order), 'first-sibling': siblings }[pos] sib_order = { 'left': target_node.sib_order, 'right': target_node.sib_order + 1, 'first-sibling': 1 }[pos] try: min = siblings.order_by('sib_order')[0].sib_order except IndexError: min = 0 if min: cls._make_hole_in_db(min, target_node) return sib_order @classmethod def _get_new_sibling_order(cls, pos, target_node): if cls._is_target_pos_the_last_sibling(pos, target_node): sib_order = target_node.get_last_sibling().sib_order + 1 else: sib_order = cls._make_hole_and_get_sibling_order(pos, target_node) return sib_order def move(self, target, pos=None): """ Moves the current node and all it's descendants to a new position relative to another node. """ pos = self._prepare_pos_var_for_move(pos) sib_order = None parent = None if pos in ('first-child', 'last-child', 'sorted-child'): # moving to a child if not target.is_leaf(): target = target.get_last_child() pos = {'first-child': 'first-sibling', 'last-child': 'last-sibling', 'sorted-child': 'sorted-sibling'}[pos] else: parent = target if pos == 'sorted-child': pos = 'sorted-sibling' else: pos = 'first-sibling' sib_order = 1 if target.is_descendant_of(self): raise InvalidMoveToDescendant( _("Can't move node to a descendant.")) if self == target and ( (pos == 'left') or (pos in ('right', 'last-sibling') and target == target.get_last_sibling()) or (pos == 'first-sibling' and target == target.get_first_sibling())): # special cases, not actually moving the node so no need to UPDATE return if pos == 'sorted-sibling': if parent: self.parent = parent else: self.parent = target.parent else: if sib_order: self.sib_order = sib_order else: self.sib_order = self.__class__._get_new_sibling_order(pos, target) if parent: self.parent = parent else: self.parent = target.parent self.save() class Meta: """Abstract model.""" abstract = True
{ "repo_name": "Venturi/oldcms", "path": "env/lib/python2.7/site-packages/treebeard/al_tree.py", "copies": "8", "size": "13877", "license": "apache-2.0", "hash": 5444470989551735000, "line_mean": 33.349009901, "line_max": 79, "alpha_frac": 0.5426965482, "autogenerated": false, "ratio": 4.327096975366386, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0002508163050347588, "num_lines": 404 }
# Adjacency Matrix Graph Class class Graph: # Constructor def __init__(self, size): self.data = [] for i in xrange(size): temp = [] for j in xrange(size): temp.append(0) self.data.append(temp) # Add the vertex in the graph def add_vertex(self, u, v): self.data[u][v] = 1 # Print graph def print_graph(self): print self.data # BFS def bfs(self, source): path = [] q = [source] visited = [] for i in xrange(len(self.data)): visited.append(0) visited[source] = 1 path.append(source) while len(q) > 0: v = q.pop(0) for i in xrange(len(self.data[v])): if visited[i] == 0 and self.data[v][i] == 1: q.append(i) visited[i] = 1 path.append(i) return path AdjacencyMatrixGraph = Graph(8) AdjacencyMatrixGraph.print_graph() AdjacencyMatrixGraph.add_vertex(0, 1) AdjacencyMatrixGraph.add_vertex(0, 2) AdjacencyMatrixGraph.add_vertex(0, 3) AdjacencyMatrixGraph.add_vertex(1, 4) AdjacencyMatrixGraph.add_vertex(1, 5) AdjacencyMatrixGraph.add_vertex(2, 6) AdjacencyMatrixGraph.add_vertex(2, 7) AdjacencyMatrixGraph.add_vertex(3, 7) AdjacencyMatrixGraph.print_graph() print AdjacencyMatrixGraph.bfs(0) # Adjacency List Graph Class class ListGraph: # Constructor def __init__(self, nodes): self.data = {} for node in nodes: self.data[node] = [] # Add the vertex in the Graph def add_vertex(self, u, v): self.data[u].append(v) # Print graph def print_graph(self): print self.data # BFS def bfs(self, source, nodes): path = [] q = [source] visited = {} for node in nodes: visited[node] = 0 visited[source] = 1 path.append(source) while len(q) > 0: v = q.pop(0) for i in xrange(len(self.data[v])): if visited[self.data[v][i]] == 0: q.append(self.data[v][i]) visited[self.data[v][i]] = 1 path.append(self.data[v][i]) return path AdjacencyListGraph = ListGraph(range(8)) AdjacencyListGraph.print_graph() AdjacencyListGraph.add_vertex(0, 1) AdjacencyListGraph.add_vertex(0, 2) AdjacencyListGraph.add_vertex(0, 3) AdjacencyListGraph.add_vertex(1, 4) AdjacencyListGraph.add_vertex(1, 5) AdjacencyListGraph.add_vertex(2, 6) AdjacencyListGraph.add_vertex(2, 7) AdjacencyListGraph.add_vertex(3, 7) AdjacencyListGraph.print_graph() print AdjacencyListGraph.bfs(0, range(8))
{ "repo_name": "manishbisht/Competitive-Programming", "path": "Data Structures/06 Graph/02 Graph - BFS.py", "copies": "1", "size": "2698", "license": "mit", "hash": -417933013202690750, "line_mean": 26.824742268, "line_max": 60, "alpha_frac": 0.5804299481, "autogenerated": false, "ratio": 3.355721393034826, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44361513411348263, "avg_score": null, "num_lines": null }
# #Adjacency Matrix implementation by using dictionary # n=int(input()) # edges = [('a', 'b'), ('a', 'd'), ('a', 'c'),('a','e')] # from collections import defaultdict # # matrix = defaultdict(int) # for edge in edges: # matrix[edge] += 1 # # print(matrix) # # #Adjacency matrix using dictionary and groupby # from itertools import groupby # # edges = [(1, 2), (2, 3), (1, 3)] # # adj = {k: [v[1] for v in g] for k, g in groupby(sorted(edges), lambda e: e[0])} # # adj: {1: [2, 3], 2: [3]} #https://algocoding.wordpress.com/2014/08/25/form-the-adjacency-matrix-and-adjacency-lists-from-the-edges/ n=int(input()) e=int(input()) edge_u=list() edge_v=list() adjMatrix = [[0 for i in range(n)] for k in range(n)] for i in range(e): m,n=map(int,input().split()) edge_u.append(m) edge_v.append(n) #populate matrix for i in range(len(edge_u)): u = edge_u[i] v = edge_v[i] adjMatrix[u][v] = 1 print("Adjacency matrix: ") print(adjMatrix) #bettr print # def printMatrix(matrix): # for i in range(len(matrix)): # for k in range(len(matrix[0])): # print(matrix[i][k], " ", end='') # print('')
{ "repo_name": "saisankargochhayat/algo_quest", "path": "Misc/adjacency_matrix.py", "copies": "1", "size": "1154", "license": "apache-2.0", "hash": 608972017319890200, "line_mean": 26.4761904762, "line_max": 106, "alpha_frac": 0.5918544194, "autogenerated": false, "ratio": 2.734597156398104, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8757500691318911, "avg_score": 0.013790176895838582, "num_lines": 42 }
"""A django elastic-beanstalk setup module See: https://github.com/reparadocs/pls """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='pls', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version='0.0.5', description='A tool that allows easy setup of Django with Elastic Beanstalk', long_description=long_description, # The project's main homepage. url='https://github.com/reparadocs/pls', # Author details author='Rishab Hegde', author_email='reparadocs@gmail.com', # Choose your license license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2.7', ], # What does your project relate to? keywords='django development elastic-beanstalk', py_modules=["pls"], # List run-time dependencies here. These will be installed by pip when # your project is installed. For an analysis of "install_requires" vs pip's # requirements files see: # https://packaging.python.org/en/latest/requirements.html install_requires=['click','virtualenv','django','awsebcli'], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'pls=pls:main', ], }, )
{ "repo_name": "Reparadocs/pls", "path": "setup.py", "copies": "1", "size": "2545", "license": "mit", "hash": -8485239480705418000, "line_mean": 31.6282051282, "line_max": 81, "alpha_frac": 0.6711198428, "autogenerated": false, "ratio": 4.072, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.52431198428, "avg_score": null, "num_lines": null }
"""A Django E-Mail backend for Google App Engine.""" __author__ = "shakusa@google.com (Steve Hakusa)" import logging from django.conf import settings from django.core.mail.backends import base from django.utils import text from google.appengine.api import app_identity from google.appengine.api import mail class EmailBackend(base.BaseEmailBackend): """Django email backend for AppEngine's mail API.""" def send_messages(self, email_messages): """Sends one or more EmailMessage objects and returns the number sent. Args: email_messages: A list of django.core.mail.EmailMessage objects. Returns: An int indicating the number of successfully sent messages. """ num_sent = 0 for email in email_messages: if self._send(email): num_sent += 1 return num_sent def _send(self, email): """Send the message using the appengine mail API.""" try: ae_email = self._convert_message(email) ae_email.send() logging.debug("Sent mail %s to %s", ae_email.subject, ae_email.to) except (ValueError, mail.Error) as err: logging.warn(err) if not self.fail_silently: raise return False return True def _convert_message(self, django_email): """Convert a Django EmailMessage to an App Engine EmailMessage.""" django_email.reply_to = django_email.extra_headers.get("Reply-To", None) html_body = None if django_email.alternatives: if django_email.alternatives[0]: html_body = django_email.alternatives[0][0] logging.info("Subject without formatting: %s", django_email.subject) from_email = "admin@%s.appspotmail.com" % app_identity.get_application_id() ae_kwargs = { "sender": from_email, "subject": self._format_subject(settings.EMAIL_SUBJECT_PREFIX + django_email.subject), "to": django_email.to, } if django_email.reply_to: ae_kwargs["reply_to"] = django_email.reply_to if django_email.cc: ae_kwargs["cc"] = django_email.cc if django_email.bcc: ae_kwargs["bcc"] = django_email.bcc ae_kwargs["body"] = django_email.body if html_body: ae_kwargs["html"] = html_body ae_email = mail.EmailMessage(**ae_kwargs) ae_email.check_initialized() return ae_email def _format_subject(self, subject): """Escape CR and LF characters, and limit length. RFC 2822"s hard limit is 998 characters per line. So, minus "Subject: " the actual subject must be no longer than 989 characters. Args: subject: A string containing the original subject. Returns: A string containing the formatted subject. """ formatted_subject = subject.replace("\n", "\\n").replace("\r", "\\r") truncator = text.Truncator(formatted_subject) formatted_subject = truncator.chars(985) return formatted_subject
{ "repo_name": "pentestfail/CAPCollector", "path": "appengine_mail.py", "copies": "3", "size": "2903", "license": "bsd-3-clause", "hash": 2824354041326210600, "line_mean": 28.3232323232, "line_max": 79, "alpha_frac": 0.6600068894, "autogenerated": false, "ratio": 3.7848761408083442, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5944883030208344, "avg_score": null, "num_lines": null }
# A Django model field for use with Python 3 enums. # # Works with any enum whose values are integers. Subclasses the IntegerField # to store the enum as integers in the database. Serializes to dotted names # (e.g. AnimalType.Cat in the example below). # # A decorator is needed on Python enums in order to make them work with # Django migrations, which require a deconstruct() method on the enum # members. # # Example: # # import enum # from enum3field import EnumField, django_enum # # @django_enum # class AnimalType(enum.Enum): # Cat = 1 # Dog = 2 # Turtle = 3 # # class Animal(models.Model): # animalType = EnumField(AnimalType) # ##################################################### import enum from django.core import exceptions from django.db import models from django.utils.functional import cached_property def django_enum(enum): # In order to make the enumeration serializable for migrations, instance members # must have a deconstruct method. But the enum class should not have a deconstruct # method or else the serialization of the enum itself as the first argument to # EnumField will fail. To achieve this, we added a deconstruct() method to the # members after the enum members have been created. def make_deconstructor(member): def deconstruct(): return (enum.__module__ + '.' + enum.__name__, [member.value], {}) return deconstruct for member in enum: member.deconstruct = make_deconstructor(member) return enum class EnumField(models.IntegerField, metaclass=models.SubfieldBase): """A Django model field for use with Python 3 enums. Usage: fieldname = EnumField(enum_class, ....)""" def __init__(self, enum_class, *args, **kwargs): if not issubclass(enum_class, enum.Enum): raise ValueError("enum_class argument must be a Python 3 enum.") self.enum_class = enum.unique(enum_class) # ensure unique members to prevent accidental database corruption kwargs['choices'] = [(item, item.name) for item in self.enum_class] super(EnumField, self).__init__(*args, **kwargs) description = "A value of the %(enum_class) enumeration." def get_prep_value(self, value): # Normally value is an enumeration value. But when running `manage.py migrate` # we may get a serialized value. Use to_python to coerce to an enumeration # member as best as possible. value = self.to_python(value) if value is not None: # Validate if not isinstance(value, self.enum_class): raise exceptions.ValidationError( "'%s' must be a member of %s." % (value, self.enum_class), code='invalid', params={'value': value}, ) # enum member => member.value (should be an integer) value = value.value # integer => database return super(EnumField, self).get_prep_value(value) def to_python(self, value): # handle None and values of the correct type already if value is None or isinstance(value, self.enum_class): return value # When serializing to create a fixture, the default serialization # is to "EnumName.MemberName". Handle that. prefix = self.enum_class.__name__ + "." if isinstance(value, str) and value.startswith(prefix): try: return self.enum_class[value[len(prefix):]] except KeyError: raise exceptions.ValidationError( "'%s' does not refer to a member of %s." % (value, self.enum_class), code='invalid', params={'value': value}, ) # We may also get string versions of the integer form from forms, # and integers when querying a database. try: return self.enum_class(int(value)) except ValueError: raise exceptions.ValidationError( "'%s' must be an integer value of %s." % (value, self.enum_class), code='invalid', params={'value': value}, ) def deconstruct(self): # Override the positional arguments info to include the enumeration class. tup = super(EnumField, self).deconstruct() return (tup[0], tup[1], [self.enum_class], tup[3]) @cached_property def validators(self): # IntegerField validators will not work on enum instances, and we don't need # any validation beyond conversion to an enum instance (which is performed # elsewhere), so we don't need to do any validation. return []
{ "repo_name": "if-then-fund/django-enum3field", "path": "enum3field/__init__.py", "copies": "1", "size": "4360", "license": "cc0-1.0", "hash": -471398493456415360, "line_mean": 35.3333333333, "line_max": 111, "alpha_frac": 0.6722477064, "autogenerated": false, "ratio": 4.052044609665428, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.019547809231578818, "num_lines": 120 }
adj_list_moo = {4: [5], 6: [5], 5: [7], 7: []} def dfs_topsort(graph): # recursive dfs with L = [] # additional list for order of nodes color = { u : "white" for u in graph } found_cycle = [False] for u in graph: if color[u] == "white": dfs_visit(graph, u, color, L, found_cycle) if found_cycle[0]: break if found_cycle[0]: # if there is a cycle, L = [] # then return an empty list L.reverse() # reverse the list return L # L contains the topological sort def dfs_visit(graph, u, color, L, found_cycle): if found_cycle[0]: return color[u] = "gray" for v in graph[u]: if color[v] == "gray": found_cycle[0] = True return if color[v] == "white": dfs_visit(graph, v, color, L, found_cycle) color[u] = "black" # when we're done with u, L.append(u) # add u to list (reverse it later!) def has_hamiltonian(adj_list): graph_sorted = dfs_topsort(adj_list) print(graph_sorted) for i in range(0, len(graph_sorted) - 1): cur_node = graph_sorted[i] next_node = graph_sorted[i + 1] if next_node not in adj_list[cur_node]: return False return True print(has_hamiltonian(adj_list_moo))
{ "repo_name": "ammiranda/CS325", "path": "week5/code/has_hamiltonian.py", "copies": "1", "size": "1411", "license": "mit", "hash": 8127567241440127000, "line_mean": 31.0681818182, "line_max": 68, "alpha_frac": 0.5102763997, "autogenerated": false, "ratio": 3.3595238095238096, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.436980020922381, "avg_score": null, "num_lines": null }
"""adjusting key length Revision ID: 956a063c52b3 Revises: f0fbf6129e13 Create Date: 2016-05-11 17:28:32.407340 """ # revision identifiers, used by Alembic. revision = '956a063c52b3' down_revision = 'f0fbf6129e13' from alembic import op import sqlalchemy as sa def upgrade(): with op.batch_alter_table('clusters', schema=None) as batch_op: batch_op.alter_column('broker_endpoint', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) batch_op.alter_column('broker_host', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) batch_op.alter_column('coordinator_endpoint', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) batch_op.alter_column('coordinator_host', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) with op.batch_alter_table('columns', schema=None) as batch_op: batch_op.alter_column('column_name', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) with op.batch_alter_table('datasources', schema=None) as batch_op: batch_op.alter_column('datasource_name', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) with op.batch_alter_table('table_columns', schema=None) as batch_op: batch_op.alter_column('column_name', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) with op.batch_alter_table('tables', schema=None) as batch_op: batch_op.alter_column('schema', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) def downgrade(): with op.batch_alter_table('tables', schema=None) as batch_op: batch_op.alter_column('schema', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) with op.batch_alter_table('table_columns', schema=None) as batch_op: batch_op.alter_column('column_name', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) with op.batch_alter_table('datasources', schema=None) as batch_op: batch_op.alter_column('datasource_name', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) with op.batch_alter_table('columns', schema=None) as batch_op: batch_op.alter_column('column_name', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) with op.batch_alter_table('clusters', schema=None) as batch_op: batch_op.alter_column('coordinator_host', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) batch_op.alter_column('coordinator_endpoint', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) batch_op.alter_column('broker_host', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) batch_op.alter_column('broker_endpoint', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True)
{ "repo_name": "SingTel-DataCo/incubator-superset", "path": "superset/migrations/versions/956a063c52b3_adjusting_key_length.py", "copies": "17", "size": "4649", "license": "apache-2.0", "hash": 5642841171418842000, "line_mean": 44.5784313725, "line_max": 72, "alpha_frac": 0.5020434502, "autogenerated": false, "ratio": 4.522373540856031, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
#============================ adjust path ===================================== import sys import os if __name__ == "__main__": here = sys.path[0] sys.path.insert(0, os.path.join(here, '..')) #============================ imports ========================================= from SmartMeshSDK import ApiException from SmartMeshSDK.ApiDefinition.IpMgrDefinition import IpMgrDefinition from SmartMeshSDK.ApiDefinition.IpMoteDefinition import IpMoteDefinition from SmartMeshSDK.ApiDefinition.HartMgrDefinition import HartMgrDefinition from SmartMeshSDK.ApiDefinition.HartMoteDefinition import HartMoteDefinition #============================ templates ======================================= TMPL_CLASSDEF = '''\'\'\' This module was generated automatically. Do not edit directly. \'\'\' import collections from SmartMeshSDK import ApiException from {MODULE_NAME} import {BASE_CLASS_NAME} ## # \\addtogroup {GEN_CLASS_NAME} # \\{{ # class {GEN_CLASS_NAME}({BASE_CLASS_NAME}): \'\'\' \\brief {BRIEF_DESCRIPTION} \'\'\' ''' TMPL_DEF = ''' ## # The named tuple returned by the {CMD_NAME}() function. # {TUPLE_COMMENT} # Tuple_{CMD_NAME} = collections.namedtuple("Tuple_{CMD_NAME}", {TUPLE_PARAMS}) ## # {DESCR} # {CMD_COMMENT} # # \\returns The response to the command, formatted as a #Tuple_{CMD_NAME} named tuple. # def {CMD_NAME}(self, {CMD_PARMS}) : res = {BASE_CLASS_NAME}.send(self, {NAMES}, {{{PARAMS_DICT}}}) return {CLASS_NAME}.Tuple_{CMD_NAME}(**res) ''' TMPL_DEF_LIST = ''' ## # The named tuple returned by the {CMD_NAME}() function. # {TUPLE_COMMENT} # Tuple_{CMD_NAME} = collections.namedtuple("Tuple_{CMD_NAME}", {TUPLE_PARAMS}) ## # {DESCR} # {CMD_COMMENT} # # \\returns The response to the command, formatted as a list of #Tuple_{CMD_NAME} named tuple. # def {CMD_NAME}(self, {CMD_PARMS}) : res = {BASE_CLASS_NAME}.send(self, {NAMES}, {{{PARAMS_DICT}}}) tupleList = [] for r in res : tupleList.append({CLASS_NAME}.Tuple_{CMD_NAME}(**r)) return tupleList ''' TMPL_DEF_NOTUPLE = ''' ## # {DESCR} # {CMD_COMMENT} # # \\returns The response to the command. # def {CMD_NAME}(self, {CMD_PARMS}) : res = {BASE_CLASS_NAME}.send(self, {NAMES}, {{{PARAMS_DICT}}}) return res ''' TMPL_NOTIF = ''' ## # \\brief {NOTIF_NAME_UP} notification. # # {DESCR} # {NOTIF_COMMENT} # {NOTIF_NAME_UP} = "{NOTIF_NAME}" notifTupleTable[{NOTIF_NAME_UP}] = Tuple_{NOTIF_NAME} = collections.namedtuple("Tuple_{NOTIF_NAME}", {NOTIF_PARAMS}) ''' TMPL_NOTIF_NOTUPLE = ''' ## # \\brief Notification {NOTIF_NAME_UP} # # {DESCR} # {NOTIF_NAME_UP} = "{NOTIF_NAME}" notifTupleTable[{NOTIF_NAME_UP}] = None ''' TMPL_GETNOTIFICATION = ''' ## # \\brief Get a notification from the notification queue, and returns # it properly formatted. # # \\exception NotificationError if unknown notification. # def getNotification(self, timeoutSec=-1) : temp = self.getNotificationInternal(timeoutSec) if not temp: return temp (ids, param) = temp try : if {CLASS_NAME}.notifTupleTable[ids[-1]] : return (ids[-1], {CLASS_NAME}.notifTupleTable[ids[-1]](**param)) else : return (ids[-1], None) except KeyError : raise ApiException.NotificationError(ids, param) ''' START_LOCATION_COMMENT = ''' # \param numFrames 1-byte field formatted as an integer.<br/> # There is no restriction on the value of this field. # \param mobileMote 8-byte field formatted as hex.<br/> # There is no restriction on the value of this field. # \param fixedMotes list of 8-byte fields formatted as hex.<br/> # There is no restriction on the value of this field. # ''' START_LOCATION_PAYLOAD = ''' payload = [] for fm in fixedMotes : payload += fm res = {BASE_CLASS_NAME}.send(self, ['startLocation'], {{"numFrames" : numFrames, "mobileMote" : mobileMote, "fixedMotes" : payload}}) ''' TMPL_ENDCLASSDEF = ''' ## # end of {GEN_CLASS_NAME} # \\}} # ''' def printStartLocation(names, respFieldsName, reqFieldsName, CMD_NAME, CMD_PARMS, DESCR, TUPLE_PARAMS, NAMES, PARAMS_DICT, BASE_CLASS_NAME, CLASS_NAME, TUPLE_COMMENT, CMD_COMMENT) : s = TMPL_DEF.format(CMD_NAME = CMD_NAME, CMD_PARMS = CMD_PARMS, DESCR = DESCR, TUPLE_PARAMS = TUPLE_PARAMS, NAMES = NAMES, PARAMS_DICT = PARAMS_DICT, BASE_CLASS_NAME = BASE_CLASS_NAME, CLASS_NAME = CLASS_NAME, TUPLE_COMMENT = TUPLE_COMMENT, CMD_COMMENT = '***') lines = s.split('\n') res = [] for l in lines : if l == '***' : res += [START_LOCATION_COMMENT[1:]] elif l.find('send(self') >= 0: res += [START_LOCATION_PAYLOAD[1:].format(BASE_CLASS_NAME=BASE_CLASS_NAME)] else : res += [l + '\n'] return ''.join(res) RADIOTEST_TX_COMMENT = ''' # \param type 1-byte field formatted as an integer.<br/> # Type of transmission test: 0=packet, 1=continuous modulation (CM), 2=continuous wave (CW) # \param mask 2-bytes field formatted as an integer.<br/> # Mask of channels(0-15) enabled for test. # \param txPower 1-byte field formatted as an sign integer.<br/> # Transmit power, in dB. Valid values are 0 (power amplifier off) and 8 (power amplifier on). # \param numRepeats 2-byte field formatted as an integer.<br/> # Number of times to repeat the packet sequence (0=do not stop). Applies only to packet transmission tests. # \param tests list of pair of integer.<br/> # Sequence definitions (up to 10) specifies the length (bytes) and after-packet delay (usec) for each packets ''' RADIOTEST_TX_PAYLOAD = ''' d = {{"type" : type, "mask" : mask, "numRepeats" : numRepeats, "txPower" : txPower, "numPackets" : len(tests)}} for i in xrange(10) : if i < len(tests) : l, g = tests[i] else : l, g = (0, 0) d["pkSize" + str(i+1)] = l d["gap" + str(i+1)] = g res = {BASE_CLASS_NAME}.send(self, ['radiotestTx'], d) ''' def printRsadioTestTx(names, respFieldsName, reqFieldsName, CMD_NAME, CMD_PARMS, DESCR, TUPLE_PARAMS, NAMES, PARAMS_DICT, BASE_CLASS_NAME, CLASS_NAME, TUPLE_COMMENT, CMD_COMMENT) : s = TMPL_DEF.format(CMD_NAME = CMD_NAME, CMD_PARMS = CMD_PARMS, DESCR = DESCR, TUPLE_PARAMS = TUPLE_PARAMS, NAMES = NAMES, PARAMS_DICT = PARAMS_DICT, BASE_CLASS_NAME = BASE_CLASS_NAME, CLASS_NAME = CLASS_NAME, TUPLE_COMMENT = TUPLE_COMMENT, CMD_COMMENT = '***') lines = s.split('\n') res = [] for l in lines : if l == '***' : res += [RADIOTEST_TX_COMMENT[1:]] elif l.find('def dn_radioTestTx') >= 0 : res += ' def dn_radioTestTx(self, type, mask, txPower, numRepeats, tests) :\n' elif l.find('send(self') >= 0: res += [RADIOTEST_TX_PAYLOAD[1:].format(BASE_CLASS_NAME=BASE_CLASS_NAME)] else : res += [l + '\n'] return ''.join(res) ''' Dictionary of commands with special processing: {'cmdName' : [requestFields, responseFields, generator]} def generator(names, respFieldsName, reqFieldsName, CMD_NAME, CMD_PARMS, DESCR, TUPLE_PARAMS, NAMES, PARAMS_DICT, BASE_CLASS_NAME, CLASS_NAME, TUPLE_COMMENT, CMD_COMMENT) : return strings ''' specialCmd = { 'dn_startLocation' : [ ['numFrames', 'mobileMote', 'fixedMotes'], ['RC', 'callbackId'], printStartLocation ], 'dn_radioTestTx' : [ ['type', 'mask', 'numRepeats', 'txPower', 'numPackets', 'pkSize1', 'gap1', 'pkSize2', 'gap2', 'pkSize3', 'gap3', 'pkSize4', 'gap4', 'pkSize5', 'gap5', 'pkSize6', 'gap6', 'pkSize7', 'gap7', 'pkSize8', 'gap8', 'pkSize9', 'gap9', 'pkSize10', 'gap10'], ['RC'], printRsadioTestTx ] } class GenApiConnectors(object): #======================== public ========================================== def __init__(self, apiDefName, myClassName, baseClassName, baseModuleName, outputFileName = None, briefDescription = '', apiDefClass=None): if apiDefName: apiDefClass = globals()[apiDefName] self.apiDef = apiDefClass() self.myClassName = myClassName self.baseClassName = baseClassName self.baseModuleName = baseModuleName self.briefDescription = briefDescription if outputFileName: self.outFile = open(outputFileName, "wt") else: self.outFile = sys.stdout def gen(self): s = TMPL_CLASSDEF.format(MODULE_NAME = self.baseModuleName, BASE_CLASS_NAME = self.baseClassName, GEN_CLASS_NAME = self.myClassName, BRIEF_DESCRIPTION = self.briefDescription) self.outFile.write(s) self.outFile.write('\n #======================== commands ========================================\n') self.genCmd() self.outFile.write('\n #======================== notifications ===================================\n') self.genNotif() s = TMPL_ENDCLASSDEF.format(GEN_CLASS_NAME = self.myClassName) self.outFile.write(s) self.genFinish() #======================== private ========================================= #===== commands def genCmd(self): cmdNames = self.apiDef.getNames(self.apiDef.COMMAND) for name in cmdNames : self.genOneCmd([name], [], []) def genOneCmd(self, names, respFieldsName, reqFieldsName): # get request fields r = self.apiDef.getRequestFieldNames(names) reqFieldsName += [n for n in r if n not in self.apiDef.RESERVED] # get response fields try: r = self.apiDef.getResponseFieldNames(self.apiDef.COMMAND, names) respFieldsName += [n for n in r if n not in self.apiDef.RESERVED] except ApiException.CommandError : # means that this function has no response fields, which is OK pass if self.apiDef.hasSubcommands(self.apiDef.COMMAND, names): subcmdsName = self.apiDef.getNames(self.apiDef.COMMAND, names) for sn in subcmdsName : self.genOneCmd(names+[sn], respFieldsName[:], reqFieldsName[:]) else: cmdName = 'dn_' cmdName += '_'.join([n for n in names]) cmdParams = ', '.join([p for p in reqFieldsName]) paramsDict = ', '.join(['"{0}" : {1}'.format(p, p) for p in reqFieldsName]) descr = self.apiDef.getDescription(self.apiDef.COMMAND, names).replace('\n', '\n # ') cmdComment = ''.join([self.getCmdComments(names, p) for p in reqFieldsName])[:-1] if not cmdComment: cmdComment = ' # ' tupleComment = ''.join([self.getCmdTupleComments(names, p) for p in respFieldsName])[:-1] if cmdName in specialCmd and specialCmd[cmdName][0] == reqFieldsName and specialCmd[cmdName][1] == respFieldsName : s = specialCmd[cmdName][2](names, respFieldsName, reqFieldsName, CMD_NAME = cmdName, CMD_PARMS = cmdParams, DESCR = descr, TUPLE_PARAMS = respFieldsName, NAMES = names, PARAMS_DICT = paramsDict, BASE_CLASS_NAME = self.baseClassName, CLASS_NAME = self.myClassName, TUPLE_COMMENT = tupleComment, CMD_COMMENT = cmdComment) else : if respFieldsName : cmd_metadata = self.apiDef.getDefinition(self.apiDef.COMMAND, names) if ('isResponseArray' in cmd_metadata) : s = TMPL_DEF_LIST.format(CMD_NAME = cmdName, CMD_PARMS = cmdParams, DESCR = descr, TUPLE_PARAMS = respFieldsName, NAMES = names, PARAMS_DICT = paramsDict, BASE_CLASS_NAME = self.baseClassName, CLASS_NAME = self.myClassName, TUPLE_COMMENT = tupleComment, CMD_COMMENT = cmdComment) else : s = TMPL_DEF.format(CMD_NAME = cmdName, CMD_PARMS = cmdParams, DESCR = descr, TUPLE_PARAMS = respFieldsName, NAMES = names, PARAMS_DICT = paramsDict, BASE_CLASS_NAME = self.baseClassName, CLASS_NAME = self.myClassName, TUPLE_COMMENT = tupleComment, CMD_COMMENT = cmdComment) else : s = TMPL_DEF_NOTUPLE.format(CMD_NAME = cmdName, CMD_PARMS = cmdParams, DESCR = descr, NAMES = names, PARAMS_DICT = paramsDict, BASE_CLASS_NAME = self.baseClassName, CMD_COMMENT = cmdComment) self.outFile.write(s) #===== notifications def genNotif(self): # write header output = [] output += [' \n'] output += [' ##\n'] output += [' # Dictionary of all notification tuples.\n'] output += [' #\n'] output += [' notifTupleTable = {}\n'] output += [' '] self.outFile.write(''.join(output)) # generate all notifications notifIds = self.apiDef.getIds(self.apiDef.NOTIFICATION) for notifId in notifIds : notifName = self.apiDef.idToName(self.apiDef.NOTIFICATION, notifId) self.genOneNotif([notifName], []) s = TMPL_GETNOTIFICATION.format(BASE_CLASS_NAME=self.baseClassName, CLASS_NAME=self.myClassName) self.outFile.write(s) def genOneNotif(self, names, fieldNames) : try : f = self.apiDef.getResponseFieldNames(self.apiDef.NOTIFICATION, names) if not f : raise KeyError fieldNames += [n for n in f if n not in self.apiDef.RESERVED] except (NameError, KeyError, ApiException.CommandError) : pass try : subcmdsName = self.apiDef.getNames(self.apiDef.NOTIFICATION, names) for sn in subcmdsName : self.genOneNotif(names + [sn], fieldNames[:]) except ApiException.CommandError : notifName = names[-1] descr = self.apiDef.getDescription(self.apiDef.NOTIFICATION, names).replace('\n', '\n # ') if fieldNames: tupleName = "Tuple_"+notifName notifComment = ' # Formatted as a {0} named tuple.'.format(tupleName) notifComment += ' It contains the following fields:\n' notifComment += ''.join([self.getNotifComments(names,tupleName,fieldName) for fieldName in fieldNames])[:-1] if not notifComment: notifComment = ' # ' s = TMPL_NOTIF.format(NOTIF_NAME = notifName, NOTIF_NAME_UP = notifName.upper(), NOTIF_PARAMS = fieldNames, DESCR = descr, NOTIF_COMMENT = notifComment) else : s = TMPL_NOTIF_NOTUPLE.format(NOTIF_NAME = notifName, NOTIF_NAME_UP = notifName.upper(), DESCR = descr) self.outFile.write(s) #===== end def genFinish(self): if self.outFile != sys.stdout : self.outFile.close() #======================== helpers ========================================= def getCmdTupleComments(self, names, param): format = self.apiDef.getResponseFieldFormat(self.apiDef.COMMAND, names, param) length = self.apiDef.getResponseFieldLength(self.apiDef.COMMAND, names, param) options = self.apiDef.getResponseFieldOptions(self.apiDef.COMMAND, names, param) s = ' # - <tt>{NAME}</tt>: {LEN}-byte field formatted as a {FMT}.<br/>\n'.format(NAME=param, LEN=length, FMT=format) s += self.getValidationComment(options) return s def getCmdComments(self, names, param): format = self.apiDef.getRequestFieldFormat(names, param) length = self.apiDef.getRequestFieldLength(names, param) options = self.apiDef.getRequestFieldOptions(names, param) s = ' # \param {NAME} {LEN}-byte field formatted as a {FMT}.<br/>\n'.format(NAME=param, LEN=length, FMT=format) s += self.getValidationComment(options) return s def getNotifComments(self, names, tupleName, fieldName): format = self.apiDef.getResponseFieldFormat(self.apiDef.NOTIFICATION, names, fieldName) length = self.apiDef.getResponseFieldLength(self.apiDef.NOTIFICATION, names, fieldName) options = self.apiDef.getResponseFieldOptions(self.apiDef.NOTIFICATION, names, fieldName) s = ' # - <tt>{NAME}</tt> {LEN}-byte field formatted as a {FMT}.<br/>\n'.format(NAME=fieldName, LEN=length, FMT=format) s += self.getValidationComment(options) return s def getValidationComment(self, options): if not options.validOptions: return ' # There is no restriction on the value of this field.\n' s = ' # This field can only take one of the following values:\n' for i in range(len(options.validOptions)): s += ' # - {0}: {1}\n'.format(options.validOptions[i], options.optionDescs[i]) return s def genFile(srcFileName, dstFileName, comment): if isinstance(srcFileName, str): apiDefClass = None apiDefName = os.path.splitext(os.path.basename(srcFileName))[0] else: apiDefClass = srcFileName apiDefName = None baseName = os.path.splitext(os.path.basename(dstFileName))[0] gen = GenApiConnectors(apiDefName=apiDefName, apiDefClass=apiDefClass, myClassName=baseName, baseClassName=baseName + "Internal", baseModuleName=baseName + "Internal", outputFileName=dstFileName, briefDescription=comment) gen.gen() def main() : if len(sys.argv) < 3: print "Usage: GenApiConnectors <apiDefinitionFile> <resultFile> [<comment>]" return 1 comment = '' if len(sys.argv) > 3: comment = sys.argv[3] genFile(sys.argv[1], sys.argv[2], comment) if __name__ == '__main__': main()
{ "repo_name": "twatteyne/dustlink_academy", "path": "SmartMeshSDK/GenApiConnectors.py", "copies": "3", "size": "22517", "license": "bsd-3-clause", "hash": -7359305635251569000, "line_mean": 42.4122287968, "line_max": 143, "alpha_frac": 0.4727983302, "autogenerated": false, "ratio": 4.244486333647503, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.02900681053561051, "num_lines": 507 }
"""Adjusts in tasks Revision ID: 2232f498d42e Revises: d469ee22a37d Create Date: 2019-02-13 10:35:29.598613 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '2232f498d42e' down_revision = 'd469ee22a37d' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('task_group', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=200), nullable=False), sa.Column('type', sa.Enum('SERVICE', 'PIPELINE', 'TEMPLATE', name='TaskGroupTypeEnumType'), nullable=False), sa.Column('color', sa.String(length=200), nullable=True), sa.PrimaryKeyConstraint('id') ) op.add_column('flow', sa.Column('environment', sa.Enum('DESIGN', 'DEPLOYMENT', name='DiagramEnvironmentEnumType'), nullable=False)) op.add_column('task', sa.Column('environment', sa.Enum('DESIGN', 'DEPLOYMENT', name='DiagramEnvironmentEnumType'), nullable=False)) op.add_column('workflow', sa.Column('deployment_enabled', sa.Boolean(), nullable=False)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('workflow', 'deployment_enabled') op.drop_column('task', 'environment') op.drop_column('flow', 'environment') op.drop_table('task_group') # ### end Alembic commands ###
{ "repo_name": "eubr-bigsea/tahiti", "path": "migrations/versions/2232f498d42e_adjusts_in_tasks.py", "copies": "1", "size": "1434", "license": "apache-2.0", "hash": -723856806736452600, "line_mean": 34.85, "line_max": 135, "alpha_frac": 0.6882845188, "autogenerated": false, "ratio": 3.430622009569378, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46189065283693775, "avg_score": null, "num_lines": null }
"""Adjust some old Python 2 idioms to their modern counterparts. * Change some type comparisons to isinstance() calls: type(x) == T -> isinstance(x, T) type(x) is T -> isinstance(x, T) type(x) != T -> not isinstance(x, T) type(x) is not T -> not isinstance(x, T) * Change "while 1:" into "while True:". * Change both v = list(EXPR) v.sort() foo(v) and the more general v = EXPR v.sort() foo(v) into v = sorted(EXPR) foo(v) """ # Author: Jacques Frechet, Collin Winter # Local imports from .. import fixer_base from ..fixer_util import Call, Comma, Name, Node, BlankLine, syms CMP = "(n='!=' | '==' | 'is' | n=comp_op< 'is' 'not' >)" TYPE = "power< 'type' trailer< '(' x=any ')' > >" class FixIdioms(fixer_base.BaseFix): explicit = True # The user must ask for this fixer PATTERN = r""" isinstance=comparison< %s %s T=any > | isinstance=comparison< T=any %s %s > | while_stmt< 'while' while='1' ':' any+ > | sorted=any< any* simple_stmt< expr_stmt< id1=any '=' power< list='list' trailer< '(' (not arglist<any+>) any ')' > > > '\n' > sort= simple_stmt< power< id2=any trailer< '.' 'sort' > trailer< '(' ')' > > '\n' > next=any* > | sorted=any< any* simple_stmt< expr_stmt< id1=any '=' expr=any > '\n' > sort= simple_stmt< power< id2=any trailer< '.' 'sort' > trailer< '(' ')' > > '\n' > next=any* > """ % (TYPE, CMP, CMP, TYPE) def match(self, node): r = super(FixIdioms, self).match(node) # If we've matched one of the sort/sorted subpatterns above, we # want to reject matches where the initial assignment and the # subsequent .sort() call involve different identifiers. if r and "sorted" in r: if r["id1"] == r["id2"]: return r return None return r def transform(self, node, results): if "isinstance" in results: return self.transform_isinstance(node, results) elif "while" in results: return self.transform_while(node, results) elif "sorted" in results: return self.transform_sort(node, results) else: raise RuntimeError("Invalid match") def transform_isinstance(self, node, results): x = results["x"].clone() # The thing inside of type() T = results["T"].clone() # The type being compared against x.prefix = u"" T.prefix = u" " test = Call(Name(u"isinstance"), [x, Comma(), T]) if "n" in results: test.prefix = u" " test = Node(syms.not_test, [Name(u"not"), test]) test.prefix = node.prefix return test def transform_while(self, node, results): one = results["while"] one.replace(Name(u"True", prefix=one.prefix)) def transform_sort(self, node, results): sort_stmt = results["sort"] next_stmt = results["next"] list_call = results.get("list") simple_expr = results.get("expr") if list_call: list_call.replace(Name(u"sorted", prefix=list_call.prefix)) elif simple_expr: new = simple_expr.clone() new.prefix = u"" simple_expr.replace(Call(Name(u"sorted"), [new], prefix=simple_expr.prefix)) else: raise RuntimeError("should not have reached here") sort_stmt.remove() btwn = sort_stmt.prefix # Keep any prefix lines between the sort_stmt and the list_call and # shove them right after the sorted() call. if u"\n" in btwn: if next_stmt: # The new prefix should be everything from the sort_stmt's # prefix up to the last newline, then the old prefix after a new # line. prefix_lines = (btwn.rpartition(u"\n")[0], next_stmt[0].prefix) next_stmt[0].prefix = u"\n".join(prefix_lines) else: assert list_call.parent assert list_call.next_sibling is None # Put a blank line after list_call and set its prefix. end_line = BlankLine() list_call.parent.append_child(end_line) assert list_call.next_sibling is end_line # The new prefix should be everything up to the first new line # of sort_stmt's prefix. end_line.prefix = btwn.rpartition(u"\n")[0]
{ "repo_name": "fkolacek/FIT-VUT", "path": "bp-revok/python/lib/python2.7/lib2to3/fixes/fix_idioms.py", "copies": "7", "size": "4890", "license": "apache-2.0", "hash": 1741605827814763000, "line_mean": 30.9607843137, "line_max": 88, "alpha_frac": 0.5124744376, "autogenerated": false, "ratio": 3.887122416534181, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0006525809455540101, "num_lines": 153 }
""" Adjusts sept 2020 Revision ID: 6a299689ea75 Revises: 86699b2e6672 Create Date: 2020-09-02 15:26:43.422785 """ from alembic import context from alembic import op from sqlalchemy import String, Integer, Text from sqlalchemy.orm import sessionmaker from sqlalchemy.sql import table, column import sqlalchemy as sa import json from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '6a299689ea75' down_revision = '86699b2e6672' branch_labels = None depends_on = None BASE_FORM_ID = 152 BASE_FORM_FIELD_ID = 578 BASE_PORT_ID = 324 DATA_SOURCE = 139 ALL_OPS = [DATA_SOURCE] def _insert_operation(): tb = table( 'operation', column('id', Integer), column('slug', String), column('enabled', String), column('type', String), column('icon', String), column('css_class', String), ) rows = [ (DATA_SOURCE, 'data-source', 1, 'SHORTCUT', ' ', None), ] rows = [dict(list(zip([c.name for c in tb.columns], row))) for row in rows] op.bulk_insert(tb, rows) def _insert_operation_translation(): tb = table( 'operation_translation', column('id', Integer), column('locale', String), column('name', String), column('description', String), ) rows = [ (DATA_SOURCE, 'en', 'Data source', 'Reads a data source.'), (DATA_SOURCE, 'pt', 'Fonte de dados', 'Lê uma fonte de dados.'), ] rows = [dict(list(zip([c.name for c in tb.columns], row))) for row in rows] op.bulk_insert(tb, rows) def _insert_operation_platform(): tb = table( 'operation_platform', column('operation_id', Integer), column('platform_id', Integer)) rows = [(op_id, 1) for op_id in ALL_OPS] rows = [dict(list(zip([c.name for c in tb.columns], row))) for row in rows] op.bulk_insert(tb, rows) def _insert_operation_port(): tb = table( 'operation_port', column('id', Integer), column('type', String), column('tags', String), column('operation_id', Integer), column('order', Integer), column('multiplicity', String), column('slug', String)) new_id = BASE_PORT_ID rows = [] for op_id in ALL_OPS: new_id += 1 rows.append([new_id, 'OUTPUT', None, op_id, 1, 'MANY', 'output data']) # new_id += 1 # rows.append([new_id, 'INPUT', None, op_id, 1, 'ONE', 'input data']) rows = [dict(list(zip([c.name for c in tb.columns], row))) for row in rows] op.bulk_insert(tb, rows) def _insert_operation_port_translation(): tb = table( 'operation_port_translation', column('id', Integer), column('locale', String), column('name', String), column('description', String), ) new_id = BASE_PORT_ID data = [] for op_id in ALL_OPS: new_id += 1 data.append([new_id, 'en', 'output data', 'Output data']) data.append([new_id, 'pt', 'dados de saída', 'Dados de saída']) # new_id += 1 # data.append([new_id, 'en', 'input data', 'Input data']) # data.append([new_id, 'pt', 'dados de entrada', 'Dados de entrada']) rows = [dict(list(zip([c.name for c in tb.columns], row))) for row in data] op.bulk_insert(tb, rows) def _insert_operation_port_interface_operation_port(): tb = table( 'operation_port_interface_operation_port', column('operation_port_id', Integer), column('operation_port_interface_id', Integer)) columns = [c.name for c in tb.columns] base_id_port = BASE_PORT_ID new_id = base_id_port data = [] for op_id in ALL_OPS: new_id += 1 data.append([new_id, 1]) # new_id += 1 # data.append([new_id, 1]) rows = [dict(list(zip(columns, cat))) for cat in data] op.bulk_insert(tb, rows) def _insert_operation_category_operation(): tb = table( 'operation_category_operation', column('operation_id', Integer), column('operation_category_id', Integer)) columns = [c.name for c in tb.columns] data = [] for op_id in ALL_OPS: data.append([op_id, 1]) rows = [dict(list(zip(columns, cat))) for cat in data] op.bulk_insert(tb, rows) def _insert_operation_form(): tb = table( 'operation_form', column('id', Integer), column('enabled', Integer), column('order', Integer), column('category', String), ) columns = [c.name for c in tb.columns] form_id = BASE_FORM_ID + 1 data = [] for op_id in ALL_OPS: data.append([form_id, 1, 1, 'execution']) form_id += 1 rows = [dict(list(zip(columns, row))) for row in data] op.bulk_insert(tb, rows) def _insert_operation_operation_form(): tb = table( 'operation_operation_form', column('operation_id', Integer), column('operation_form_id', Integer)) columns = [c.name for c in tb.columns] form_id = BASE_FORM_ID + 1 data = [] for op_id in ALL_OPS: data.append([op_id, 41]) # appearance data.append([op_id, form_id]) form_id += 1 rows = [dict(list(zip(columns, row))) for row in data] op.bulk_insert(tb, rows) def _insert_operation_form_translation(): tb = table( 'operation_form_translation', column('id', Integer), column('locale', String), column('name', String) ) columns = [c.name for c in tb.columns] form_id = BASE_FORM_ID + 1 data = [] for op_id in ALL_OPS: data.append([form_id, 'en', 'Execution']) data.append([form_id, 'pt', 'Execução']) form_id += 1 rows = [dict(list(zip(columns, row))) for row in data] op.bulk_insert(tb, rows) def _insert_operation_form_field(): tb = table( 'operation_form_field', column('id', Integer), column('name', String), column('type', String), column('required', Integer), column('order', Integer), column('default', Text), column('suggested_widget', String), column('values_url', String), column('values', String), column('scope', String), column('enable_conditions', String), column('form_id', Integer), column('editable', Integer), ) JOIN_TYPES = [ {"en": "Inner join", "key": "inner", "value": "Inner join", "pt": "Inner join"}, {"en": "Left outer join", "key": "left_outer", "value": "Left outer join", "pt": "Left outer join"}, {"en": "Right outer join", "key": "right_outer", "value": "Right outer join", "pt": "Right outer join"} ] data = [ # DATA SOURCE [BASE_FORM_ID + 1, 'data_source', 'INTEGER', 1, 0, None, 'lookup', '`${LIMONERO_URL}/datasources?uiw=1&simple=true&list=true&enabled=1`', None, 'EXECUTION', None, BASE_FORM_ID + 1, 0], # [571, 'join', 'TEXT', 0, 2, None, 'join-editor', None, None, 'EXECUTION', None, # BASE_FORM_ID + 1], # [572, 'join_type', 'TEXT', 0, 3, 'inner', 'dropdown', None, json.dumps(JOIN_TYPES), 'EXECUTION', None, # BASE_FORM_ID + 1], # [573, 'left_alias', 'TEXT', 0, 2, None, 'text', None, None, 'EXECUTION', None, # BASE_FORM_ID + 1], # [574, 'right_alias', 'TEXT', 0, 2, None, 'text', None, None, 'EXECUTION', None, # BASE_FORM_ID + 1], ] columns = [c.name for c in tb.columns] rows = [dict(list(zip(columns, row))) for row in data] op.bulk_insert(tb, rows) def _insert_operation_form_field_translation(): tb = table( 'operation_form_field_translation', column('id', Integer), column('locale', String), column('label', String), column('help', String), ) columns = [c.name for c in tb.columns] data = [ # Data Source [BASE_FORM_ID + 1, 'en', 'Data source', 'Data source.'], [BASE_FORM_ID + 1, 'pt', 'Fonte de dados', 'Fonte de dados.'] ] rows = [dict(list(zip(columns, row))) for row in data] op.bulk_insert(tb, rows) all_commands = [ ( "ALTER TABLE operation MODIFY COLUMN `type` enum('ACTION','SHUFFLE','TRANSFORMATION','VISUALIZATION', 'SHORTCUT') COLLATE utf8_unicode_ci NOT NULL", "ALTER TABLE operation MODIFY COLUMN `type` enum('ACTION','SHUFFLE','TRANSFORMATION','VISUALIZATION') COLLATE utf8_unicode_ci NOT NULL" ), ( "ALTER TABLE operation_form_field ADD COLUMN editable TINYINT(1) NOT NULL DEFAULT 1", "ALTER TABLE operation_form_field DROP COLUMN editable", ), (_insert_operation, 'DELETE FROM operation WHERE id BETWEEN {s} AND {e}'.format(s=DATA_SOURCE, e=DATA_SOURCE)), (_insert_operation_translation, 'DELETE FROM operation_translation WHERE id BETWEEN {s} AND {e}'.format(s=DATA_SOURCE, e=DATA_SOURCE)), (_insert_operation_port, 'DELETE FROM operation_port ' 'WHERE operation_id BETWEEN {s} AND {e}'.format(s=DATA_SOURCE, e=DATA_SOURCE)), (_insert_operation_port_translation, 'DELETE FROM operation_port_translation WHERE id IN ' '(SELECT id FROM operation_port ' ' WHERE operation_id BETWEEN {s} AND {e})'.format(s=DATA_SOURCE, e=DATA_SOURCE)), (_insert_operation_port_interface_operation_port, 'DELETE FROM operation_port_interface_operation_port ' 'WHERE operation_port_id IN (SELECT id FROM operation_port ' 'WHERE operation_id BETWEEN {s} AND {e})'.format(s=DATA_SOURCE, e=DATA_SOURCE)), (_insert_operation_category_operation, 'DELETE FROM operation_category_operation ' 'WHERE operation_id BETWEEN {s} AND {e}'.format(s=DATA_SOURCE, e=DATA_SOURCE)), (_insert_operation_platform, 'DELETE FROM operation_platform ' 'WHERE operation_id BETWEEN {s} AND {e}'.format(s=DATA_SOURCE, e=DATA_SOURCE)), (_insert_operation_form, 'DELETE FROM operation_form WHERE id BETWEEN {s} AND {e}'.format( s=BASE_FORM_ID + 1, e=BASE_FORM_ID + 1 + len(ALL_OPS))), (_insert_operation_operation_form, 'DELETE FROM operation_operation_form ' 'WHERE operation_id BETWEEN {s} AND {e} '.format( s=DATA_SOURCE, e=DATA_SOURCE)), (_insert_operation_form_translation, 'DELETE FROM operation_form_translation WHERE id BETWEEN {s} AND {e}'.format( s=BASE_FORM_ID + 1 , e=BASE_FORM_ID + 1 + len(ALL_OPS))), (_insert_operation_form_field, """DELETE FROM operation_form_field WHERE form_id BETWEEN {s} AND {e} """.format( s=BASE_FORM_ID + 1, e=BASE_FORM_ID + 1 + len(ALL_OPS))), (_insert_operation_form_field_translation, 'DELETE FROM operation_form_field_translation WHERE id IN (' + 'SELECT id FROM operation_form_field WHERE form_id BETWEEN {s} AND {e})'.format( s=BASE_FORM_ID + 1, e=BASE_FORM_ID + 1 + len(ALL_OPS))), ] def upgrade(): ctx = context.get_context() session = sessionmaker(bind=ctx.bind)() connection = session.connection() try: for cmd in all_commands: if isinstance(cmd[0], str): connection.execute(cmd[0]) elif isinstance(cmd[0], list): for row in cmd[0]: connection.execute(row) else: cmd[0]() except: session.rollback() raise session.commit() def downgrade(): ctx = context.get_context() session = sessionmaker(bind=ctx.bind)() connection = session.connection() try: connection.execute('SET FOREIGN_KEY_CHECKS=0;') for cmd in reversed(all_commands): if isinstance(cmd[1], str): connection.execute(cmd[1]) elif isinstance(cmd[1], list): for row in cmd[1]: connection.execute(row) else: cmd[1]() connection.execute('SET FOREIGN_KEY_CHECKS=1;') except: session.rollback() raise session.commit()
{ "repo_name": "eubr-bigsea/tahiti", "path": "migrations/versions/6a299689ea75_adjusts_sept_2020.py", "copies": "1", "size": "12195", "license": "apache-2.0", "hash": -8236711353135911000, "line_mean": 30.6623376623, "line_max": 157, "alpha_frac": 0.578342904, "autogenerated": false, "ratio": 3.4948394495412844, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9539725670487218, "avg_score": 0.00669133661081328, "num_lines": 385 }
""" Adjust the existing subscriptions to cover debit order charges. Argument is the month for which we need to populate the fields Usage: adjust-subscriptions year month [--run] """ import sys, time from pprint import pprint from datetime import datetime from sqlalchemy import select, create_engine, and_ from authsys_common.model import members, subscriptions, pending_transactions from authsys_common.scripts import get_config, get_db_url from authsys_common.queries import day_start_end, add_month from debit_orders import _tstamp if len(sys.argv) not in (3, 4): print(__doc__) sys.exit(1) dry_run = True if len(sys.argv) == 4: if sys.argv[3] != '--run': print(__doc__) sys.exit(1) dry_run = False year = int(sys.argv[1]) month = int(sys.argv[2]) conf = get_config() eng = create_engine(get_db_url()) con = eng.connect() action_date = datetime(year, month, 1, 0, 0) day_start = _tstamp(action_date) day_end = _tstamp(action_date.replace(hour=23, minute=59, second=59)) for member_id, name, sub_type, charge_day in list(con.execute(select([members.c.id, members.c.name, members.c.subscription_type, members.c.debit_order_charge_day]).where( members.c.member_type == 'recurring'))): pending = list(con.execute(select([pending_transactions.c.id]).where( and_(pending_transactions.c.member_id == member_id, pending_transactions.c.timestamp > day_start)))) if len(pending) > 0: print("Skipping %s, pending charges" % name) continue subs = list(con.execute(select([subscriptions.c.start_timestamp, subscriptions.c.end_timestamp]).where( and_(subscriptions.c.member_id == member_id, and_(subscriptions.c.end_timestamp < day_end + 59*60, subscriptions.c.end_timestamp >= day_start))))) assert len(subs) == 1, (subs, name) extra_subs = list(con.execute(select([subscriptions.c.end_timestamp]).where( and_(subscriptions.c.end_timestamp > day_end + 59*60, subscriptions.c.member_id == member_id)))) if len(extra_subs) > 0: print("Skipping %s, more subscriptions" % name) continue start_timestamp = subs[0][1] end_timestamp = _tstamp(add_month(action_date).replace(day=1, hour=23, second=0, minute=0) ) print("Adding subscription from %s to %s for %s" % (datetime.fromtimestamp(start_timestamp), datetime.fromtimestamp(end_timestamp), name)) if not dry_run: con.execute(subscriptions.insert().values({ 'member_id': member_id, 'type': sub_type, 'start_timestamp': start_timestamp, 'end_timestamp': end_timestamp, 'renewal_id': 0 })) price = conf.get('price', sub_type) charge_day = action_date.replace(day=charge_day, hour=1, minute=0, second=0) #if charge_day.date() == action_date.date(): # continue print("Adding charge of %s for %s on %s" % (price, name, charge_day)) if not dry_run: con.execute(pending_transactions.insert().values({ 'member_id': member_id, 'timestamp': _tstamp(charge_day), 'creation_timestamp': int(time.time()), 'price': price, 'type': sub_type, 'description': 'monthly charge', }))
{ "repo_name": "bloc11/authsys-brain", "path": "adjust-subscriptions.py", "copies": "1", "size": "3339", "license": "mit", "hash": -5045402815300611000, "line_mean": 39.7195121951, "line_max": 130, "alpha_frac": 0.632524708, "autogenerated": false, "ratio": 3.5221518987341773, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4654676606734177, "avg_score": null, "num_lines": null }
"""adl - Arkiv for dansk litteratur. Usage: dasem.adl get-author-data [options] Options: --debug Debug messages. -h --help Help message --oe=encoding Output encoding [default: utf-8] -o --output=<file> Output filename, default output to stdout --verbose Verbose messages. Description: adl is Arkiv for dansk litteratur, a Danish digital archive with old literature. An example of a URL for download of the raw text to a complete work is: http://adl.dk/adl_pub/pg/cv/AsciiPgVaerk2.xsql?p_udg_id=50&p_vaerk_id=554 which is the novel "Phantasterne". The following is "Bispen paa Boerglum og hans Fraende": http://adl.dk/adl_pub/pg/cv/AsciiPgVaerk2.xsql?p_udg_id=97&p_vaerk_id=9138 Examples: $ python -m dasem.adl get-author-data | head -n 3 | cut -f1-3 -d, ,author,author_label 0,http://www.wikidata.org/entity/Q439370,Herman Bang 1,http://www.wikidata.org/entity/Q347482,Hans Egede Schack """ from __future__ import absolute_import, division, print_function import os from os import write from .wikidata import query_to_dataframe WIKIDATA_AUTHOR_QUERY = """ select * where { ?author wdt:P31 wd:Q5 . ?author wdt:P973 ?url . filter strstarts(lcase(str(?url)), 'http://adl.dk') optional { ?author wdt:P21 ?gender . ?gender rdfs:label ?gender_label . filter (lang(?gender_label) = 'da') } ?author rdfs:label ?author_label . filter (lang(?author_label) = 'da') } order by ?url """ def get_author_data(): """Return ADL author data from Wikidata. Returns ------- df : pandas.DataFrame Dataframe with author data, including name and gender. """ df = query_to_dataframe(WIKIDATA_AUTHOR_QUERY) return df def main(): """Handle command-line interface.""" from docopt import docopt arguments = docopt(__doc__) if arguments['--output']: output_filename = arguments['--output'] output_file = os.open(output_filename, os.O_RDWR | os.O_CREAT) else: # stdout output_file = 1 output_encoding = arguments['--oe'] if arguments['get-author-data']: df = get_author_data() write(output_file, df.to_csv(encoding=output_encoding)) if __name__ == '__main__': main()
{ "repo_name": "fnielsen/dasem", "path": "dasem/adl.py", "copies": "1", "size": "2272", "license": "apache-2.0", "hash": -7603259900445800000, "line_mean": 23.967032967, "line_max": 76, "alpha_frac": 0.6518485915, "autogenerated": false, "ratio": 3.037433155080214, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4189281746580214, "avg_score": null, "num_lines": null }
"""Admin API""" import arrow from purepage.ext import r, db, abort class Admin: """ 后台管理 $shared: user: id?str: 用户ID role?str: 角色 email?email&optional: 邮箱 github?url&optional: Github地址 avatar?url&default="http://purepage.org/static/avatar-default.png": 头像 date_create?datetime&optional: 创建时间 date_modify?datetime&optional: 修改时间 timestamp?int&optional: 安全时间戳 lastlogin_date?datetime&optional: 最近登录时间 lastlogin_ip?ipv4&optional: 最近登录IP lastlogin_ua?str&optional: 最近登录设备UserAgent """ # noqa def put(self, id, role, email): """ 修改帐号信息 $input: id?str: 用户ID role?str: 角色 email?email: 邮箱 $output: @message """ if role == "root": abort(403, "PermissionDeny", "不能设为root帐号") db.run( r.table("user").get(id).update({ "role": role, "email": email, "date_modify": arrow.utcnow().datetime, "timestamp": arrow.utcnow().timestamp }) ) return {"message": "OK"} def get(self, account): """ 查找帐号 $input: account?str: 用户名或邮箱 $output: @user $error: 404.NotFound: 用户不存在 """ user = db.run(r.table("user").get(account)) if not user: user = db.first(r.table("user").get_all(account, index="email")) if not user: abort(404, "NotFound", "用户不存在") return user def get_list(self, page, per_page): """ 查看所有用户 $input: @pagging $output: - @user """ return db.pagging(r.table("user"), page, per_page) def delete(self, id): """ 删除帐号 $input: id?str: ID $output: @message """ user = db.run(r.table("user").get(id)) if user and user["role"] == "root": abort(403, "PermissionDeny", "root帐号无法删除") db.run(r.table("user").get(id).delete()) return {"message": "OK"}
{ "repo_name": "guyskk/kkblog", "path": "api/purepage/views/admin.py", "copies": "2", "size": "2393", "license": "mit", "hash": 7295870566679592000, "line_mean": 24.5697674419, "line_max": 82, "alpha_frac": 0.4820372897, "autogenerated": false, "ratio": 3.224340175953079, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4706377465653079, "avg_score": null, "num_lines": null }
"""Admin API.""" from django import http from django.contrib.contenttypes.models import ContentType from django.utils.translation import ugettext as _ from django_filters import rest_framework as dj_filters from drf_spectacular.utils import extend_schema, extend_schema_view from rest_framework import filters, renderers, status, viewsets from rest_framework.decorators import action from rest_framework.exceptions import ParseError from rest_framework.permissions import DjangoModelPermissions, IsAuthenticated from rest_framework.response import Response from modoboa.core import models as core_models from modoboa.core import sms_backends from modoboa.lib import renderers as lib_renderers from modoboa.lib import viewsets as lib_viewsets from ... import lib, models from . import serializers @extend_schema_view( retrieve=extend_schema( description="Retrieve a particular domain", summary="Retrieve a particular domain" ), list=extend_schema( description="Retrieve a list of domains", summary="Retrieve a list of domains" ), create=extend_schema( description="Create a new domain", summary="Create a new domain" ) ) class DomainViewSet(lib_viewsets.RevisionModelMixin, viewsets.ModelViewSet): """Domain viewset.""" permission_classes = [IsAuthenticated, DjangoModelPermissions, ] serializer_class = serializers.DomainSerializer def get_queryset(self): """Filter queryset based on current user.""" return models.Domain.objects.get_for_admin(self.request.user) def perform_destroy(self, instance): """Add custom args to delete call.""" instance.delete(self.request.user) class DomainAliasFilterSet(dj_filters.FilterSet): """Custom FilterSet for DomainAlias.""" domain = dj_filters.CharFilter(field_name="target__name") class Meta: model = models.DomainAlias fields = ["domain"] class DomainAliasViewSet(lib_viewsets.RevisionModelMixin, lib_viewsets.ExpandableModelViewSet): """ViewSet for DomainAlias.""" filter_backends = (dj_filters.DjangoFilterBackend, ) filterset_class = DomainAliasFilterSet permission_classes = [IsAuthenticated, DjangoModelPermissions, ] renderer_classes = (renderers.JSONRenderer, lib_renderers.CSVRenderer) serializer_expanded_fields = ["target"] serializer_class = serializers.DomainAliasSerializer def get_queryset(self): """Filter queryset based on current user.""" return models.DomainAlias.objects.get_for_admin(self.request.user) def get_renderer_context(self): context = super().get_renderer_context() context["headers"] = ["name", "target__name", "enabled"] return context class AccountViewSet(lib_viewsets.RevisionModelMixin, viewsets.ModelViewSet): """ViewSet for User/Mailbox.""" filter_backends = (filters.SearchFilter, ) permission_classes = [IsAuthenticated, DjangoModelPermissions, ] search_fields = ("^first_name", "^last_name", "^email") def get_serializer_class(self): """Return a serializer.""" action_dict = { "list": serializers.AccountSerializer, "retrieve": serializers.AccountSerializer, "password": serializers.AccountPasswordSerializer, "reset_password": serializers.ResetPasswordSerializer, } return action_dict.get( self.action, serializers.WritableAccountSerializer) def get_queryset(self): """Filter queryset based on current user.""" user = self.request.user ids = user.objectaccess_set \ .filter(content_type=ContentType.objects.get_for_model(user)) \ .values_list("object_id", flat=True) queryset = core_models.User.objects.filter(pk__in=ids) domain = self.request.query_params.get("domain") if domain: queryset = queryset.filter(mailbox__domain__name=domain) return queryset @action(methods=["put"], detail=True) def password(self, request, pk=None): """Change account password.""" try: user = core_models.User.objects.get(pk=pk) except core_models.User.DoesNotExist: raise http.Http404 serializer = self.get_serializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response() return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) @action(detail=False) def exists(self, request): """Check if account exists. Requires a valid email address as argument. Example: GET /exists/?email=user@test.com """ email = request.GET.get("email") if not email: raise ParseError("email not provided") if not core_models.User.objects.filter(email=email).exists(): data = {"exists": False} else: data = {"exists": True} serializer = serializers.AccountExistsSerializer(data) return Response(serializer.data) @action(methods=["post"], detail=False) def reset_password(self, request): """Reset account password and send a new one by SMS.""" sms_password_recovery = ( request.localconfig.parameters .get_value("sms_password_recovery", app="core") ) if not sms_password_recovery: return Response(status=404) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = core_models.User.objects.filter( email=serializer.validated_data["email"]).first() if not user or not user.phone_number: return Response(status=404) backend = sms_backends.get_active_backend( request.localconfig.parameters) if not backend: return Response(status=404) password = lib.make_password() content = _("Here is your new Modoboa password: {}").format( password) if not backend.send(content, [str(user.phone_number)]): body = {"status": "ko"} else: # SMS was sent, now we can set the new password. body = {"status": "ok"} user.set_password(password) user.save(update_fields=["password"]) return Response(body) class AliasViewSet(lib_viewsets.RevisionModelMixin, viewsets.ModelViewSet): """ create: Create a new alias instance. """ permission_classes = [IsAuthenticated, DjangoModelPermissions, ] serializer_class = serializers.AliasSerializer def get_queryset(self): """Filter queryset based on current user.""" user = self.request.user ids = ( user.objectaccess_set.filter( content_type=ContentType.objects.get_for_model(models.Alias)) .values_list("object_id", flat=True) ) queryset = models.Alias.objects.filter(pk__in=ids) domain = self.request.query_params.get("domain") if domain: queryset = queryset.filter(domain__name=domain) return queryset class SenderAddressViewSet(lib_viewsets.RevisionModelMixin, viewsets.ModelViewSet): """View set for SenderAddress model.""" permission_classes = [IsAuthenticated, DjangoModelPermissions, ] serializer_class = serializers.SenderAddressSerializer def get_queryset(self): """Filter queryset based on current user.""" user = self.request.user mb_ids = ( user.objectaccess_set.filter( content_type=ContentType.objects.get_for_model(models.Mailbox)) .values_list("object_id", flat=True) ) return models.SenderAddress.objects.filter(mailbox__pk__in=mb_ids)
{ "repo_name": "modoboa/modoboa", "path": "modoboa/admin/api/v1/viewsets.py", "copies": "1", "size": "7892", "license": "isc", "hash": 6012403017578290000, "line_mean": 35.2018348624, "line_max": 79, "alpha_frac": 0.6550937658, "autogenerated": false, "ratio": 4.305510092744135, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 218 }
"""Admin API.""" from django import http from django.contrib.contenttypes.models import ContentType from rest_framework import status, viewsets from rest_framework.decorators import detail_route, list_route from rest_framework.exceptions import ParseError from rest_framework.permissions import IsAuthenticated, DjangoModelPermissions from rest_framework.response import Response from modoboa.core import models as core_models from . import models from . import serializers class DomainViewSet(viewsets.ModelViewSet): """ViewSet for Domain.""" permission_classes = [IsAuthenticated, DjangoModelPermissions, ] serializer_class = serializers.DomainSerializer http_method_names = ["get", "post", "put", "delete"] def get_queryset(self): """Filter queryset based on current user.""" return models.Domain.objects.get_for_admin(self.request.user) def perform_destroy(self, instance): """Add custom args to delete call.""" instance.delete(self.request.user) class DomainAliasViewSet(viewsets.ModelViewSet): """ViewSet for DomainAlias.""" permission_classes = [IsAuthenticated, DjangoModelPermissions, ] serializer_class = serializers.DomainAliasSerializer http_method_names = ["get", "post", "put", "delete"] def get_queryset(self): """Filter queryset based on current user.""" queryset = models.DomainAlias.objects.get_for_admin(self.request.user) domain = self.request.query_params.get("domain") if domain: queryset = queryset.filter(target__name=domain) return queryset class AccountViewSet(viewsets.ModelViewSet): """ViewSet for User/Mailbox.""" permission_classes = [IsAuthenticated, DjangoModelPermissions, ] http_method_names = ["get", "post", "put", "delete"] def get_serializer_class(self): """Return a serializer.""" action_dict = { "list": serializers.AccountSerializer, "retrive": serializers.AccountSerializer } return action_dict.get( self.action, serializers.WritableAccountSerializer) def get_queryset(self): """Filter queryset based on current user.""" user = self.request.user ids = user.objectaccess_set \ .filter(content_type=ContentType.objects.get_for_model(user)) \ .values_list('object_id', flat=True) queryset = core_models.User.objects.filter(pk__in=ids) domain = self.request.query_params.get("domain") if domain: queryset = queryset.filter(mailbox__domain__name=domain) return queryset @detail_route(methods=["put"]) def password(self, request, pk=None): """Change account password.""" try: user = core_models.User.objects.get(pk=pk) except core_models.User.DoesNotExist: raise http.Http404 serializer = serializers.AccountPasswordSerializer( user, data=request.data) if serializer.is_valid(): serializer.save() return Response() return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) @list_route() def exists(self, request): """Check if account exists. Requires a valid email address as argument. Example: GET /exists/?email=user@test.com """ email = request.GET.get("email") if not email: raise ParseError("email not provided") if not core_models.User.objects.filter(email=email).exists(): data = {"exists": False} else: data = {"exists": True} serializer = serializers.AccountExistsSerializer(data) return Response(serializer.data) class AliasViewSet(viewsets.ModelViewSet): """ViewSet for Alias. --- create: serializer: modoboa.admin.serializers.AliasSerializer parameters: - name: recipients description: recipient(s) of the alias required: true type: array[string] paramType: form update: serializer: modoboa.admin.serializers.AliasSerializer parameters: - name: recipients description: recipient(s) of the alias required: true type: array[string] paramType: form partial_update: serializer: modoboa.admin.serializers.AliasSerializer parameters: - name: recipients description: recipient(s) of the alias required: true type: array[string] paramType: form """ permission_classes = [IsAuthenticated, DjangoModelPermissions, ] serializer_class = serializers.AliasSerializer http_method_names = ["get", "post", "put", "delete"] def get_queryset(self): """Filter queryset based on current user.""" user = self.request.user ids = ( user.objectaccess_set.filter( content_type=ContentType.objects.get_for_model(models.Alias)) .values_list('object_id', flat=True) ) queryset = models.Alias.objects.filter(pk__in=ids) domain = self.request.query_params.get("domain") if domain: queryset = queryset.filter(domain__name=domain) return queryset
{ "repo_name": "carragom/modoboa", "path": "modoboa/admin/api.py", "copies": "1", "size": "5375", "license": "isc", "hash": 7820533304622974000, "line_mean": 32.3850931677, "line_max": 78, "alpha_frac": 0.6346046512, "autogenerated": false, "ratio": 4.460580912863071, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5595185564063071, "avg_score": null, "num_lines": null }
"""Admin API.""" from __future__ import unicode_literals from django import http from django.contrib.contenttypes.models import ContentType from rest_framework import status, viewsets from rest_framework.decorators import detail_route, list_route from rest_framework.exceptions import ParseError from rest_framework.permissions import IsAuthenticated, DjangoModelPermissions from rest_framework.response import Response from modoboa.core import models as core_models from . import models from . import serializers class DomainViewSet(viewsets.ModelViewSet): """ retrieve: Return the given domain. list: Return a list of all existing domains. create: Create a new domain instance. """ permission_classes = [IsAuthenticated, DjangoModelPermissions, ] serializer_class = serializers.DomainSerializer http_method_names = ["get", "post", "put", "delete"] def get_queryset(self): """Filter queryset based on current user.""" return models.Domain.objects.get_for_admin(self.request.user) def perform_destroy(self, instance): """Add custom args to delete call.""" instance.delete(self.request.user) class DomainAliasViewSet(viewsets.ModelViewSet): """ViewSet for DomainAlias.""" permission_classes = [IsAuthenticated, DjangoModelPermissions, ] serializer_class = serializers.DomainAliasSerializer http_method_names = ["get", "post", "put", "delete"] def get_queryset(self): """Filter queryset based on current user.""" queryset = models.DomainAlias.objects.get_for_admin(self.request.user) domain = self.request.query_params.get("domain") if domain: queryset = queryset.filter(target__name=domain) return queryset class AccountViewSet(viewsets.ModelViewSet): """ViewSet for User/Mailbox.""" permission_classes = [IsAuthenticated, DjangoModelPermissions, ] http_method_names = ["get", "post", "put", "delete"] def get_serializer_class(self): """Return a serializer.""" action_dict = { "list": serializers.AccountSerializer, "retrive": serializers.AccountSerializer } return action_dict.get( self.action, serializers.WritableAccountSerializer) def get_queryset(self): """Filter queryset based on current user.""" user = self.request.user ids = user.objectaccess_set \ .filter(content_type=ContentType.objects.get_for_model(user)) \ .values_list('object_id', flat=True) queryset = core_models.User.objects.filter(pk__in=ids) domain = self.request.query_params.get("domain") if domain: queryset = queryset.filter(mailbox__domain__name=domain) return queryset @detail_route(methods=["put"]) def password(self, request, pk=None): """Change account password.""" try: user = core_models.User.objects.get(pk=pk) except core_models.User.DoesNotExist: raise http.Http404 serializer = serializers.AccountPasswordSerializer( user, data=request.data) if serializer.is_valid(): serializer.save() return Response() return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) @list_route() def exists(self, request): """Check if account exists. Requires a valid email address as argument. Example: GET /exists/?email=user@test.com """ email = request.GET.get("email") if not email: raise ParseError("email not provided") if not core_models.User.objects.filter(email=email).exists(): data = {"exists": False} else: data = {"exists": True} serializer = serializers.AccountExistsSerializer(data) return Response(serializer.data) class AliasViewSet(viewsets.ModelViewSet): """ create: Create a new alias instance. """ permission_classes = [IsAuthenticated, DjangoModelPermissions, ] serializer_class = serializers.AliasSerializer http_method_names = ["get", "post", "put", "delete"] def get_queryset(self): """Filter queryset based on current user.""" user = self.request.user ids = ( user.objectaccess_set.filter( content_type=ContentType.objects.get_for_model(models.Alias)) .values_list('object_id', flat=True) ) queryset = models.Alias.objects.filter(pk__in=ids) domain = self.request.query_params.get("domain") if domain: queryset = queryset.filter(domain__name=domain) return queryset
{ "repo_name": "bearstech/modoboa", "path": "modoboa/admin/api.py", "copies": "1", "size": "4741", "license": "isc", "hash": 3930975862180767000, "line_mean": 31.4726027397, "line_max": 78, "alpha_frac": 0.6494410462, "autogenerated": false, "ratio": 4.337602927721867, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5487043973921867, "avg_score": null, "num_lines": null }
"""Admin API related tests.""" import copy import json from unittest import mock import dns.resolver from django.test import override_settings from django.urls import reverse from rest_framework.authtoken.models import Token from reversion.models import Version from modoboa.admin import factories from modoboa.admin import models from modoboa.admin.tests import utils from modoboa.core import factories as core_factories, models as core_models from modoboa.lib.tests import ModoAPITestCase class DomainAPITestCase(ModoAPITestCase): """Check API.""" @classmethod def setUpTestData(cls): # NOQA:N802 """Create test data.""" super(DomainAPITestCase, cls).setUpTestData() factories.populate_database() cls.da_token = Token.objects.create( user=core_models.User.objects.get(username="admin@test.com")) def test_get_domains(self): """Retrieve a list of domains.""" url = reverse("v1:domain-list") response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 2) domain = response.data[0] url = reverse( "v1:domain-detail", args=[domain["pk"]]) response = self.client.get(url) data = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(data["name"], domain["name"]) self.assertEqual(data["mailbox_count"], 2) def test_create_domain(self): """Check domain creation.""" url = reverse("v1:domain-list") response = self.client.post( url, {"name": "test3.com", "quota": 0, "default_mailbox_quota": 10} ) self.assertEqual(response.status_code, 201) domain = models.Domain.objects.get(name="test3.com") self.assertEqual(Version.objects.get_for_object(domain).count(), 1) response = self.client.post(url, {}) self.assertEqual(response.status_code, 400) self.assertIn("name", response.data) response = self.client.post( url, {"name": "test5.com", "quota": 1, "default_mailbox_quota": 10} ) self.assertEqual(response.status_code, 400) self.assertIn("default_mailbox_quota", response.data) self.client.credentials( HTTP_AUTHORIZATION="Token " + self.da_token.key) response = self.client.post( url, {"name": "test4.com", "default_mailbox_quota": 10}) self.assertEqual(response.status_code, 403) @mock.patch.object(dns.resolver.Resolver, "resolve") @mock.patch("socket.getaddrinfo") def test_create_domain_with_mx_check(self, mock_getaddrinfo, mock_query): """Check domain creation when MX check is activated.""" self.set_global_parameter("enable_admin_limits", False, app="limits") self.set_global_parameter("valid_mxs", "192.0.2.1 2001:db8::1") self.set_global_parameter("domains_must_have_authorized_mx", True) reseller = core_factories.UserFactory( username="reseller", groups=("Resellers", )) token = Token.objects.create(user=reseller) self.client.credentials(HTTP_AUTHORIZATION="Token " + token.key) url = reverse("v1:domain-list") mock_query.side_effect = utils.mock_dns_query_result mock_getaddrinfo.side_effect = utils.mock_ip_query_result response = self.client.post( url, {"name": "no-mx.example.com", "quota": 0, "default_mailbox_quota": 10} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json()["name"][0], "No authorized MX record found for this domain") mock_getaddrinfo.side_effect = utils.mock_ip_query_result response = self.client.post( url, {"name": "test4.com", "quota": 0, "default_mailbox_quota": 10} ) self.assertEqual(response.status_code, 201) def test_update_domain(self): """Check domain update.""" domain = models.Domain.objects.get(name="test.com") models.Mailbox.objects.filter( domain__name="test.com", address="user").update( use_domain_quota=True) url = reverse("v1:domain-detail", args=[domain.pk]) response = self.client.put( url, {"name": "test.com", "default_mailbox_quota": 1000}) self.assertEqual(response.status_code, 200) domain.refresh_from_db() self.assertEqual(domain.default_mailbox_quota, 1000) mb = models.Mailbox.objects.get( domain__name="test.com", address="user") self.assertEqual(mb.quota, 1000) response = self.client.put( url, {"name": "test42.com", "default_mailbox_quota": 1000}) self.assertEqual(response.status_code, 200) self.assertTrue( models.Mailbox.objects.filter( address="user", domain__name="test42.com").exists()) def test_patch_domain(self): """Check domain partial update.""" domain = models.Domain.objects.get(name="test.com") url = reverse("v1:domain-detail", args=[domain.pk]) response = self.client.put(url, {"name": "toto.test"}) self.assertEqual(response.status_code, 200) domain.refresh_from_db() self.assertEqual(domain.name, "toto.test") def test_delete_domain(self): """Try to delete a domain.""" domain = models.Domain.objects.get(name="test.com") url = reverse("v1:domain-detail", args=[domain.pk]) response = self.client.delete(url) self.assertEqual(response.status_code, 204) self.assertFalse(models.Domain.objects.filter(pk=domain.pk).exists()) class DomainAliasAPITestCase(ModoAPITestCase): """Check DomainAlias API.""" @classmethod def setUpTestData(cls): # NOQA:N802 """Create test data.""" super(DomainAliasAPITestCase, cls).setUpTestData() factories.populate_database() cls.dom_alias1 = factories.DomainAliasFactory( name="dalias1.com", target__name="test.com") cls.dom_alias2 = factories.DomainAliasFactory( name="dalias2.com", target__name="test2.com") cls.da_token = Token.objects.create( user=core_models.User.objects.get(username="admin@test.com")) def test_get(self): """Retrieve a list of domain aliases.""" url = reverse("v1:domain_alias-list") response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 2) url = reverse( "v1:domain_alias-detail", args=[response.data[0]["pk"]]) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(response.data["name"], "dalias1.com") url = reverse("v1:domain_alias-list") response = self.client.get("{}?domain=test.com".format(url)) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 1) self.client.credentials( HTTP_AUTHORIZATION="Token " + self.da_token.key) response = self.client.get(reverse("v1:domain_alias-list")) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 0) def test_post(self): """Try to create a new domain alias.""" url = reverse("v1:domain_alias-list") target = models.Domain.objects.get(name="test.com") data = { "name": "dalias3.com", "target": target.pk } response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 201) dalias = response.json() dalias = models.DomainAlias.objects.filter( pk=dalias["pk"]).first() self.assertEqual(dalias.target, target) self.client.credentials( HTTP_AUTHORIZATION="Token " + self.da_token.key) response = self.client.post( url, {"name": "dalias4.com", "target": target.pk}, format="json") self.assertEqual(response.status_code, 403) def test_put(self): """Try to update a domain alias.""" dalias = models.DomainAlias.objects.get(name="dalias1.com") url = reverse("v1:domain_alias-detail", args=[dalias.pk]) data = { "name": "dalias3.com", "target": dalias.target.pk } response = self.client.put(url, data, format="json") self.assertEqual(response.status_code, 200) dalias.refresh_from_db() self.assertEqual(dalias.name, "dalias3.com") self.assertTrue(dalias.enabled) def test_delete(self): """Try to delete an existing domain alias.""" dalias = models.DomainAlias.objects.get(name="dalias1.com") url = reverse("v1:domain_alias-detail", args=[dalias.pk]) response = self.client.delete(url) self.assertEqual(response.status_code, 204) self.assertFalse( models.DomainAlias.objects.filter(pk=dalias.pk).exists()) class AccountAPITestCase(ModoAPITestCase): """Check Account API.""" ACCOUNT_DATA = { "username": "fromapi@test.com", "role": "SimpleUsers", "password": "Toto1234", "mailbox": { "full_address": "fromapi@test.com", "quota": 10 } } @classmethod def setUpTestData(cls): # NOQA:N802 """Create test data.""" super(AccountAPITestCase, cls).setUpTestData() factories.populate_database() cls.da_token = Token.objects.create( user=core_models.User.objects.get(username="admin@test.com")) def setUp(self): """Test setup.""" super(AccountAPITestCase, self).setUp() self.set_global_parameters({ "enable_admin_limits": False, "enable_domain_limits": False }, app="limits") def test_get_accounts(self): """Retrieve a list of accounts.""" url = reverse("v1:account-list") response = self.client.get(url) self.assertEqual(response.status_code, 200) response = response.json() self.assertEqual(len(response), 5) response = self.client.get("{}?domain=test.com".format(url)) self.assertEqual(response.status_code, 200) response = response.json() self.assertEqual(len(response), 2) response = self.client.get("{}?domain=pouet.com".format(url)) self.assertEqual(response.status_code, 200) response = response.json() self.assertEqual(len(response), 0) response = self.client.get("{}?search=user@test.com".format(url)) self.assertEqual(response.status_code, 200) response = response.json() self.assertEqual(len(response), 1) def test_create_account(self): """Try to create a new account.""" url = reverse("v1:account-list") response = self.client.post(url, self.ACCOUNT_DATA, format="json") self.assertEqual(response.status_code, 201) account = response.json() user = core_models.User.objects.filter(pk=account["pk"]).first() self.assertIsNot(user, None) self.assertIsNot(user.mailbox, None) domadmin = core_models.User.objects.get(username="admin@test.com") self.assertTrue(domadmin.can_access(user)) self.assertIn("pk", account["mailbox"]) data = copy.deepcopy(self.ACCOUNT_DATA) data["username"] = "fromapi_ééé@test.com" data["mailbox"]["full_address"] = data["username"] del data["password"] response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 400) data["password"] = "Toto1234" response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 201) def test_create_account_with_random_password(self): """Try to create a new account with random password.""" url = reverse("v1:account-list") data = dict(self.ACCOUNT_DATA) data["random_password"] = True del data["password"] response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 201) @override_settings(LANGUAGE_CODE="fr") def test_create_account_default_lang(self): """Try to create a new account with(out) language.""" url = reverse("v1:account-list") data = dict(self.ACCOUNT_DATA) response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 201) account = response.json() user = core_models.User.objects.filter(pk=account["pk"]).first() self.assertEqual(user.language, "fr") user.delete() data["language"] = "pl" response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 201) account = response.json() user = core_models.User.objects.filter(pk=account["pk"]).first() self.assertEqual(user.language, data["language"]) def test_create_domainadmin_account(self): """Try to create a domain admin.""" data = copy.deepcopy(self.ACCOUNT_DATA) data["domains"] = ["test.com"] data["role"] = "DomainAdmins" url = reverse("v1:account-list") response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 201) domain = models.Domain.objects.get(name="test.com") admin = core_models.User.objects.get( pk=response.json()["pk"]) self.assertIn(admin, domain.admins) response = self.client.get( reverse("v1:account-detail", args=[admin.pk])) self.assertEqual(response.status_code, 200) self.assertIn("domains", response.json()) data["username"] = "domain_admin" del data["mailbox"] response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 201) def test_create_account_with_no_mailbox(self): """Try to create a new account.""" data = copy.deepcopy(self.ACCOUNT_DATA) del data["mailbox"] url = reverse("v1:account-list") response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 201) account = response.json() user = core_models.User.objects.filter(pk=account["pk"]).first() self.assertIsNot(user, None) self.assertIsNot(user.mailbox, None) self.assertEqual( user.mailbox.quota, user.mailbox.domain.default_mailbox_quota) def test_create_existing_account(self): """Check if unicity is respected.""" data = copy.deepcopy(self.ACCOUNT_DATA) data["username"] = "user@test.com" url = reverse("v1:account-list") response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 400) data.update({"username": "domainadmin", "role": "DomainAdmins"}) data["mailbox"]["full_address"] = "admin@test.com" response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 409) def test_create_account_bad_password(self): """Try to create a new account.""" data = copy.deepcopy(self.ACCOUNT_DATA) data["password"] = "toto" url = reverse("v1:account-list") response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 400) errors = response.json() self.assertIn("password", errors) def test_create_account_as_domadmin(self): """As DomainAdmin, try to create a new account.""" self.client.credentials( HTTP_AUTHORIZATION="Token " + self.da_token.key) data = copy.deepcopy(self.ACCOUNT_DATA) data["mailbox"]["quota"] = 1000 url = reverse("v1:account-list") response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 400) data["username"] = "fromapi@test2.com" data["mailbox"].update({"full_address": "fromapi@test2.com", "quota": 10}) url = reverse("v1:account-list") response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 400) errors = response.json() self.assertIn("domain", errors) def test_create_account_bad_master_user(self): """Try to create a new account.""" data = copy.deepcopy(self.ACCOUNT_DATA) data["master_user"] = True url = reverse("v1:account-list") response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 400) errors = response.json() self.assertIn("master_user", errors) def test_update_account(self): """Try to update an account.""" account = core_models.User.objects.get(username="user@test.com") url = reverse("v1:account-detail", args=[account.pk]) data = { "username": "fromapi@test.com", "role": account.role, "password": "Toto1234", "mailbox": { "full_address": "fromapi@test.com", "quota": account.mailbox.quota } } response = self.client.put(url, data, format="json") self.assertEqual(response.status_code, 200) account.refresh_from_db() account.mailbox.refresh_from_db() self.assertEqual(account.email, account.mailbox.full_address) self.assertTrue(account.check_password("Toto1234")) del data["password"] response = self.client.put(url, data, format="json") self.assertEqual(response.status_code, 200) account.refresh_from_db() self.assertTrue(account.check_password("Toto1234")) def test_update_account_with_no_mailbox(self): """Try to disable an account.""" account = core_factories.UserFactory( username="reseller", groups=("Resellers", )) url = reverse("v1:account-detail", args=[account.pk]) data = { "username": "reseller", "role": account.role, "is_active": False } response = self.client.put(url, data, format="json") self.assertEqual(response.status_code, 200) def test_patch_account(self): """Try to patch an account.""" account = core_models.User.objects.get(username="user@test.com") old_quota = account.mailbox.quota url = reverse("v1:account-detail", args=[account.pk]) data = { "username": "fromapi@test.com", "mailbox": { "full_address": "fromapi@test.com", } } response = self.client.patch(url, data, format="json") self.assertEqual(response.status_code, 200) account.refresh_from_db() self.assertEqual(account.email, data["username"]) self.assertEqual(account.mailbox.quota, old_quota) def test_update_domain_admin_account(self): """Try to change administered domains.""" account = core_models.User.objects.get(username="admin@test.com") url = reverse("v1:account-detail", args=[account.pk]) data = { "username": account.username, "role": account.role, "password": "Toto1234", "mailbox": { "full_address": account.mailbox.full_address, "quota": account.mailbox.quota }, "domains": ["test.com", "test2.com"] } response = self.client.put(url, data, format="json") self.assertEqual(response.status_code, 200) domains = models.Domain.objects.get_for_admin(account) self.assertEqual(domains.count(), 2) self.assertTrue(domains.filter(name="test2.com").exists()) data["domains"] = ["test2.com"] response = self.client.put(url, data, format="json") self.assertEqual(response.status_code, 200) domains = models.Domain.objects.get_for_admin(account) self.assertEqual(domains.count(), 1) self.assertTrue(domains.filter(name="test2.com").exists()) def test_update_account_wrong_address(self): """Try to update an account.""" account = core_models.User.objects.get(username="user@test.com") url = reverse("v1:account-detail", args=[account.pk]) data = { "username": "fromapi@test3.com", "role": account.role, "password": "Toto1234", "mailbox": { "full_address": "fromapi@test3.com", "quota": account.mailbox.quota } } response = self.client.put(url, data, format="json") self.assertEqual(response.status_code, 404) def test_delete_account(self): """Try to delete an account.""" account = core_models.User.objects.get(username="user@test.com") domadmin = core_models.User.objects.get(username="admin@test.com") self.assertTrue(domadmin.can_access(account)) url = reverse("v1:account-detail", args=[account.pk]) response = self.client.delete(url) self.assertEqual(response.status_code, 204) self.assertFalse( core_models.User.objects.filter(pk=account.pk).exists()) self.assertFalse(domadmin.can_access(account)) def test_account_exists(self): """Validate /exists/ service.""" url = reverse("v1:account-exists") response = self.client.get( "{}?email={}".format(url, "user@test.com")) self.assertEqual(response.status_code, 200) content = response.json() self.assertTrue(content["exists"]) response = self.client.get( "{}?email={}".format(url, "pipo@test.com")) self.assertEqual(response.status_code, 200) content = response.json() self.assertFalse(content["exists"]) response = self.client.get(url) self.assertEqual(response.status_code, 400) def test_change_password(self): """Check the change password service.""" account = core_models.User.objects.get(username="user@test.com") url = reverse( "v1:account-password", args=[account.pk]) response = self.client.put( url, {"password": "toto", "new_password": "pass"}, format="json") # must fail because password is too weak self.assertEqual(response.status_code, 400) response = self.client.put( url, {"password": "toto", "new_password": "Toto1234"}, format="json") self.assertEqual(response.status_code, 200) account.refresh_from_db() self.assertTrue(account.check_password("Toto1234")) @mock.patch("ovh.Client.get") @mock.patch("ovh.Client.post") def test_reset_password(self, client_post, client_get): url = reverse("v1:account-reset-password") # SMS password recovery not enabled response = self.client.post(url) self.assertEqual(response.status_code, 404) self.set_global_parameters({ "sms_password_recovery": True, "sms_provider": "ovh", "sms_ovh_application_key": "key", "sms_ovh_application_secret": "secret", "sms_ovh_consumer_key": "consumer" }, app="core") # No email provided response = self.client.post(url) self.assertEqual(response.status_code, 400) account = core_models.User.objects.get(username="user@test.com") data = {"email": account.email} # No phone number response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 404) account.phone_number = "+33612345678" account.save() client_get.return_value = ["service"] client_post.return_value = {"totalCreditsRemoved": 1} response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 200) class AliasAPITestCase(ModoAPITestCase): """Check Alias API.""" ALIAS_DATA = { "address": "alias_fromapi@test.com", "recipients": [ "user@test.com", "postmaster@test.com", "user_éé@nonlocal.com" ] } @classmethod def setUpTestData(cls): # NOQA:N802 """Create test data.""" super(AliasAPITestCase, cls).setUpTestData() cls.localconfig.parameters.set_value( "enable_admin_limits", False, app="limits") cls.localconfig.save() factories.populate_database() cls.da_token = Token.objects.create( user=core_models.User.objects.get(username="admin@test.com")) def test_get_aliases(self): """Retrieve a list of aliases.""" url = reverse("v1:alias-list") response = self.client.get(url) self.assertEqual(response.status_code, 200) response = response.json() self.assertEqual(len(response), 3) response = self.client.get("{}?domain=test.com".format(url)) self.assertEqual(response.status_code, 200) response = response.json() self.assertEqual(len(response), 3) def test_get_alias(self): """Retrieve an alias.""" al = models.Alias.objects.get(address="alias@test.com") url = reverse("v1:alias-detail", args=[al.pk]) response = self.client.get(url) self.assertEqual(response.status_code, 200) response = response.json() self.assertEqual(response["recipients"], ["user@test.com"]) def test_create_alias(self): """Try to create a new alias.""" url = reverse("v1:alias-list") response = self.client.post(url, self.ALIAS_DATA, format="json") self.assertEqual(response.status_code, 201) alias = json.loads(response.content.decode("utf-8")) alias = models.Alias.objects.filter(pk=alias["pk"]).first() domadmin = core_models.User.objects.get(username="admin@test.com") self.assertTrue(domadmin.can_access(alias)) self.assertEqual(alias.aliasrecipient_set.count(), 3) self.assertTrue(alias.aliasrecipient_set.filter( address="user@test.com", r_mailbox__isnull=False).exists()) self.assertTrue(alias.aliasrecipient_set.filter( address="postmaster@test.com", r_alias__isnull=False).exists()) self.assertTrue(alias.aliasrecipient_set.filter( address="user_éé@nonlocal.com", r_mailbox__isnull=True, r_alias__isnull=True).exists()) # Create catchall alias data = copy.deepcopy(self.ALIAS_DATA) data["address"] = "@test.com" response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 201) def test_create_alias_as_domadmin(self): """As DomainAdmin, try to create a new alias.""" self.client.credentials( HTTP_AUTHORIZATION="Token " + self.da_token.key) url = reverse("v1:alias-list") response = self.client.post(url, self.ALIAS_DATA, format="json") self.assertEqual(response.status_code, 201) data = copy.deepcopy(self.ALIAS_DATA) data["address"] = "alias_fromapi@test2.com" response = self.client.post(url, data, format="json") self.assertEqual(response.status_code, 400) errors = response.json() self.assertIn("address", errors) def test_update_alias(self): """Try to update an alias.""" alias = models.Alias.objects.get(address="alias@test.com") url = reverse("v1:alias-detail", args=[alias.pk]) data = { "address": "alias@test.com", "recipients": ["user@test.com", "user@nonlocal.com"] } response = self.client.put(url, data, format="json") self.assertEqual(response.status_code, 200) alias.refresh_from_db() self.assertEqual(alias.aliasrecipient_set.count(), 2) data = { "address": "alias@test.com", "recipients": ["user@nonlocal.com"] } response = self.client.put(url, data, format="json") self.assertEqual(response.status_code, 200) alias.refresh_from_db() self.assertEqual(alias.aliasrecipient_set.count(), 1) data = { "address": "alias@test.com", "recipients": [] } response = self.client.put(url, data, format="json") self.assertEqual(response.status_code, 400) def test_delete_alias(self): """Try to delete an existing alias.""" alias = models.Alias.objects.get(address="alias@test.com") domadmin = core_models.User.objects.get(username="admin@test.com") self.assertTrue(domadmin.can_access(alias)) url = reverse("v1:alias-detail", args=[alias.pk]) response = self.client.delete(url) self.assertEqual(response.status_code, 204) self.assertFalse( models.Alias.objects.filter(pk=alias.pk).exists()) self.assertFalse(domadmin.can_access(alias)) self.assertFalse( models.AliasRecipient.objects.filter( address="user@test.com", alias__address="alias@test.com") .exists() ) class SenderAddressAPITestCase(ModoAPITestCase): """Check SenderAddress API.""" @classmethod def setUpTestData(cls): # NOQA:N802 """Create test data.""" super(SenderAddressAPITestCase, cls).setUpTestData() cls.localconfig.parameters.set_value( "enable_admin_limits", False, app="limits") cls.localconfig.save() factories.populate_database() cls.sa1 = factories.SenderAddressFactory( address="test@domain.ext", mailbox__user__username="user@test.com", mailbox__address="user", mailbox__domain__name="test.com" ) cls.da_token = Token.objects.create( user=core_models.User.objects.get(username="admin@test.com")) def test_list(self): """Retrieve a list of sender addresses.""" url = reverse("v1:sender_address-list") response = self.client.get(url) self.assertEqual(response.status_code, 200) response = response.json() self.assertEqual(len(response), 1) def test_create(self): """Create a new sender addresses.""" url = reverse("v1:sender_address-list") mbox = models.Mailbox.objects.get( address="admin", domain__name="test.com") data = {"address": "@extdomain.test", "mailbox": mbox.pk} response = self.client.post(url, data) self.assertEqual(response.status_code, 201) self.client.credentials( HTTP_AUTHORIZATION="Token " + self.da_token.key) data = {"address": "user@test2.com", "mailbox": mbox.pk} response = self.client.post(url, data) self.assertEqual(response.status_code, 400) self.assertEqual( response.json()["address"][0], "You don't have access to this domain.") mbox = models.Mailbox.objects.get( address="admin", domain__name="test2.com") data = {"address": "toto@titi.com", "mailbox": mbox.pk} response = self.client.post(url, data) self.assertEqual(response.status_code, 400) self.assertEqual( response.json()["mailbox"][0], "You don't have access to this mailbox.") def test_patch(self): """Patch an existing sender address.""" url = reverse("v1:sender_address-detail", args=[self.sa1.pk]) mbox = models.Mailbox.objects.get( address="user", domain__name="test.com") data = {"address": "@extdomain.test"} response = self.client.patch(url, data) self.assertEqual(response.status_code, 200) self.sa1.refresh_from_db() self.assertEqual(self.sa1.mailbox, mbox) self.assertEqual(self.sa1.address, data["address"]) def test_update(self): """Update an existing sender address.""" url = reverse("v1:sender_address-detail", args=[self.sa1.pk]) mbox = models.Mailbox.objects.get( address="user", domain__name="test.com") data = {"address": "@extdomain.test", "mailbox": mbox.pk} response = self.client.put(url, data) self.assertEqual(response.status_code, 200) self.sa1.refresh_from_db() self.assertEqual(self.sa1.mailbox, mbox) self.assertEqual(self.sa1.address, data["address"]) def test_delete(self): """Delete an existing sender address.""" url = reverse("v1:sender_address-detail", args=[self.sa1.pk]) response = self.client.delete(url) self.assertEqual(response.status_code, 204) with self.assertRaises(models.SenderAddress.DoesNotExist): self.sa1.refresh_from_db()
{ "repo_name": "modoboa/modoboa", "path": "modoboa/admin/api/v1/tests.py", "copies": "1", "size": "33081", "license": "isc", "hash": -3787825951955663400, "line_mean": 39.5318627451, "line_max": 79, "alpha_frac": 0.6095724738, "autogenerated": false, "ratio": 3.8222581763550214, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49318306501550213, "avg_score": null, "num_lines": null }
"""Admin API v2 serializers.""" import os from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ from django.contrib.auth import password_validation from rest_framework import serializers from modoboa.admin.api.v1 import serializers as v1_serializers from modoboa.core import models as core_models, signals as core_signals from modoboa.lib import exceptions as lib_exceptions from modoboa.lib import fields as lib_fields from modoboa.lib import validators, web_utils from modoboa.lib.sysutils import exec_cmd from modoboa.parameters import tools as param_tools from ... import constants, models class CreateDomainAdminSerializer(serializers.Serializer): """Sub serializer for domain administrator creation.""" username = serializers.CharField() password = serializers.CharField(required=False) with_mailbox = serializers.BooleanField(default=False) with_aliases = serializers.BooleanField(default=False) class DomainSerializer(v1_serializers.DomainSerializer): """Domain serializer for v2 API.""" domain_admin = CreateDomainAdminSerializer(required=False) class Meta(v1_serializers.DomainSerializer.Meta): fields = v1_serializers.DomainSerializer.Meta.fields + ( "domain_admin", ) def create(self, validated_data): """Create administrator and other stuff if needed.""" domain_admin = validated_data.pop("domain_admin", None) domain = super().create(validated_data) if not domain_admin: return domain # 1. Create a domain administrator username = "%s@%s" % (domain_admin["username"], domain.name) try: da = core_models.User.objects.get(username=username) except core_models.User.DoesNotExist: pass else: raise lib_exceptions.Conflict( _("User '%s' already exists") % username) user = self.context["request"].user core_signals.can_create_object.send( self.__class__, context=user, klass=models.Mailbox) da = core_models.User(username=username, email=username, is_active=True) password = domain_admin.get("password") if password is None: password = param_tools.get_global_parameter( "default_password", app="core") da.set_password(password) da.save() da.role = "DomainAdmins" da.post_create(user) # 2. Create mailbox if needed if domain_admin["with_mailbox"]: dom_admin_username = domain_admin["username"] mb = models.Mailbox( address=dom_admin_username, domain=domain, user=da, use_domain_quota=True ) mb.set_quota( override_rules=user.has_perm("admin.change_domain")) mb.save(creator=user) # 3. Create aliases if needed condition = ( domain.type == "domain" and domain_admin["with_aliases"] and dom_admin_username != "postmaster" ) if condition: core_signals.can_create_object.send( self.__class__, context=user, klass=models.Alias) address = u"postmaster@{}".format(domain.name) alias = models.Alias.objects.create( address=address, domain=domain, enabled=True) alias.set_recipients([mb.full_address]) alias.post_create(user) domain.add_admin(da) return domain class DeleteDomainSerializer(serializers.Serializer): """Serializer used with delete operation.""" keep_folder = serializers.BooleanField(default=False) class AdminGlobalParametersSerializer(serializers.Serializer): """A serializer for global parameters.""" # Domain settings enable_mx_checks = serializers.BooleanField(default=True) valid_mxs = serializers.CharField(allow_blank=True) domains_must_have_authorized_mx = serializers.BooleanField(default=False) enable_spf_checks = serializers.BooleanField(default=True) enable_dkim_checks = serializers.BooleanField(default=True) enable_dmarc_checks = serializers.BooleanField(default=True) enable_autoconfig_checks = serializers.BooleanField(default=True) custom_dns_server = serializers.IPAddressField(allow_blank=True) enable_dnsbl_checks = serializers.BooleanField(default=True) dkim_keys_storage_dir = serializers.CharField(allow_blank=True) dkim_default_key_length = serializers.ChoiceField( default=2048, choices=constants.DKIM_KEY_LENGTHS) default_domain_quota = serializers.IntegerField(default=0) default_domain_message_limit = serializers.IntegerField( required=False, allow_null=True) # Mailboxes settings handle_mailboxes = serializers.BooleanField(default=False) default_mailbox_quota = serializers.IntegerField(default=0) default_mailbox_message_limit = serializers.IntegerField( required=False, allow_null=True) auto_account_removal = serializers.BooleanField(default=False) auto_create_domain_and_mailbox = serializers.BooleanField(default=True) create_alias_on_mbox_rename = serializers.BooleanField(default=False) def validate_default_domain_quota(self, value): """Ensure quota is a positive integer.""" if value < 0: raise serializers.ValidationError( _("Must be a positive integer") ) return value def validate_default_mailbox_quota(self, value): """Ensure quota is a positive integer.""" if value < 0: raise serializers.ValidationError( _("Must be a positive integer") ) return value def validate_dkim_keys_storage_dir(self, value): """Check that directory exists.""" if value: if not os.path.isdir(value): raise serializers.ValidationError( _("Directory not found.") ) code, output = exec_cmd("which openssl") if code: raise serializers.ValidationError( _("openssl not found, please make sure it is installed.") ) return value def validate(self, data): """Check MX options.""" condition = ( data.get("enable_mx_checks") and data.get("domains_must_have_authorized_mx") and not data.get("valid_mxs")) if condition: raise serializers.ValidationError({ "valid_mxs": _("Define at least one authorized network / address") }) return data class DomainAdminSerializer(serializers.ModelSerializer): """Serializer used for administrator related routes.""" class Meta: model = core_models.User fields = ("id", "username", "first_name", "last_name") class SimpleDomainAdminSerializer(serializers.Serializer): """Serializer used for add/remove operations.""" account = serializers.PrimaryKeyRelatedField( queryset=core_models.User.objects.all() ) class TagSerializer(serializers.Serializer): """Serializer used to represent a tag.""" name = serializers.CharField() label = serializers.CharField() type = serializers.CharField() class IdentitySerializer(serializers.Serializer): """Serializer used for identities.""" pk = serializers.IntegerField() type = serializers.CharField() identity = serializers.CharField() name_or_rcpt = serializers.CharField() tags = TagSerializer(many=True) class MailboxSerializer(serializers.ModelSerializer): """Base mailbox serializer.""" quota = serializers.CharField(required=False) class Meta: model = models.Mailbox fields = ( "pk", "use_domain_quota", "quota", "message_limit" ) def validate_quota(self, value): """Convert quota to MB.""" return web_utils.size2integer(value, output_unit="MB") def validate(self, data): """Check if quota is required.""" method = self.context["request"].method if not data.get("use_domain_quota", False): if "quota" not in data and method != "PATCH": raise serializers.ValidationError({ "quota": _("This field is required") }) return data class WritableAccountSerializer(v1_serializers.WritableAccountSerializer): """Add support for aliases and sender addresses.""" aliases = serializers.ListField( child=lib_fields.DRFEmailFieldUTF8(), required=False ) mailbox = MailboxSerializer(required=False) class Meta(v1_serializers.WritableAccountSerializer.Meta): fields = tuple( field for field in v1_serializers.WritableAccountSerializer.Meta.fields if field != "random_password" ) + ("aliases", ) def validate_aliases(self, value): """Check if required domains are locals and user can access them.""" aliases = [] for alias in value: localpart, domain = models.validate_alias_address( alias, self.context["request"].user) aliases.append({"localpart": localpart, "domain": domain}) return aliases def validate(self, data): """Check constraints.""" master_user = data.get("master_user", False) role = data.get("role") if master_user and role != "SuperAdmins": raise serializers.ValidationError({ "master_user": _("Not allowed for this role.") }) if role == "SimpleUsers": username = data.get("username") if username: try: validators.UTF8EmailValidator()(username) except ValidationError as err: raise ValidationError({"username": err.message}) mailbox = data.get("mailbox") if mailbox is None: if not self.instance: data["mailbox"] = { "use_domain_quota": True } if data.get("password") or not self.partial: password = data.get("password") if password: try: password_validation.validate_password( data["password"], self.instance) except ValidationError as exc: raise serializers.ValidationError({ "password": exc.messages[0]}) elif not self.instance: raise serializers.ValidationError({ "password": _("This field is required.") }) aliases = data.get("aliases") if aliases and "mailbox" not in data: raise serializers.ValidationError({ "aliases": _("A mailbox is required to create aliases.") }) domain_names = data.get("domains") if not domain_names: return data domains = [] for name in domain_names: domain = models.Domain.objects.filter(name=name).first() if domain: domains.append(domain) continue raise serializers.ValidationError({ "domains": _("Local domain {} does not exist").format(name) }) data["domains"] = domains return data def create(self, validated_data): """Create account, mailbox and aliases.""" creator = self.context["request"].user mailbox_data = validated_data.pop("mailbox", None) role = validated_data.pop("role") domains = validated_data.pop("domains", []) aliases = validated_data.pop("aliases", None) user = core_models.User(**validated_data) password = validated_data.pop("password") user.set_password(password) if "language" not in validated_data: user.language = settings.LANGUAGE_CODE user.save(creator=creator) if mailbox_data: mailbox_data["full_address"] = user.username self._create_mailbox(creator, user, mailbox_data) user.role = role self.set_permissions(user, domains) if aliases: for alias in aliases: models.Alias.objects.create( creator=creator, domain=alias["domain"], address="{}@{}".format(alias["localpart"], alias["domain"]), recipients=[user.username] ) return user class DeleteAccountSerializer(serializers.Serializer): """Serializer used with delete operation.""" keepdir = serializers.BooleanField(default=False) class AliasSerializer(v1_serializers.AliasSerializer): """Alias serializer for v2 API.""" class Meta(v1_serializers.AliasSerializer.Meta): # We remove 'internal' field fields = tuple( field for field in v1_serializers.AliasSerializer.Meta.fields if field != "internal" ) + ("expire_at", "description")
{ "repo_name": "modoboa/modoboa", "path": "modoboa/admin/api/v2/serializers.py", "copies": "1", "size": "13290", "license": "isc", "hash": -7530860059036407000, "line_mean": 35.6115702479, "line_max": 82, "alpha_frac": 0.6136192626, "autogenerated": false, "ratio": 4.633891213389122, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5747510475989123, "avg_score": null, "num_lines": null }
"""Admin API v2 viewsets.""" from django.utils.translation import ugettext as _ from django.contrib.contenttypes.models import ContentType from django_filters import rest_framework as dj_filters from drf_spectacular.utils import extend_schema, extend_schema_view from rest_framework import ( filters, mixins, permissions, response, status, viewsets ) from rest_framework.decorators import action from rest_framework.exceptions import PermissionDenied from modoboa.admin.api.v1 import ( serializers as v1_serializers, viewsets as v1_viewsets ) from modoboa.core import models as core_models from modoboa.lib import viewsets as lib_viewsets from ... import lib from ... import models from . import serializers @extend_schema_view( retrieve=extend_schema( description="Retrieve a particular domain", summary="Retrieve a particular domain" ), list=extend_schema( description="Retrieve a list of domains", summary="Retrieve a list of domains" ), create=extend_schema( description="Create a new domain", summary="Create a new domain" ), delete=extend_schema( description="Delete a particular domain", summary="Delete a particular domain" ), ) class DomainViewSet(lib_viewsets.RevisionModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): """V2 viewset.""" permission_classes = ( permissions.IsAuthenticated, permissions.DjangoModelPermissions, ) def get_queryset(self): """Filter queryset based on current user.""" return models.Domain.objects.get_for_admin(self.request.user) def get_serializer_class(self, *args, **kwargs): if self.action == "create": return serializers.DomainSerializer if self.action == "delete": return serializers.DeleteDomainSerializer if self.action == "administrators": return serializers.DomainAdminSerializer if self.action in ["add_administrator", "remove_administrator"]: return serializers.SimpleDomainAdminSerializer return v1_serializers.DomainSerializer @action(methods=["post"], detail=True) def delete(self, request, **kwargs): """Custom delete method that accepts body arguments.""" domain = self.get_object() if not request.user.can_access(domain): raise PermissionDenied(_("You don't have access to this domain")) mb = getattr(request.user, "mailbox", None) if mb and mb.domain == domain: raise PermissionDenied(_("You can't delete your own domain")) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) domain.delete(request.user, serializer.validated_data["keep_folder"]) return response.Response(status=status.HTTP_204_NO_CONTENT) @action(methods=["get"], detail=True) def administrators(self, request, **kwargs): """Retrieve all administrators of a domain.""" domain = self.get_object() serializer = self.get_serializer(domain.admins, many=True) return response.Response(serializer.data) @action(methods=["post"], detail=True, url_path="administrators/add") def add_administrator(self, request, **kwargs): """Add an administrator to a domain.""" domain = self.get_object() context = self.get_serializer_context() context["domain"] = domain serializer = self.get_serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) domain.add_admin(serializer.validated_data["account"]) return response.Response() @action(methods=["post"], detail=True, url_path="administrators/remove") def remove_administrator(self, request, **kwargs): """Remove an administrator from a domain.""" domain = self.get_object() context = self.get_serializer_context() context["domain"] = domain serializer = self.get_serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) domain.remove_admin(serializer.validated_data["account"]) return response.Response() class AccountFilterSet(dj_filters.FilterSet): """Custom FilterSet for Account.""" domain = dj_filters.ModelChoiceFilter( queryset=lambda request: models.Domain.objects.get_for_admin( request.user), field_name="mailbox__domain" ) role = dj_filters.CharFilter(method="filter_role") class Meta: model = core_models.User fields = ["domain", "role"] def filter_role(self, queryset, name, value): return queryset.filter(groups__name=value) class AccountViewSet(v1_viewsets.AccountViewSet): """ViewSet for User/Mailbox.""" filter_backends = (filters.SearchFilter, dj_filters.DjangoFilterBackend) filterset_class = AccountFilterSet def get_serializer_class(self): if self.action in ["create", "validate", "update", "partial_update"]: return serializers.WritableAccountSerializer if self.action == "delete": return serializers.DeleteAccountSerializer return super().get_serializer_class() def get_queryset(self): """Filter queryset based on current user.""" user = self.request.user ids = ( user.objectaccess_set .filter(content_type=ContentType.objects.get_for_model(user)) .values_list("object_id", flat=True) ) return core_models.User.objects.filter(pk__in=ids) @action(methods=["post"], detail=False) def validate(self, request, **kwargs): """Validate given account without creating it.""" serializer = self.get_serializer( data=request.data, context=self.get_serializer_context(), partial=True) serializer.is_valid(raise_exception=True) return response.Response(status=204) @action(methods=["get"], detail=False) def random_password(self, request, **kwargs): """Generate a random password.""" password = lib.make_password() return response.Response({"password": password}) @action(methods=["post"], detail=True) def delete(self, request, **kwargs): """Custom delete method that accepts body arguments.""" account = self.get_object() serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) account.delete() return response.Response(status=status.HTTP_204_NO_CONTENT) class IdentityViewSet(viewsets.ViewSet): """Viewset for identities.""" permission_classes = (permissions.IsAuthenticated, ) def list(self, request, **kwargs): """Return all identities.""" serializer = serializers.IdentitySerializer( lib.get_identities(request.user), many=True) return response.Response(serializer.data) class AliasViewSet(v1_viewsets.AliasViewSet): """Viewset for Alias.""" serializer_class = serializers.AliasSerializer @action(methods=["post"], detail=False) def validate(self, request, **kwargs): """Validate given alias without creating it.""" serializer = self.get_serializer( data=request.data, context=self.get_serializer_context(), partial=True) serializer.is_valid(raise_exception=True) return response.Response(status=204) @action(methods=["get"], detail=False) def random_address(self, request, **kwargs): return response.Response({ "address": models.Alias.generate_random_address() })
{ "repo_name": "modoboa/modoboa", "path": "modoboa/admin/api/v2/viewsets.py", "copies": "1", "size": "7880", "license": "isc", "hash": -3384506701012157400, "line_mean": 35.9953051643, "line_max": 77, "alpha_frac": 0.6597715736, "autogenerated": false, "ratio": 4.313081554460865, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5472853128060865, "avg_score": null, "num_lines": null }
"""Admin application helper utilities.""" from flask_admin.base import MenuLink from flask.ext.admin.contrib.sqla import ModelView from flask_login import current_user from pygotham.core import db __all__ = ('menu_link', 'model_view') class AdminModelView(ModelView): """Base class for all protected admin model-based views.""" acceptable_roles = [] def is_accessible(self): """Return ``True`` if any acceptable role is found.""" acceptable_roles = set(self.acceptable_roles) acceptable_roles.add('admin') return any(current_user.has_role(role) for role in acceptable_roles) class AuthenticatedMenuLink(MenuLink): """Only show a link to authenticated users.""" def is_accessible(self): return current_user.is_authenticated() class NotAuthenticatedMenuLink(MenuLink): """Only show a link to unauthenticated users.""" def is_accessible(self): return not current_user.is_authenticated() def menu_link(name, endpoint, authenticated): """Return a subclass of :class:`~flask_admin.base.MenuLink`. :param name: name of the link. :param endpoint: endpoint of the view for the link. :param authenticated: whether or not the link is available to authenticated users. """ type_name = '{}MenuLink'.format(name) spec = ( AuthenticatedMenuLink if authenticated else NotAuthenticatedMenuLink, ) cls = type(type_name, spec, {}) return cls(name=name, endpoint=endpoint) def model_view(model, name, category=None, **kwargs): r"""Return a subclass of :class:`~flask.ext.admin.contrib.sql.ModelView`. :param model: model class to associate with the view. :param name: name of the menu item. :param category: (optional) category of the menu item. :param \*\*kwargs: class-level attributes for the :class:`~flask.ext.admin.contrib.sqla.ModelView`. """ type_name = '{}ModelView'.format(model.__class__.__name__) cls = type(type_name, (AdminModelView,), kwargs) return cls(model, db.session, name, category, name.lower())
{ "repo_name": "PyGotham/pygotham", "path": "pygotham/admin/utils.py", "copies": "2", "size": "2128", "license": "bsd-3-clause", "hash": -477316952364873400, "line_mean": 30.7611940299, "line_max": 77, "alpha_frac": 0.6734022556, "autogenerated": false, "ratio": 3.9850187265917603, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.565842098219176, "avg_score": null, "num_lines": null }
"""Admin application.""" import importlib import pkgutil from flask_admin import Admin from flask_admin.base import AdminIndexView, MenuLink from flask.ext.admin.contrib.sqla import ModelView from flask_login import current_user from raven.contrib.flask import Sentry from pygotham import factory, filters __all__ = ('create_app',) class HomeView(AdminIndexView): """Only show the admin to authenticated admin users.""" def is_accessible(self): return current_user.has_role('admin') def create_app(settings_override=None): """Return the PyGotham admin application. :param settings_override: a ``dict`` of settings to override. """ app = factory.create_app(__name__, __path__, settings_override) Sentry(app) app.jinja_env.filters['rst'] = filters.rst_to_html # Because the admin is being wrapped inside an app, the url needs to # be overridden to use / instead of the default of /admin/. One of # the side effects of doing this is that the static assets won't # serve correctly without overriding static_url_path as well. admin = Admin( app, name='PyGotham', static_url_path='/admin', subdomain='<event_slug>', index_view=HomeView(endpoint='', url='/'), template_mode='bootstrap3', ) # Iterate through all the modules of the current package. For each # module, check the public API for any instances of types that can # be added to the Flask-Admin menu and register them. for _, name, _ in pkgutil.iter_modules(__path__): module = importlib.import_module('{}.{}'.format(__name__, name)) for attr in dir(module): view = getattr(module, attr) if isinstance(view, ModelView): admin.add_view(view) elif isinstance(view, MenuLink): admin.add_link(view) return app
{ "repo_name": "pathunstrom/pygotham", "path": "pygotham/admin/__init__.py", "copies": "2", "size": "1881", "license": "bsd-3-clause", "hash": -3089258057826308000, "line_mean": 30.8813559322, "line_max": 72, "alpha_frac": 0.6608187135, "autogenerated": false, "ratio": 4.053879310344827, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 59 }
"""Admin automatic evaluation of teams view.""" import copy import cStringIO import csv from auvsi_suas.models import MissionConfig from auvsi_suas.views import logger from auvsi_suas.views.decorators import require_superuser from auvsi_suas.views.missions import mission_for_request from django.http import HttpResponse from django.http import HttpResponseServerError from django.utils.decorators import method_decorator from django.views.generic import View class EvaluateTeams(View): """Evaluates the teams by forming a CSV containing useful stats.""" @method_decorator(require_superuser) def dispatch(self, *args, **kwargs): return super(EvaluateTeams, self).dispatch(*args, **kwargs) def get(self, request): logger.info('Admin downloaded team evaluation.') # Get the mission to evaluate a team for. mission, error = mission_for_request(request.GET) if error: logger.warning('Could not get mission to evaluate teams.') return error # Get the eval data for the teams user_eval_data = mission.evaluate_teams() if not user_eval_data: logger.warning('No data for team evaluation.') return HttpResponseServerError( 'Could not get user evaluation data.') # Reformat to column oriented user_col_data = {} for (user, eval_data) in user_eval_data.iteritems(): col_data = user_col_data.setdefault(user, {}) col_data['username'] = user.username work_queue = [([], eval_data)] while len(work_queue) > 0: (cur_prefixes, cur_map) = work_queue.pop() for (key, val) in cur_map.iteritems(): new_prefixes = copy.copy(cur_prefixes) new_prefixes.append(str(key)) if isinstance(val, dict): work_queue.append((new_prefixes, val)) else: column_key = '.'.join(new_prefixes) col_data[column_key] = val # Get column headers col_headers = set() for col_data in user_col_data.values(): for header in col_data.keys(): col_headers.add(header) col_headers = sorted(col_headers) # Write output csv_output = cStringIO.StringIO() writer = csv.DictWriter(csv_output, fieldnames=col_headers) writer.writeheader() for col_data in user_col_data.values(): writer.writerow(col_data) output = csv_output.getvalue() csv_output.close() return HttpResponse(output)
{ "repo_name": "transformation/utatuav-interop", "path": "auvsi/server/auvsi_suas/views/auvsi_admin/evaluate_teams.py", "copies": "1", "size": "2670", "license": "apache-2.0", "hash": -7020055705648351000, "line_mean": 37.1428571429, "line_max": 71, "alpha_frac": 0.6104868914, "autogenerated": false, "ratio": 4.24483306836248, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 70 }
#admin blueprint from flask import Blueprint, render_template, redirect, session, request import MySQLdb as mdb import json import hashlib blueprint = Blueprint('admin', __name__, url_prefix='/admin', static_folder='../static', template_folder='../templates') #database query functions def getHours(): #gets fec hours con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "select * from hours" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) rows = cur.fetchall() return rows def getReservations(): #gets fec reservations con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "select * from reservations where date > CURDATE()" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) rows = cur.fetchall() x = 0 while x < len(rows): rows[x]["details"] = unicode(rows[x]["details"], "utf-8") x += 1 return rows def deleteReservation(i): #deletes fec reservations con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "delete from reservations where id = " + str(i) with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) def updateDay(day, start, end, o): #gets fec hours con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "update hours set start = " + start + ", end = " + end + ", open = " + o + " where day = '" + day + "'" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) def updatePassword(password): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "update password set password = '" + hashlib.md5(password).hexdigest() + "'" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) def updatePeople(people): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "update people set people = " + str(people) with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) def updatePhone(phone): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "update phone set phone = '" + str(phone) + "'" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) def updateEmail(email): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "update email set email = '" + email + "'" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) def getPassword(): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "select password from password" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) rows = cur.fetchall() return rows[0]["password"] def getPeople(): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "select people from people" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) rows = cur.fetchall() return rows[0]["people"] def getPhone(): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "select phone from phone" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) rows = cur.fetchall() return rows[0]["phone"] def getEmail(): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "select email from email" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) rows = cur.fetchall() return rows[0]["email"] def getReservationsByMonth(): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "select months.id, months.month, count(reservations.id) count from months left outer join reservations on months.id = month(reservations.date) group by months.id order by months.id asc;" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) rows = cur.fetchall() return rows def getReservationsByDay(): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "select days.id, days.day, count(reservations.id) count from days left outer join reservations on days.id = dayofweek(reservations.date) group by days.id order by days.id asc;" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) rows = cur.fetchall() return rows def getPackagesByType(): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "select packages.id - 1 id, packages.package, count(reservations.id) count from packages left outer join reservations on packages.id - 1 = reservations.package group by packages.id order by packages.id asc;" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) rows = cur.fetchall() return rows def getReservationsByCounty(): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "SELECT county, COUNT(*) count FROM reservations where county <> 'NULL' GROUP BY county ORDER BY count asc;" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) rows = cur.fetchall() return rows def getMessages(): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') con.set_character_set('utf8') query = "select *, DATE_FORMAT(ts, '%c/%e/%Y') smalldate,DATE_FORMAT(ts, '%l:%i %p') time, DATE_FORMAT(ts, '%M %e, %Y') date from messages order by ts desc;" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute('SET NAMES utf8;') cur.execute('SET CHARACTER SET utf8;') cur.execute('SET character_set_connection=utf8;') cur.execute(query) rows = cur.fetchall() x = 0 while x < len(rows): rows[x]["message"] = unicode(rows[x]["message"], "utf-8") x += 1 return rows def numberOfMessages(): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "select count(*) count from messages" with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) rows = cur.fetchall() return int(rows[0]["count"]) def deleteMessage(i): con = mdb.connect('localhost', 'root', 'visibilitymatters', 'fbla') query = "delete from messages where id = " + str(i) with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute(query) #session functions def login(): session["admin"] = True def logout(): session.pop("admin") @blueprint.route('/') def indexRoute(): if "admin" in session: return render_template("admin_pages/index.html", page="home", messageNum=numberOfMessages(), reservationsByMonth=getReservationsByMonth(), reservationsByDay=getReservationsByDay(), packagesByType=getPackagesByType(), reservationsByCounty=getReservationsByCounty()) else: return redirect("/admin/login") @blueprint.route('/hours') def formRoute(): if "admin" in session: return render_template("admin_pages/hours.html", page="hours", messageNum=numberOfMessages(), hours=getHours()) else: return redirect("/admin/login") @blueprint.route('/reservations') def reservationsRoute(): if "admin" in session: return render_template("admin_pages/reservations.html", page="reservations", messageNum=numberOfMessages(), reservations=getReservations()) else: return redirect("/admin/login") @blueprint.route('/settings') def settingsRoute(): if "admin" in session: return render_template("admin_pages/settings.html", page="settings", messageNum=numberOfMessages(), people=getPeople(), phone=getPhone(), email=getEmail()) else: return redirect("/admin/login") @blueprint.route('/messages') def messagesRoute(): if "admin" in session: return render_template("admin_pages/messages.html", page="messages", messageNum=numberOfMessages(), messages=getMessages()) else: return redirect("/admin/login") #login routes @blueprint.route('/login', methods=["GET", "POST"]) def loginRoute(): if "admin" not in session: if request.method == "GET": error = False try: request.args["password"] error = True except: pass return render_template("admin_pages/login.html", page="login", error=error) if request.method == "POST": if hashlib.md5(request.form["password"]).hexdigest() == getPassword(): login() return redirect("/admin") else: return redirect("/admin/login?password=false") else: return redirect("/admin") @blueprint.route('/logout') def logoutRoute(): logout() return redirect("/admin/login") #api routes @blueprint.route('/api/updatehours', methods=["POST"]) def apiUpdateHoursRoute(): if "admin" in session: hours = json.loads(request.form["hours"]) updateDay("mon", hours["mon"]["start"], hours["mon"]["end"], hours["mon"]["open"]) updateDay("tue", hours["tue"]["start"], hours["tue"]["end"], hours["tue"]["open"]) updateDay("wed", hours["wed"]["start"], hours["wed"]["end"], hours["wed"]["open"]) updateDay("thu", hours["thu"]["start"], hours["thu"]["end"], hours["thu"]["open"]) updateDay("fri", hours["fri"]["start"], hours["fri"]["end"], hours["fri"]["open"]) updateDay("sat", hours["sat"]["start"], hours["sat"]["end"], hours["sat"]["open"]) updateDay("sun", hours["sun"]["start"], hours["sun"]["end"], hours["sun"]["open"]) return "true" else: return "false" @blueprint.route('/api/deletereservation', methods=["POST"]) def apiDeleteReservationRoute(): if "admin" in session: deleteReservation(request.form["id"]) return "true" else: return "false" @blueprint.route('/api/updatepassword', methods=["POST"]) def apiUpdatePasswordRoute(): if "admin" in session: updatePassword(request.form["password"]) return "true" else: return "false" @blueprint.route('/api/updatepeople', methods=["POST"]) def apiUpdatePeopleRoute(): if "admin" in session: updatePeople(request.form["people"]) return "true" else: return "false" @blueprint.route('/api/updatephone', methods=["POST"]) def apiUpdatePhoneRoute(): if "admin" in session: updatePhone(request.form["phone"]) return "true" else: return "false" @blueprint.route('/api/updateemail', methods=["POST"]) def apiUpdateEmailRoute(): if "admin" in session: updateEmail(request.form["email"]) return "true" else: return "false" @blueprint.route('/api/deletemessage', methods=["POST"]) def apiDeleteMessageRoute(): if "admin" in session: deleteMessage(request.form["id"]) return "true" else: return "false"
{ "repo_name": "rileymjohnson/fbla", "path": "app/admin/views.py", "copies": "1", "size": "10140", "license": "mit", "hash": 2985858388038877700, "line_mean": 31.7096774194, "line_max": 266, "alpha_frac": 0.6958579882, "autogenerated": false, "ratio": 3.1393188854489162, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4335176873648916, "avg_score": null, "num_lines": null }
"""Admin Cell CLI module""" from __future__ import absolute_import import logging import click from treadmill import admin from treadmill import cli from treadmill import context from treadmill import utils from treadmill import versionmgr from treadmill import zkutils from treadmill import zknamespace as z _LOGGER = logging.getLogger(__name__) def init(): """Admin Cell CLI module""" @click.command() @click.option('--ldap', required=True, envvar='TREADMILL_LDAP') @click.option('--ldap-search-base', required=True, envvar='TREADMILL_LDAP_SEARCH_BASE') @click.option('--batch', help='Upgrade batch size.', type=int, default=10) @click.option('--timeout', help='Upgrade timeout.', type=int, default=60) @click.option('--treadmill_root', help='Treadmill root dir.') @click.option('--continue_on_error', help='Stop if batch upgrade failed.', is_flag=True, default=False) @click.option('--dry_run', help='Dry run, verify status.', is_flag=True, default=False) @click.option('--force', help='Force event if server appears up-to-date', is_flag=True, default=False) @click.option('--servers', help='Servers to upgrade.', multiple=True, default=[],) @click.argument('cell') @cli.admin.ON_EXCEPTIONS def upgrade(cell, ldap, ldap_search_base, batch, timeout, treadmill_root, continue_on_error, dry_run, force, servers): """Upgrade the supplied cell""" context.GLOBAL.ldap.url = ldap context.GLOBAL.ldap.search_base = ldap_search_base servers = [] for server_list in servers: servers.extend(server_list.split(',')) if not treadmill_root: admin_cell = admin.Cell(context.GLOBAL.ldap.conn) cell_info = admin_cell.get(cell) treadmill_root = cell_info.get('treadmill_root') _LOGGER.info('Treadmill root: %s', treadmill_root) digest = versionmgr.checksum_dir(treadmill_root).hexdigest() _LOGGER.info('Checksum: %s', digest) context.GLOBAL.resolve(cell) zkclient = context.GLOBAL.zk.conn if not servers: # pylint: disable=R0204 servers = zkutils.get(zkclient, z.SERVERS) if dry_run: failed = versionmgr.verify(zkclient, digest, servers) else: failed = versionmgr.upgrade( zkclient, digest, servers, batch, timeout, stop_on_error=(not continue_on_error), force_upgrade=force, ) if not failed: _LOGGER.info('All servers are up to date.') else: _LOGGER.error('Upgrade failed.') utils.print_yaml(failed) return upgrade
{ "repo_name": "toenuff/treadmill", "path": "lib/python/treadmill/cli/admin/cell.py", "copies": "1", "size": "2938", "license": "apache-2.0", "hash": 5145009055402012000, "line_mean": 31.6444444444, "line_max": 77, "alpha_frac": 0.586113002, "autogenerated": false, "ratio": 3.9225634178905207, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 90 }
"""Admin Cell CLI module""" import importlib import logging import sys import time import click import jinja2 import ldap3 import yaml from treadmill import admin from treadmill import cli from treadmill import context from treadmill import master as master_api from treadmill import zkadmin from treadmill import zknamespace as z from treadmill import zkutils from treadmill.api import instance _LOGGER = logging.getLogger(__name__) _CELL_APIS = ['adminapi', 'wsapi', 'stateapi', 'cellapi'] class CellCtx(object): """Cell context.""" def __init__(self): self.cell = context.GLOBAL.cell admin_cell = admin.Cell(context.GLOBAL.ldap.conn) cell = admin_cell.get(self.cell) self.version = cell['version'] self.proid = cell['username'] self.treadmill = cell.get('root') if not self.treadmill: self.treadmill = _treadmill_root(self.version) def _treadmill_root(version): """Load cell version plugin""" cell_plugin = importlib.import_module('treadmill.plugins.cell_model') return cell_plugin.treadmill_root(version) def _cell_version(cellname): """Gets the cell based treadmill root.""" admin_cell = admin.Cell(context.GLOBAL.ldap.conn) cell = admin_cell.get(cellname) version = cell.get('version') if version is None: raise Exception('Version is not defined for cell: %s') root = cell.get('root') if not root: root = _treadmill_root(version) return version, root def _zkok(cell): """Check that Zookeeper ensemble has two followers and is ok.""" status = { 'follower': 0, 'leader': 0, } for master in cell['masters']: hostname = master['hostname'] port = master['zk-client-port'] try: zk_status = zkadmin.netcat(hostname, port, 'stat\n') for line in zk_status.splitlines(): line.strip() if line == 'Mode: follower': status['follower'] += 1 break if line == 'Mode: leader': status['leader'] += 1 break except Exception: return False return (status['leader'] == 1) and (status['follower'] == 2) def init(): """Admin Cell CLI module""" @click.group(name='cell') @click.option('--cell', required=True, envvar='TREADMILL_CELL', is_eager=True, callback=cli.handle_context_opt, expose_value=False) @click.pass_context def cell_grp(ctx): """Manage treadmill cell.""" ctx.obj = CellCtx() @cell_grp.command(name='clear-blackout') def clear_blackout(): """Clear cell blackout.""" zkclient = context.GLOBAL.zk.conn blacked_out = zkclient.get_children(z.BLACKEDOUT_SERVERS) for server in blacked_out: zkutils.ensure_deleted(zkclient, z.path.blackedout_server(server)) @cell_grp.command(name='configure-apps') @click.option('--root', help='Treadmill root override.') @click.option('--apps', type=cli.LIST, help='List of apps to configure.') @click.option('--dry-run', help='Dry run.', is_flag=True, default=False) @click.pass_context def configure_apps(ctx, root, apps, dry_run): """Configure cell API.""" admin_app = admin.Application(context.GLOBAL.ldap.conn) if not apps: apps = _CELL_APIS if root: ctx.obj.treadmill = root jinja_env = jinja2.Environment(loader=jinja2.PackageLoader(__name__)) for appname in apps: template = jinja_env.get_template(appname) app = yaml.load(template.render(**ctx.obj.__dict__)) fullname = '%s.%s.%s' % (ctx.obj.proid, appname, ctx.obj.cell) _LOGGER.debug(fullname) _LOGGER.debug(yaml.dump(app)) if not dry_run: try: admin_app.create(fullname, app) except ldap3.LDAPEntryAlreadyExistsResult: admin_app.replace(fullname, app) @cell_grp.command(name='configure-monitors') @click.option('--monitors', type=cli.DICT, help='Key/value pairs for monitor count overrides.') @click.pass_context def configure_monitors(ctx, monitors): """Configure system apps monitors.""" jinja_env = jinja2.Environment(loader=jinja2.PackageLoader(__name__)) if not monitors: template = jinja_env.get_template('monitors') monitors = yaml.load(template.render(**ctx.obj.__dict__)) for name, count in monitors.items(): _LOGGER.debug('%s %s', name, count) master_api.update_appmonitor( context.GLOBAL.zk.conn, name, count ) @cell_grp.command(name='configure-appgroups') @click.pass_context def configure_appgroups(ctx): """Configure system app groups.""" jinja_env = jinja2.Environment(loader=jinja2.PackageLoader(__name__)) template = jinja_env.get_template('appgroups') appgroups = yaml.load(template.render(**ctx.obj.__dict__)) admin_app_group = admin.AppGroup(context.GLOBAL.ldap.conn) for name, data in appgroups.items(): _LOGGER.debug('%s %s', name, data) try: admin_app_group.create(name, data) except ldap3.LDAPEntryAlreadyExistsResult: admin_app_group.update(name, data) existing = admin_app_group.get(name) group_cells = set(existing['cells']) group_cells.update([ctx.obj.cell]) admin_app_group.update(name, {'cells': list(group_cells)}) existing = admin_app_group.get(name) _LOGGER.debug(existing) @cell_grp.command(name='restart-apps') @click.option('--apps', type=cli.LIST, help='List of apps to restart.') @click.option('--wait', type=int, help='Interval to wait before restart.', default=20) @click.pass_context def restart_apps(ctx, wait, apps): """Restart cell API.""" jinja_env = jinja2.Environment(loader=jinja2.PackageLoader(__name__)) instance_api = instance.init(None) template = jinja_env.get_template('monitors') monitors = yaml.load(template.render(**ctx.obj.__dict__)) for name, count in monitors.items(): _, appname, _ = name.split('.') if apps and appname not in apps: continue for _idx in range(0, count): instance_id = instance_api.create(name, {}, 1) print(list(map(str, instance_id)), end='') for _sec in range(0, wait): print('.', end='') sys.stdout.flush() time.sleep(1) print('.') del clear_blackout del restart_apps del configure_apps del configure_monitors del configure_appgroups return cell_grp
{ "repo_name": "gaocegege/treadmill", "path": "treadmill/cli/admin/cell.py", "copies": "1", "size": "7093", "license": "apache-2.0", "hash": -4493801197446644000, "line_mean": 30.9504504505, "line_max": 78, "alpha_frac": 0.5835330608, "autogenerated": false, "ratio": 3.8951125755079627, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4978645636307963, "avg_score": null, "num_lines": null }
"""Admin classes for the account_keeping app.""" from django.contrib import admin from . import models class BranchAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] admin.site.register(models.Branch, BranchAdmin) class AccountAdmin(admin.ModelAdmin): list_display = [ 'name', 'slug', 'currency', 'initial_amount', 'total_amount', 'branch'] list_filter = ['branch'] admin.site.register(models.Account, AccountAdmin) class InvoiceAdmin(admin.ModelAdmin): list_display = [ 'invoice_type', 'invoice_date', 'invoice_number', 'description', 'currency', 'amount_net', 'vat', 'amount_gross', 'payment_date', 'branch'] list_filter = ['invoice_type', 'currency', 'payment_date', 'branch'] date_hierarchy = 'invoice_date' search_fields = ['invoice_number', 'description'] admin.site.register(models.Invoice, InvoiceAdmin) class PayeeAdmin(admin.ModelAdmin): list_display = ['name', ] admin.site.register(models.Payee, PayeeAdmin) class CategoryAdmin(admin.ModelAdmin): list_display = ['name', ] admin.site.register(models.Category, CategoryAdmin) class TransactionAdmin(admin.ModelAdmin): list_display = [ 'transaction_date', 'parent', 'invoice_number', 'invoice', 'payee', 'description', 'category', 'currency', 'value_net', 'vat', 'value_gross', ] list_filter = ['account', 'currency', 'payee', 'category'] date_hierarchy = 'transaction_date' raw_id_fields = ['parent', 'invoice'] search_fields = [ 'invoice_number', 'invoice__invoice_number', 'description'] admin.site.register(models.Transaction, TransactionAdmin)
{ "repo_name": "bitmazk/django-account-keeping", "path": "account_keeping/admin.py", "copies": "1", "size": "1648", "license": "mit", "hash": 897250099783754500, "line_mean": 31.96, "line_max": 79, "alpha_frac": 0.6753640777, "autogenerated": false, "ratio": 3.646017699115044, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9809477315584121, "avg_score": 0.0023808922461846, "num_lines": 50 }
"""Admin classes for the aps_bom app.""" from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models class AdditionalTextAdmin(admin.ModelAdmin): list_display = ['ipn', 'text'] search_fields = ['ipn__code', 'text'] class BOMItemInline(admin.TabularInline): model = models.BOMItem class BOMAdmin(admin.ModelAdmin): list_display = ['ipn', 'description'] search_fields = ['ipn__code', 'description'] inlines = [BOMItemInline, ] class BOMItemAdmin(admin.ModelAdmin): list_display = ['ipn', 'bom', 'qty', 'unit', 'position'] search_fields = ['ipn__code', 'bom__description'] class CBOMItemInline(admin.TabularInline): model = models.CBOMItem fields = ['bom', 'consign', 'epn', 'position', 'qty', 'unit'] def get_queryset(self, request): return models.CBOMItem.objects.all().select_related( 'bom', 'epn', 'unit') class CBOMAdmin(admin.ModelAdmin): list_display = ['customer', 'description', 'html_link', 'product', 'version_date'] search_fields = ['customer__description', 'description', 'product'] inlines = [CBOMItemInline, ] class Media: js = ('aps_bom/cbom_admin.js', ) class CBOMItemAdmin(admin.ModelAdmin): list_display = ['bom', 'epn', 'qty', 'unit', 'position'] search_fields = ['bom__description', 'bom__product', 'epn'] fields = ['bom', 'consign', 'epn', 'position', 'qty', 'unit'] class CompanyAdmin(admin.ModelAdmin): list_display = ['code', 'description', 'country'] search_fields = ['country', 'code', 'description'] list_fiter = ['country', ] class CountryAdmin(admin.ModelAdmin): list_display = ['code', 'description'] search_fields = ['description'] class EPNAdmin(admin.ModelAdmin): list_display = ['company', 'description', 'epn', 'ipn', 'cpn'] search_fields = ['company__description', 'cpn__code', 'epn', 'ipn__code', 'description'] raw_id_fields = ['ipn', 'cpn'] fields = ['company', 'description', 'epn', 'ipn', 'cpn'] class IPNAdmin(admin.ModelAdmin): list_display = ['code', 'code2', 'name', 'price_group', 'shape', 'price_max'] search_fields = ['code', 'name'] list_filter = ['price_group'] def price_max(self, obj): return obj.price_max price_max.short_description = _('Price max') class PriceGroupAdmin(admin.ModelAdmin): list_display = ['code', 'rate', 'add'] class PriceMarkerAdmin(admin.ModelAdmin): list_display = ['ipn', 'price', 'date'] search_fields = ['ipn__code'] class ProductAdmin(admin.ModelAdmin): """Custom admin for the ``Product`` model.""" list_display = ('product_number', ) class ShapeAdmin(admin.ModelAdmin): list_display = ['code', 'name'] search_fields = ['code', 'name'] class TechnologyAdmin(admin.ModelAdmin): """Custom admin for the ``Technology`` model.""" list_display = ('identifier', ) class UnitAdmin(admin.ModelAdmin): list_display = ['code', 'description'] search_fields = ['code', 'description'] admin.site.register(models.AdditionalText, AdditionalTextAdmin) admin.site.register(models.BOM, BOMAdmin) admin.site.register(models.BOMItem, BOMItemAdmin) admin.site.register(models.CBOM, CBOMAdmin) admin.site.register(models.CBOMItem, CBOMItemAdmin) admin.site.register(models.Company, CompanyAdmin) admin.site.register(models.Country, CountryAdmin) admin.site.register(models.EPN, EPNAdmin) admin.site.register(models.IPN, IPNAdmin) admin.site.register(models.PriceGroup, PriceGroupAdmin) admin.site.register(models.PriceMarker, PriceMarkerAdmin) admin.site.register(models.Product, ProductAdmin) admin.site.register(models.Shape, ShapeAdmin) admin.site.register(models.Technology, TechnologyAdmin) admin.site.register(models.Unit, UnitAdmin)
{ "repo_name": "bitmazk/django-aps-bom", "path": "aps_bom/admin.py", "copies": "1", "size": "3856", "license": "mit", "hash": 4667899336587643000, "line_mean": 29.6031746032, "line_max": 77, "alpha_frac": 0.6685684647, "autogenerated": false, "ratio": 3.442857142857143, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9611425607557142, "avg_score": 0, "num_lines": 126 }
"""Admin classes for the aps_process app.""" from django.contrib import admin from . import models # ====== # Mixins # ====== class DefaultProcessAdmin(admin.ModelAdmin): """Common defaults for all admins.""" save_on_top = True exclude = ('source', 'lft', 'rght', 'lvl') class DefaultProcessTabularInline(admin.TabularInline): exclude = ('source', 'lft', 'rght', 'lvl') # ======= # Inlines # ======= class CalendarBucketInline(DefaultProcessTabularInline): model = models.CalendarBucket extra = 0 class FlowInline(DefaultProcessTabularInline): model = models.Flow raw_id_fields = ('operation', 'thebuffer', ) extra = 0 class ResourceLoadInline(DefaultProcessTabularInline): model = models.ResourceLoad raw_id_fields = ('operation', 'resource', ) extra = 0 class SetupRuleInline(DefaultProcessTabularInline): model = models.SetupRule extra = 3 exclude = ('source', ) class SubOperationInline(DefaultProcessTabularInline): model = models.SubOperation fk_name = 'operation' extra = 1 raw_id_fields = ('suboperation', ) # =========== # ModelAdmins # =========== class BufferAdmin(DefaultProcessAdmin): """Custom admin for the ``Buffer`` model.""" raw_id_fields = ('location', 'item', 'minimum_calendar', 'producing', 'owner', ) list_display = ( 'name', 'description', 'category', 'subcategory', 'location', 'item', 'onhand', 'minimum', 'minimum_calendar', 'producing', 'carrying_cost', 'source', 'lastmodified') inlines = [FlowInline] class CalendarAdmin(DefaultProcessAdmin): """Custom admin for the ``Calendar`` model.""" list_display = ( 'name', 'description', 'category', 'subcategory', 'defaultvalue', 'source', 'lastmodified') inlines = [CalendarBucketInline] class CalendarBucketAdmin(DefaultProcessAdmin): """Custom admin for the ``CalendarBucket`` model.""" raw_id_fields = ('calendar', ) list_display = ( 'id', 'startdate', 'enddate', 'value', 'priority', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'starttime', 'endtime', 'source', 'lastmodified') class FlowAdmin(DefaultProcessAdmin): """Custom admin for the ``Flow`` model.""" raw_id_fields = ('operation', 'thebuffer',) list_display = ( 'id', 'operation', 'thebuffer', 'type', 'quantity', 'effective_start', 'effective_end', 'name', 'alternate', 'priority', 'source', 'lastmodified') class ItemAdmin(DefaultProcessAdmin): """Custom admin for the ``Item`` model.""" raw_id_fields = ('operation', 'owner',) list_display = ( 'name', 'description', 'category', 'subcategory', 'operation', 'price', 'source', 'lastmodified') class LocationAdmin(DefaultProcessAdmin): """Custom admin for the ``Location`` model.""" raw_id_fields = ('available', 'owner',) list_display = ( 'name', 'description', 'category', 'subcategory', 'available', 'source', 'lastmodified') class OperationAdmin(DefaultProcessAdmin): """Custom admin for the ``Location`` model.""" raw_id_fields = ('location',) list_display = ( 'name', 'type', 'description', 'category', 'subcategory', 'location', 'setup', 'batchqty', 'batchtime', 'setup', 'setdown', 'source', 'lastmodified') inlines = [SubOperationInline, FlowInline, ResourceLoadInline] class ResourceAdmin(DefaultProcessAdmin): """Custom admin for the ``Resource`` model.""" raw_id_fields = ('maximum_calendar', 'location', 'setupmatrix', 'owner') list_display = ( 'name', 'description', 'category', 'subcategory', 'maximum', 'maximum_calendar', 'location', 'cost', 'maxearly', 'setupmatrix', 'setup', 'source', 'lastmodified') inlines = [ResourceLoadInline] class ResourceLoadAdmin(DefaultProcessAdmin): """Custom admin for the ``ResourceLoad`` model.""" raw_id_fields = ('operation', 'resource') list_display = ( 'id', 'operation', 'resource', 'quantity', 'effective_start', 'effective_end', 'name', 'alternate', 'priority', 'setup', 'search', 'source', 'lastmodified') class SetupMatrixAdmin(DefaultProcessAdmin): """Custom admin for the ``SetupMatrix`` model.""" list_display = ( 'name', 'source', 'lastmodified') inlines = [SetupRuleInline] class SubOperationAdmin(DefaultProcessAdmin): """Custom admin for the ``SubOperation`` model.""" raw_id_fields = ('operation', 'suboperation',) list_display = ( 'id', 'operation', 'priority', 'suboperation', 'effective_start', 'effective_end', 'source', 'lastmodified') # ============ # Registration # ============ admin.site.register(models.Buffer, BufferAdmin) admin.site.register(models.Calendar, CalendarAdmin) admin.site.register(models.CalendarBucket, CalendarBucketAdmin) admin.site.register(models.Flow, FlowAdmin) admin.site.register(models.Item, ItemAdmin) admin.site.register(models.Location, LocationAdmin) admin.site.register(models.Operation, OperationAdmin) admin.site.register(models.Resource, ResourceAdmin) admin.site.register(models.ResourceLoad, ResourceLoadAdmin) admin.site.register(models.SetupMatrix, SetupMatrixAdmin) admin.site.register(models.SubOperation, SubOperationAdmin)
{ "repo_name": "bitmazk/django-aps-process", "path": "aps_process/admin.py", "copies": "1", "size": "5363", "license": "mit", "hash": -540532145530826430, "line_mean": 30.5470588235, "line_max": 79, "alpha_frac": 0.6507551743, "autogenerated": false, "ratio": 3.838940586972083, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49896957612720827, "avg_score": null, "num_lines": null }
"""Admin classes for the aps_production app.""" from django.contrib import admin from . import models # Inlines ==================================================================== class OrderLineInlineAdmin(admin.TabularInline): model = models.OrderLine class OrderRunInlineAdmin(admin.TabularInline): model = models.OrderRun class ShipmentInlineAdmin(admin.TabularInline): model = models.Shipment # Admins ===================================================================== class ErrorAdmin(admin.ModelAdmin): """Custom admin for the ``Error`` model.""" list_display = ('order_run', 'error_bin', 'quantity', 'comment') raw_id_fields = ['order_run', 'error_bin'] class ErrorBinAdmin(admin.ModelAdmin): """Custom admin for the ``ErrorBin`` model.""" list_display = ('technology', 'error_code') search_fields = ['technology__identifier', 'error_code'] class OrderAdmin(admin.ModelAdmin): """Custom admin for the ``Order`` model.""" list_display = ('order_number', 'company', 'date_created', 'customer_po_number', 'customer_po_date') search_fields = ['order_number'] inlines = [OrderLineInlineAdmin] class OrderLineAdmin(admin.ModelAdmin): """Custom admin for the ``OrderLine`` model.""" list_display = ('order', 'line_no', 'product', 'quantity_ordered', 'date_requested', 'date_shipped', 'date_delivered') search_fields = ['order__order_number'] raw_id_fields = ['order'] inlines = [OrderRunInlineAdmin] class OrderRunAdmin(admin.ModelAdmin): """Custom admin for the ```` model.""" list_display = ('order_line', 'run_number', 'parent', 'ipn', 'quantity_started', 'quantity_dest_out', 'quantity_out', 'is_open', 'comment') list_filter = ['is_open'] search_fields = ['run_number'] raw_id_fields = ['order_line'] inlines = [ShipmentInlineAdmin] class ShipmentAdmin(admin.ModelAdmin): """Custom admin for the ``Shipment`` model.""" list_display = ('order_run', 'quantity', 'date_shipped') raw_id_fields = ['order_run'] admin.site.register(models.Error, ErrorAdmin) admin.site.register(models.ErrorBin, ErrorBinAdmin) admin.site.register(models.Order, OrderAdmin) admin.site.register(models.OrderLine, OrderLineAdmin) admin.site.register(models.OrderRun, OrderRunAdmin) admin.site.register(models.Shipment, ShipmentAdmin)
{ "repo_name": "bitmazk/django-aps-production", "path": "aps_production/admin.py", "copies": "1", "size": "2429", "license": "mit", "hash": -7805121339685258000, "line_mean": 31.8243243243, "line_max": 78, "alpha_frac": 0.6311239193, "autogenerated": false, "ratio": 3.831230283911672, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9962354203211672, "avg_score": 0, "num_lines": 74 }
"""Admin classes for the cmsplugin_accordion app.""" from django.contrib import admin from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from cms.admin.placeholderadmin import PlaceholderAdmin from . import models # ADMIN INLINES =============================================================== # ============================================================================= class AccordionRowInline(admin.TabularInline): model = models.AccordionRow exclude = ['content', ] fields = ['title', 'content_link', 'position', ] readonly_fields = ['content_link', ] def content_link(self, obj): if not obj.pk: return _('Please save first...') url = reverse( 'admin:cmsplugin_accordion_accordionrow_change', args=[obj.pk, ]) link = '<a href="{0}" target="_blank">Edit content</a>'.format(url) return mark_safe(link) # MODEL ADMINS ================================================================ # ============================================================================= class AccordionPluginAdmin(admin.ModelAdmin): list_display = ['name', ] search_fields = ['name', ] inlines = [AccordionRowInline, ] class AccordionRowAdmin(PlaceholderAdmin): list_display = ['title', 'accordion__name', 'position', ] list_editable = ['position', ] list_filter = ['accordion', ] search_fields = ['title', 'accordion__name', ] def accordion__name(self, obj): return obj.accordion.name accordion__name.short_description = _('Accordion') admin.site.register(models.AccordionPlugin, AccordionPluginAdmin) admin.site.register(models.AccordionRow, AccordionRowAdmin)
{ "repo_name": "bitmazk/cmsplugin-accordion", "path": "cmsplugin_accordion/admin.py", "copies": "1", "size": "1772", "license": "mit", "hash": 5602608279828163000, "line_mean": 35.1632653061, "line_max": 79, "alpha_frac": 0.5744920993, "autogenerated": false, "ratio": 4, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.50744920993, "avg_score": null, "num_lines": null }
"""Admin classes for the ``cmsplugin_blog_categories`` app.""" from django.contrib import admin from django.utils.translation import get_language from django.utils.translation import ugettext_lazy as _ from cmsplugin_blog.admin import EntryAdmin from simple_translation.admin import TranslationAdmin from simple_translation.utils import get_preferred_translation_from_lang from cmsplugin_blog_categories.models import Category, EntryCategory class EntryCategoryInline(admin.TabularInline): model = EntryCategory extra = 1 class EntryCategoryAdmin(admin.ModelAdmin): list_display = ['entry_title', 'category_title', ] def category_title(self, obj): """Returns the best available translation for the category title.""" return obj.category.get_translation().title category_title.short_description = _('Category') def entry_title(self, obj): """Returns the best available translation for the entry title.""" lang = get_language() entry_title = get_preferred_translation_from_lang(obj.entry, lang) return entry_title.title entry_title.short_description = _('Entry title') class CategoryAdmin(TranslationAdmin): list_display = ['title', 'languages', ] def title(self, obj): """Returns the best available translation for the catrgory title.""" return obj.get_translation().title title.short_description = _('Title') # Enhance original EntryAdmin EntryAdmin.inlines = EntryAdmin.inlines[:] + [EntryCategoryInline] # Register our own admins admin.site.register(Category, CategoryAdmin) admin.site.register(EntryCategory, EntryCategoryAdmin)
{ "repo_name": "bitmazk/cmsplugin-blog-categories", "path": "cmsplugin_blog_categories/admin.py", "copies": "1", "size": "1650", "license": "mit", "hash": -6263307522640065000, "line_mean": 33.375, "line_max": 76, "alpha_frac": 0.7375757576, "autogenerated": false, "ratio": 4.274611398963731, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.551218715656373, "avg_score": null, "num_lines": null }
"""Admin classes for the ``cmsplugin_blog_language_publish`` app.""" from django.contrib import admin from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import get_language from django.utils.translation import ugettext_lazy as _ from cmsplugin_blog.models import Entry from cmsplugin_blog.admin import EntryAdmin, EntryForm from simple_translation.translation_pool import translation_pool from simple_translation.utils import get_preferred_translation_from_lang from .models import EntryLanguagePublish class EntryLanguagePublishAdmin(admin.ModelAdmin): """ Admin for the ``EntryLanguagePublish`` model. Mainly used for debugging purposes. You would rather set the publish flag when editing a blog entry via the EntryAdmin. """ list_display = ( 'title', 'language', 'is_published') def title(self, obj): return obj.entry_title.title def language(self, obj): return obj.entry_title.language class CustomEntryForm(EntryForm): """ Custom form for the ``Entry`` model, used by the ``EntryAdmin``. This is quite a hack. We will always set the `is_published` of the Entry model to true and we will override the initial value for the `is_published` field with the corresponding value of a ``EntryLanguagePublish`` object. """ def __init__(self, *args, **kwargs): super(CustomEntryForm, self).__init__(*args, **kwargs) model = self._meta.model info = translation_pool.get_info(model) self.current_language = self.base_fields[info.language_field].initial title = None if self.instance and self.instance.pk: try: title = self.instance.entrytitle_set.get( language=self.current_language) except ObjectDoesNotExist: pass publish = None if title: try: publish = EntryLanguagePublish.objects.get( entry_title=title) except EntryLanguagePublish.DoesNotExist: pass self.initial['is_published'] = ( publish and publish.is_published or False) def save(self, *args, **kwargs): """ Setting ``is_published`` of the ``Entry`` always to ``True``. Since we no longer use this field in the admin, we will just always set it to true. """ self.instance.is_published = True return super(CustomEntryForm, self).save(*args, **kwargs) class CustomEntryAdmin(EntryAdmin): """ Custom admin for the ``Entry`` model. """ form = CustomEntryForm list_display = ('title', 'languages', 'author', 'pub_date', 'is_published_lang') list_editable = () list_filter = ('pub_date', ) def title(self, obj): lang = get_language() return get_preferred_translation_from_lang(obj, lang).title def is_published_lang(self, obj): """ This is a copy from the ``is_pubished`` method of the ``MultilingualPublishMixin``. Only providing the mixin and adding ``is_published`` would have resulted in adding the entry's field to the list instead of using the mixin version. """ languages = '' for trans in obj.translations: if trans.is_published: if languages == '': languages = trans.language else: languages += ', {0}'.format(trans.language) if languages == '': return _('Not published') return languages is_published_lang.short_description = _('Is published') def save_model(self, request, obj, form, change): """ Creating the ``EntryLanguagePublish`` model after saving the ``Entry``. Unfortunately this can't be done in the form's ``save()`` method. The admin only creates the ``EntryTitle`` object in this method. Therefore we override it and create our ``EntryLanguagePublish`` model here. """ super(CustomEntryAdmin, self).save_model(request, obj, form, change) title = obj.entrytitle_set.get(language=form.current_language) published, created = EntryLanguagePublish.objects.get_or_create( entry_title=title) published.is_published = form.cleaned_data.get('is_published') published.save() admin.site.unregister(Entry) admin.site.register(Entry, CustomEntryAdmin) admin.site.register(EntryLanguagePublish, EntryLanguagePublishAdmin)
{ "repo_name": "bitmazk/cmsplugin-blog-language-publish", "path": "cmsplugin_blog_language_publish/admin.py", "copies": "1", "size": "4578", "license": "mit", "hash": 4378378224128685600, "line_mean": 33.1641791045, "line_max": 79, "alpha_frac": 0.6376146789, "autogenerated": false, "ratio": 4.410404624277457, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 134 }
"""Admin classes for the ``django-crowdsourced-fields`` app.""" from django.contrib import admin from crowdsourced_fields.models import ( CrowdsourcedItem, CrowdsourcedItemGenericForeignKey, ) def approve_items(modeladmin, request, queryset): queryset.update(is_user_generated=False) approve_items.short_description = "Approve selected items" class CrowdsourcedItemAdmin(admin.ModelAdmin): list_display = ('item_type', 'value', 'is_user_generated', ) list_filter = ('item_type', 'is_user_generated', ) search_fields = ['value', ] actions = [approve_items] class CrowdsourcedItemGenericForeignKeyAdmin(admin.ModelAdmin): list_display = ('item_type', 'item', 'content_type', 'object_id', 'field_name') list_filter = ('item_type', 'item__is_user_generated', 'field_name') search_fields = ['item__value', ] actions = [approve_items] admin.site.register(CrowdsourcedItem, CrowdsourcedItemAdmin) admin.site.register( CrowdsourcedItemGenericForeignKey, CrowdsourcedItemGenericForeignKeyAdmin)
{ "repo_name": "bitmazk/django-crowdsourced-fields", "path": "crowdsourced_fields/admin.py", "copies": "1", "size": "1063", "license": "mit", "hash": -4590010123393487400, "line_mean": 32.21875, "line_max": 78, "alpha_frac": 0.7187206021, "autogenerated": false, "ratio": 3.3961661341853033, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4614886736285303, "avg_score": null, "num_lines": null }
"""Admin classes for the ``document_library`` app.""" from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from django.utils.translation import ugettext_lazy as _ from cms.admin.placeholderadmin import PlaceholderAdminMixin from hvad.admin import TranslatableAdmin from . import models class MulilingualModelAdmin(PlaceholderAdminMixin, TranslatableAdmin): pass class AttachmentInline(GenericTabularInline): model = models.Attachment extra = 1 raw_id_fields = ['document', ] class DocumentAdmin(MulilingualModelAdmin): """Admin class for the ``Document`` model.""" list_display = [ 'get_title', 'category', 'position', 'user', 'is_on_front_page', 'all_translations', 'get_is_published', ] list_select_related = [] def get_title(self, obj): return obj.title get_title.short_description = _('Title') def get_is_published(self, obj): return obj.is_published get_is_published.short_description = _('Is published') get_is_published.boolean = True class DocumentCategoryAdmin(MulilingualModelAdmin): """Admin class for the ``DocumentCategory`` model.""" list_display = ['get_title', 'all_translations', 'is_published'] def get_title(self, obj): return obj.title get_title.short_description = _('Title') admin.site.register(models.Document, DocumentAdmin) admin.site.register(models.DocumentCategory, DocumentCategoryAdmin)
{ "repo_name": "bitmazk/django-document-library", "path": "document_library/admin.py", "copies": "1", "size": "1487", "license": "mit", "hash": -5794375646204317000, "line_mean": 28.74, "line_max": 72, "alpha_frac": 0.7148621385, "autogenerated": false, "ratio": 3.9028871391076114, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5117749277607612, "avg_score": null, "num_lines": null }
"""Admin classes for the freckle_budgets app.""" from django.contrib import admin from . import models class EmployeeAdmin(admin.ModelAdmin): list_display = ['name', 'freckle_id'] class EmployeeProjectMonthAdmin(admin.ModelAdmin): list_display = ['project_month', 'employee', 'responsibility'] raw_id_fields = ['project_month'] class EmployeeProjectMonthInline(admin.TabularInline): model = models.EmployeeProjectMonth class FreeTimeAdmin(admin.ModelAdmin): list_display = ['employee', 'day', 'is_sick_leave', 'is_public_holiday'] list_filter = ['employee', ] class MonthAdmin(admin.ModelAdmin): list_display = ['year', 'month', 'employees', 'public_holidays'] class ProjectAdmin(admin.ModelAdmin): list_display = ['name', 'freckle_project_id', 'color', 'is_investment'] class ProjectMonthAdmin(admin.ModelAdmin): list_display = [ 'month', 'project', 'budget', 'overhead_previous_month', 'rate'] list_filter = ['project', ] inlines = [EmployeeProjectMonthInline, ] class YearAdmin(admin.ModelAdmin): list_display = ['year', 'sick_leave_days', 'vacation_days'] admin.site.register(models.Employee, EmployeeAdmin) admin.site.register(models.EmployeeProjectMonth, EmployeeProjectMonthAdmin) admin.site.register(models.FreeTime, FreeTimeAdmin) admin.site.register(models.Month, MonthAdmin) admin.site.register(models.Project, ProjectAdmin) admin.site.register(models.ProjectMonth, ProjectMonthAdmin) admin.site.register(models.Year, YearAdmin)
{ "repo_name": "bitmazk/django-freckle-budgets", "path": "freckle_budgets/admin.py", "copies": "1", "size": "1515", "license": "mit", "hash": 3702009892695777300, "line_mean": 29.3, "line_max": 76, "alpha_frac": 0.7359735974, "autogenerated": false, "ratio": 3.598574821852732, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4834548419252732, "avg_score": null, "num_lines": null }
"""Admin classes for the ``generic_positions`` app.""" from django.contrib import admin from django.contrib.contenttypes.models import ContentType from .models import ObjectPosition class GenericPositionsAdmin(admin.ModelAdmin): """Admin to let models be dragged & dropped with jQuery UI sortable.""" change_list_template = 'generic_positions/admin/change_list.html' class Media: js = ( '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js', 'generic_positions/js/reorder.js', ) def save_model(self, request, obj, form, change): """Add an ObjectPosition to the object.""" super(GenericPositionsAdmin, self).save_model(request, obj, form, change) c_type = ContentType.objects.get_for_model(obj) try: ObjectPosition.objects.get(content_type__pk=c_type.id, object_id=obj.id) except ObjectPosition.DoesNotExist: position_objects = ObjectPosition.objects.filter( content_type__pk=c_type.id, position__isnull=False).order_by( '-position') try: position = (position_objects[0].position + 1) except IndexError: position = 1 ObjectPosition.objects.create( content_object=obj, position=position)
{ "repo_name": "bitmazk/django-generic-positions", "path": "generic_positions/admin.py", "copies": "1", "size": "1511", "license": "mit", "hash": 3046600870338922500, "line_mean": 40.9722222222, "line_max": 79, "alpha_frac": 0.5936465917, "autogenerated": false, "ratio": 4.292613636363637, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5386260228063637, "avg_score": null, "num_lines": null }
"""Admin classes for the ``good_practice_examples`` app.""" from django.contrib import admin from django.utils.translation import ugettext_lazy as _ try: from cms.admin.placeholderadmin import FrontendEditableAdmin except ImportError: class Object(object): pass FrontendEditableAdmin = Object from cms.admin.placeholderadmin import PlaceholderAdmin from hvad.admin import TranslatableAdmin from .models import ( Country, Goal, GoodPracticeExample, Sector, ) class GoalAdmin(TranslatableAdmin): """Admin class for the ``Goal`` model.""" list_display = ['get_name', 'all_translations'] def get_name(self, obj): return obj.name get_name.short_description = _('Name') class GoodPracticeExampleAdmin(FrontendEditableAdmin, PlaceholderAdmin, TranslatableAdmin): """Admin class for the ``GoodPracticeExample`` model.""" list_display = ['get_title', 'all_translations', 'get_is_published'] list_filter = ('goals', 'sectors', 'countries') def get_title(self, obj): return obj.title get_title.short_description = _('Title') def get_is_published(self, obj): return obj.is_published get_is_published.short_description = _('Is published') get_is_published.boolean = True class SectorAdmin(TranslatableAdmin): """Admin class for the ``Sector`` model.""" list_display = ['get_name', 'all_translations'] def get_name(self, obj): return obj.name get_name.short_description = _('Name') admin.site.register(Country) admin.site.register(Goal, GoalAdmin) admin.site.register(GoodPracticeExample, GoodPracticeExampleAdmin) admin.site.register(Sector, SectorAdmin)
{ "repo_name": "bitmazk/django-good-practice-examples", "path": "good_practice_examples/admin.py", "copies": "1", "size": "1720", "license": "mit", "hash": 1077182274018653000, "line_mean": 27.6666666667, "line_max": 72, "alpha_frac": 0.6936046512, "autogenerated": false, "ratio": 3.6909871244635193, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9884591775663519, "avg_score": 0, "num_lines": 60 }
"""Admin classes for the ``hero_slider`` app.""" from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from hvad.admin import TranslatableAdmin from . import models class SliderItemCategoryAdmin(TranslatableAdmin): """Admin for the ``SliderItemCategory`` model.""" list_display = ['slug', 'get_name', 'all_translations'] def get_name(self, obj): return obj.name get_name.short_description = _('Name') class SliderItemAdmin(TranslatableAdmin): """Admin for the ``SliderItem`` model.""" list_display = ['get_title', 'position', 'all_translations', 'get_is_published'] list_editable = ['position', ] def get_title(self, obj): return obj.title get_title.short_description = _('Title') def get_is_published(self, obj): return obj.is_published get_is_published.short_description = _('Is published') get_is_published.boolean = True admin.site.register(models.SliderItem, SliderItemAdmin) admin.site.register(models.SliderItemCategory, SliderItemCategoryAdmin)
{ "repo_name": "bitmazk/django-hero-slider", "path": "hero_slider/admin.py", "copies": "1", "size": "1091", "license": "mit", "hash": -2534795197714280400, "line_mean": 29.3055555556, "line_max": 71, "alpha_frac": 0.6892758937, "autogenerated": false, "ratio": 3.8013937282229966, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9990669621922996, "avg_score": 0, "num_lines": 36 }
"""Admin classes for the image_collection app.""" from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from generic_positions.admin import GenericPositionsAdmin from . import models class ImageInline(admin.TabularInline): model = models.ImageSlide class ImageCollectionAdmin(admin.ModelAdmin): """Custom admin for the ``ImageCollection`` model.""" list_display = ('identifier', 'name') inlines = [ImageInline] class ImageSlideAdmin(GenericPositionsAdmin): """Custom admin for the ``ImageSlide`` model.""" change_list_template = 'image_collection/admin/change_list.html' list_display = ( 'collection', 'get_headline', 'get_caption', 'image', 'image_mobile') list_filter = ['collection'] def get_caption(self, obj): return obj.caption get_caption.short_description = _('description') def get_headline(self, obj): return obj.caption_headline get_headline.short_description = _('headline') admin.site.register(models.ImageSlide, ImageSlideAdmin) admin.site.register(models.ImageCollection, ImageCollectionAdmin)
{ "repo_name": "bitmazk/django-image-collection", "path": "image_collection/admin.py", "copies": "1", "size": "1128", "license": "mit", "hash": 4534780779256254000, "line_mean": 29.4864864865, "line_max": 77, "alpha_frac": 0.7225177305, "autogenerated": false, "ratio": 4.01423487544484, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.523675260594484, "avg_score": null, "num_lines": null }
"""Admin classes for the ``multilingual_event`` app.""" from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from hvad.admin import TranslatableAdmin from .models import Event, EventCategory class EventCategoryAdmin(TranslatableAdmin): """Admin class for the ``EventCategory`` model.""" list_display = ['get_title', 'all_translations', ] list_select_related = [] def get_title(self, obj): return obj.title get_title.short_description = _('Title') class EventAdmin(TranslatableAdmin): """Admin class for the ``Event`` model.""" list_display = ['get_title', 'start_date', 'user', 'all_translations', 'get_is_published'] list_select_related = [] def get_title(self, obj): return obj.title get_title.short_description = _('Title') def get_is_published(self, obj): return obj.is_published get_is_published.short_description = _('Is published') get_is_published.boolean = True admin.site.register(Event, EventAdmin) admin.site.register(EventCategory, EventCategoryAdmin)
{ "repo_name": "bitmazk/django-multilingual-events", "path": "multilingual_events/admin.py", "copies": "1", "size": "1108", "license": "mit", "hash": 1244404370589280500, "line_mean": 28.9459459459, "line_max": 74, "alpha_frac": 0.6814079422, "autogenerated": false, "ratio": 3.8339100346020762, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5015317976802076, "avg_score": null, "num_lines": null }
"""Admin classes for the ``multilingual_initiatives`` app.""" from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from hvad.admin import TranslatableAdmin from .models import Initiative, InitiativePersonRole class InitiativePersonRoleInline(admin.TabularInline): """Inline admin for ``InitiativePersonRole`` objects.""" model = InitiativePersonRole class InitiativeAdmin(TranslatableAdmin): """Admin for the ``Initiative`` model.""" inlines = [InitiativePersonRoleInline] list_display = ['get_title', 'phone', 'website', 'start_date', 'end_date', 'description_short', 'organization', 'get_is_published'] def get_title(self, obj): return obj.title get_title.short_description = _('Title') def get_is_published(self, obj): return obj.is_published get_is_published.short_description = _('Title') get_is_published.boolean = True def description_short(self, obj): if len(obj.description) > 40: return obj.description[:40] return obj.description description_short.short_description = _('Description') admin.site.register(Initiative, InitiativeAdmin)
{ "repo_name": "bitmazk/django-multilingual-initiatives", "path": "multilingual_initiatives/admin.py", "copies": "1", "size": "1204", "license": "mit", "hash": -5416732842444130000, "line_mean": 31.5405405405, "line_max": 78, "alpha_frac": 0.6968438538, "autogenerated": false, "ratio": 3.960526315789474, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5157370169589474, "avg_score": null, "num_lines": null }
"""Admin classes for the ``multilingual_news`` app.""" from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from cms.admin.placeholderadmin import PlaceholderAdminMixin from document_library.admin import AttachmentInline from hvad.admin import TranslatableAdmin from multilingual_tags.admin import TaggedItemInline from .models import Category, NewsEntry class CategoryAdmin(TranslatableAdmin): list_display = ['get_title', 'hide_on_list', 'all_translations', ] def get_title(self, obj): return obj.title get_title.short_description = _('Title') class NewsEntryAdmin(PlaceholderAdminMixin, TranslatableAdmin): """Admin class for the ``NewsEntry`` model.""" inlines = [AttachmentInline, TaggedItemInline] list_display = [ 'get_title', 'pub_date', 'get_is_published', 'get_categories', 'all_translations'] # prepopulated_fields = {'slug': ('title', )} def get_is_published(self, obj): return obj.is_published get_is_published.short_description = _('Is published') def get_title(self, obj): return obj.title get_title.short_description = _('Title') def get_categories(self, obj): return ', '.join(str(c.title) for c in obj.categories.all()) get_title.short_description = _('Categories') admin.site.register(Category, CategoryAdmin) admin.site.register(NewsEntry, NewsEntryAdmin)
{ "repo_name": "bitmazk/django-multilingual-news", "path": "multilingual_news/admin.py", "copies": "1", "size": "1424", "license": "mit", "hash": 4449171642599741000, "line_mean": 32.1162790698, "line_max": 70, "alpha_frac": 0.7099719101, "autogenerated": false, "ratio": 3.7872340425531914, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49972059526531915, "avg_score": null, "num_lines": null }
"""Admin classes for the multilingual_survey app.""" from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from generic_positions.admin import GenericPositionsAdmin from hvad.admin import TranslatableAdmin from . import models class SurveyAdmin(TranslatableAdmin): """Custom admin for the ``Survey`` model.""" list_display = ['get_title', 'slug'] def get_title(self, obj): return obj.__str__() get_title.short_description = _('Title') class SurveyQuestionAdmin(GenericPositionsAdmin, TranslatableAdmin): """Custom admin for the ``SurveyQuestion`` model.""" list_display = ['get_title', 'get_survey', 'slug', 'is_multi_select', 'has_other_field', 'required'] def get_title(self, obj): return obj.__str__() get_title.short_description = _('Title') def get_survey(self, obj): return obj.survey get_survey.short_description = _('Survey') class SurveyAnswerAdmin(GenericPositionsAdmin, TranslatableAdmin): """Custom admin for the ``SurveyAnswer`` model.""" list_display = ['get_title', 'slug', 'get_question'] def get_title(self, obj): return obj.__str__() get_title.short_description = _('Title') def get_question(self, obj): return obj.question get_question.short_description = _('Question') class SurveyResponseAdmin(admin.ModelAdmin): """Custom admin for the ``SurveyResponse`` model.""" list_display = ['user_email', 'question', 'get_answer', 'date_created'] def get_answer(self, obj): answer_string = '' for answer in obj.answer.all(): if answer_string == '': answer_string += answer.__str__() else: answer_string += u', {0}'.format(answer.__str__()) if obj.other_answer: if answer_string == '': answer_string += obj.other_answer else: answer_string += u', *{0}'.format(obj.other_answer) return answer_string[:30] get_answer.short_description = _('Answer') def user_email(self, obj): return obj.user.email if obj.user else 'Anonymous' user_email.short_description = _('User') admin.site.register(models.SurveyResponse, SurveyResponseAdmin) admin.site.register(models.SurveyAnswer, SurveyAnswerAdmin) admin.site.register(models.SurveyQuestion, SurveyQuestionAdmin) admin.site.register(models.Survey, SurveyAdmin)
{ "repo_name": "bitmazk/django-multilingual-survey", "path": "multilingual_survey/admin.py", "copies": "1", "size": "2467", "license": "mit", "hash": -2798026891399881000, "line_mean": 32.3378378378, "line_max": 75, "alpha_frac": 0.644507499, "autogenerated": false, "ratio": 4.00487012987013, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.514937762887013, "avg_score": null, "num_lines": null }
"""Admin classes for the multilingual_tags app.""" from django import forms from django.contrib import admin from django.contrib.contenttypes.admin import ( BaseGenericInlineFormSet, GenericTabularInline, ) from django.utils.translation import ugettext_lazy as _ from hvad.admin import TranslatableAdmin from . import models class TaggedItemInlineFormSet(BaseGenericInlineFormSet): model = models.TaggedItem def clean(self): cleaned_data = super(TaggedItemInlineFormSet, self).clean() # validate, that every tag is only used once tags = [] for i in range(0, self.total_form_count()): tags.append(self.data.get('{0}-{1}-tag'.format(self.prefix, i))) if len(tags) != len(set(tags)): raise forms.ValidationError(_( 'A Tag may only exist once per object.')) return cleaned_data class TaggedItemInline(GenericTabularInline): formset = TaggedItemInlineFormSet model = models.TaggedItem extra = 1 admin.site.register(models.Tag, TranslatableAdmin) admin.site.register(models.TaggedItem)
{ "repo_name": "bitmazk/django-multilingual-tags", "path": "multilingual_tags/admin.py", "copies": "1", "size": "1105", "license": "mit", "hash": -378903146150117400, "line_mean": 28.8648648649, "line_max": 76, "alpha_frac": 0.7022624434, "autogenerated": false, "ratio": 4.092592592592593, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5294855035992593, "avg_score": null, "num_lines": null }
"""Admin classes for the ``people`` app.""" from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from hvad.admin import TranslatableAdmin from . import models class NationalityAdmin(TranslatableAdmin): """Admin for the ``Nationality`` model.""" list_display = ['get_name', 'all_translations'] def get_name(self, obj): return obj.name get_name.short_description = _('Name') class LinkAdmin(admin.ModelAdmin): """Admin for the ``Link`` model.""" list_display = ['person', 'link_type', 'url', ] class LinkInline(admin.TabularInline): """Inline admin for ``Link`` objects.""" model = models.Link class LinkTypeAdmin(TranslatableAdmin): """Admin for the ``LinkType`` model.""" list_display = ['get_name', 'ordering', 'all_translations', ] def get_name(self, obj): return obj.name get_name.short_description = _('Name') class PersonAdmin(TranslatableAdmin): """Admin for the ``Person`` model.""" inlines = [LinkInline, ] list_display = [ 'roman_first_name', 'roman_last_name', 'non_roman_first_name_link', 'non_roman_last_name', 'chosen_name', 'gender', 'title', 'role', 'phone', 'email', 'ordering', 'all_translations', ] def non_roman_first_name_link(self, obj): return u'<a href="{0}/">{1}</a>'.format( obj.pk, unicode(obj.non_roman_first_name)) non_roman_first_name_link.allow_tags = True non_roman_first_name_link.short_description = "Non roman first name" class RoleAdmin(TranslatableAdmin): """Admin for the ``Role`` model.""" list_display = ['get_name', 'all_translations', ] def get_name(self, obj): return obj.name get_name.short_description = _('Name') admin.site.register(models.Nationality, NationalityAdmin) admin.site.register(models.Link, LinkAdmin) admin.site.register(models.LinkType, LinkTypeAdmin) admin.site.register(models.Person, PersonAdmin) admin.site.register(models.Role, RoleAdmin)
{ "repo_name": "chayapan/django-people", "path": "people/admin.py", "copies": "1", "size": "2016", "license": "mit", "hash": 1237979528577752600, "line_mean": 29.5454545455, "line_max": 75, "alpha_frac": 0.6641865079, "autogenerated": false, "ratio": 3.518324607329843, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46825111152298426, "avg_score": null, "num_lines": null }
"""Admin classes for the review app.""" from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from hvad.admin import TranslatableAdmin from . import models class RatingAdmin(admin.ModelAdmin): list_display = ['review', 'category', 'value', ] raw_id_fields = ['review', ] class ReviewAdmin(admin.ModelAdmin): list_display = ['reviewed_item', 'user', 'language', 'creation_date'] class ReviewExtraInfoAdmin(admin.ModelAdmin): list_display = ['type', 'review', 'content_object'] class ReviewCategoryChoiceAdmin(TranslatableAdmin): list_display = ['ratingcategory', 'value', 'get_label'] list_select_related = [] def get_label(self, obj): return obj.label get_label.short_description = _('Label') admin.site.register(models.Rating, RatingAdmin) admin.site.register(models.RatingCategory, TranslatableAdmin) admin.site.register(models.Review, ReviewAdmin) admin.site.register(models.ReviewExtraInfo, ReviewExtraInfoAdmin) admin.site.register(models.RatingCategoryChoice, ReviewCategoryChoiceAdmin)
{ "repo_name": "bitmazk/django-review", "path": "review/admin.py", "copies": "1", "size": "1081", "license": "mit", "hash": 8040484256606432000, "line_mean": 29.0277777778, "line_max": 75, "alpha_frac": 0.7456059204, "autogenerated": false, "ratio": 3.7275862068965515, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4973192127296551, "avg_score": null, "num_lines": null }
"""Admin code for django_bouncy app""" from django.contrib import admin from django_bouncy.models import Bounce, Complaint, Delivery class BounceAdmin(admin.ModelAdmin): """Admin model for 'Bounce' objects""" list_display = ( 'address', 'mail_from', 'bounce_type', 'bounce_subtype', 'status') list_filter = ( 'hard', 'action', 'bounce_type', 'bounce_subtype', 'feedback_timestamp' ) search_fields = ('address',) class ComplaintAdmin(admin.ModelAdmin): """Admin model for 'Complaint' objects""" list_display = ('address', 'mail_from', 'feedback_type') list_filter = ('feedback_type', 'feedback_timestamp') search_fields = ('address',) class DeliveryAdmin(admin.ModelAdmin): """Admin model for 'Delivery' objects""" list_display = ('address', 'mail_from') list_filter = ('feedback_timestamp',) search_fields = ('address',) admin.site.register(Bounce, BounceAdmin) admin.site.register(Complaint, ComplaintAdmin) admin.site.register(Delivery, DeliveryAdmin)
{ "repo_name": "ofa/django-bouncy", "path": "django_bouncy/admin.py", "copies": "1", "size": "1040", "license": "mit", "hash": -979335700205615900, "line_mean": 28.7142857143, "line_max": 74, "alpha_frac": 0.6740384615, "autogenerated": false, "ratio": 3.5494880546075085, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47235265161075085, "avg_score": null, "num_lines": null }
#AdminComamnds.py import sys import datetime, time ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') def consolelog(name, content, db): print("User: " + name + " ran command: " + content + " at: " + st) def exitbot(client, message, db): cur = db.cursor() client.send_message(message.channel, 'Discord Bot Stopping') consolelog(message.author.name, str(message.content)) sys.exit(0) def word(client, message, db): cur = db.cursor() commandline = str(message.content).split(" ") print commandline[1] if commandline[1] == "list": cur.execute("SELECT * FROM links") rows = cur.fetchall() keywords = [] for i in rows: keywords.append(str(i[0])) keywords = str(', '.join(keywords)) client.send_message(message.channel, keywords ) return() if commandline[1] == "add": print("Attempting to add: " + commandline[2] + " To URL: " + commandline[3]) try: cur.execute('''INSERT INTO links (word,url) VALUES (?,?)''', (commandline[2], commandline[3])) db.commit() client.send_message(message.channel, "Adding Keyword: " + commandline[2]) print("User: " + message.author.name + "Added keyword: " + commandline[2] + " That has URL: " + commandline[3] + " At: " + str(st)) except: client.send_message(message.channel, 'Unable to add keyword: %s' % commandline[2]) return() if commandline[1] == "remove": cur.execute("SELECT * FROM links") rows = cur.fetchall() keywords = [] for i in rows: keywords.append(str(i[0])) if commandline[2] in keywords: try: client.send_message(message.channel, "Deleting Keyword: " + commandline[2]) print("User: " + message.author.name + "Deleted keyword: " + commandline[2] + " At: " + str(st)) cur.execute("DELETE FROM links WHERE word = ?", (commandline[2],)) db.commit() except: client.send_message(message.channel, 'Unable to delete keyword: %s' % commandline[2]) else: client.send_message(message.channel, "Keyword %s not found." % commandline[2]) return() if commandline[1] == "help": client.send_message(message.channel, "Word command usage:") client.send_message(message.channel, "Command: !word list -Lists all active keywords-") client.send_message(message.channel, "Command: !word add <keyword> <url> -Adds a keyword-") client.send_message(message.channel, "Command: !word remove <keyword> -Removes a keyword-") return() else: client.send_message(message.channel, "SubCommand %s not found in command !word" % commandline[1]) adminStrings = {'!exit': exitbot, '!word': word}
{ "repo_name": "Dreggor/HammerBot", "path": "AdminCommands.py", "copies": "1", "size": "2634", "license": "bsd-2-clause", "hash": -1328251097537623000, "line_mean": 37.9090909091, "line_max": 134, "alpha_frac": 0.6495823842, "autogenerated": false, "ratio": 3.1469534050179213, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.904397207488038, "avg_score": 0.05051274286750813, "num_lines": 66 }
'''Admin commands''' import modules.commands as commands import json import discord import re import asyncio with open("database/adminweenie.json","r") as infile: admin = json.loads(infile.read()) with open("database/warn.json","r") as infile: warnings = json.loads(infile.read()) with open("database/quoteweenie.json","r") as infile: Quotes_All = json.loads(infile.read()) '''Clear/Removes a given amount of messages.''' async def clear_logic(message, client): if message.author.permissions_in(message.channel).manage_messages: try: amount = message.content.split(' ') amount_number = amount[1] amount = int(amount_number) + 1 print(message.author.name + ' cleared {} messages'.format(amount)) deleted = await client.purge_from(message.channel, limit=int(amount), check=None) await asyncio.sleep(1) tbd = await client.send_message(message.channel, 'Deleted {} message(s)'.format(len(deleted))) await asyncio.sleep(8) await client.delete_message(tbd) except ValueError: await client.send_message(message.channel, 'Error, Did you specify number?') else: await client.send_message(message.channel, 'You need manage messages permission on this server, to use this commands') commands.add_command(command_name='clear', command_function=clear_logic) async def warning_add(message, client): if message.author.permissions_in(message.channel).ban_members: if message.author.id in admin: person = re.sub('[!@<>]', '', message.content) r_person = person.split()[1] print(r_person) if r_person not in warnings.keys(): warnings[r_person] = [] warnings[r_person].append(' '.join(person.split()[1:])) with open("database/warn.json", "w+") as outfile: outfile.write(json.dumps(warnings)) x = message.server.get_member(r_person) await asyncio.sleep(1) if len(warnings[r_person]) == 1: await client.send_message(x, ' '.join(person.split()[1:])) elif len(warnings[r_person]) == 2: await client.send_message(message.server.get_member(r_person), ' '.join(person.split()[1:])) await client.send_message(message.channel, 'The next warning this person gets will result in a ban!') elif len(warnings[r_person]) == 3: await client.send_message(message.server.get_member(r_person), ' '.join(person.split()[1:])) await client.send_message(message.channel, 'Banning is not added yet! D:') else: await client.send_message(message.channel, 'You must be a bot admin to use this command!') else: await client.send_message(message.channel, '`ban_members` permission is needed for this command!') commands.add_command(command_name='warn', command_function=warning_add) async def warning_add(message, client): if message.author.permissions_in(message.channel).ban_members: if message.author.id in admin: person = re.sub('[!@<>]', '', message.content) person = person.replace(client.pfix + 'warn ', '') r_person = person.split()[0] print(r_person) if r_person not in warnings.keys(): warnings[r_person] = [] warnings[r_person].append(' '.join(person.split()[1:])) with open("database/warn.json", "w+") as outfile: outfile.write(json.dumps(warnings)) x = message.server.get_member(r_person) await asyncio.sleep(1) if len(warnings[r_person]) == 1: await client.send_message(x, ' '.join(person.split()[1:])) elif len(warnings[r_person]) == 2: await client.send_message(message.server.get_member(r_person), ' '.join(person.split()[1:])) await client.send_message(message.channel, 'The next warning this person gets will result in a ban!') elif len(warnings[r_person]) == 3: await client.send_message(message.server.get_member(r_person), ' '.join(person.split()[1:])) await client.send_message(message.channel, 'Banning is not added yet! D:') else: await client.send_message(message.channel, 'You must be a bot admin to use this command!') else: await client.send_message(message.channel, '`ban_members` permission is needed for this command!') commands.add_command(command_name='warn', command_function=warning_add) async def warning_amount(message, client): person = re.sub('[!@<>]', '', message.content) person = person.split()[1] print(person) if person in warnings.keys() and len(wanrings[person]) != 0: await client.send_message(message.channel, '```'+ '\n'.join(warnings[person])+ '```') else: await client.send_message(message.channel, 'That person has no warnings!') commands.add_command(command_name='warnings', command_function=warning_amount, alias='warns') async def clear_warning(message, client): if message.author.id in admin: person = re.sub('[!@<>]', '', message.content) person = person.split()[1] print(person) if person in warnings.keys(): warnings[person] = [] with open("database/warn.json", "w+") as outfile: outfile.write(json.dumps(warnings)) await client.send_message(message.channel,'Cleared all warnings!') else: await client.send_message(message.channel, 'That person has no warnings!') else: await client.send_message(message.channel, 'You must be a bot admin to use this command!') commands.add_command(command_name='clearwarns', command_function=clear_warning) async def admintest_logic(message, client): if str(message.author.id) in admin: await client.send_message(message.channel, 'Hello Admin!') elif str(message.author.id) not in admin: await client.send_message(message.channel, 'Not Admin!') commands.add_command(command_name='admintest', command_function=admintest_logic, alias='testadmin, admin') '''Deletes Admin.''' async def deladmin_logic(message, client): try: del_admin = str(message.content.replace(message.content.split()[0] + ' ', '')) if str(message.author.id) in admin: if del_admin in admin: deleted_admin = message.server.get_member_named(del_admin) await client.send_message(message.channel, 'Admin Removed') admin.remove(deleted_admin.id) with open("database/adminweenie.json", "w+") as outfile: outfile.write(json.dumps(admin)) else: await client.send_message(message.channel, 'ERROR {} was never an Admin!'.format('`' + del_admin + '`')) elif str(message.author.id) not in admin: await client.send_message(message.channel, 'ERROR You are not Admin. If you would like to get admin please contact ' + client.bot_info.owner) except: pass commands.add_command(command_name='deladmin', command_function=deladmin_logic, alias='admindel, removeadmin, remove_admin') '''Adds Admin.''' async def add_admin_logic(message, client): if str(message.author.id) in admin or message.author.id == client.bot_info.owner.id: username = message.content.split(' ')[1] try: msg3 = message.server.get_member_named(username) await client.send_message(message.channel, msg3.display_name + ' has been added as an admin') admin.append(msg3.id) with open("database/adminweenie.json", "w+") as outfile: outfile.write(json.dumps(admin)) except: await client.send_message(message.channel, 'Could not find user with this name, try doing name#discrim') elif str(message.author.id) not in admin: await client.send_message(message.channel, 'ERROR You are not Admin. If you would like to get admin please contact ' + client.bot_info.owner) commands.add_command(command_name='addadmin', command_function=add_admin_logic, alias='adminadd') '''Adds quote.''' async def quoteadd_logic(message, client): if str(message.author.id) in admin: msg = message.content.replace(message.content.split()[0] + ' ', '') global counter1 counter1 = len(Quotes_All) await client.send_message(message.channel, 'Quote {} Added!'.format(counter1)) counter1 counter1 = len(Quotes_All) + 1 Quotes_All.append(str(len(Quotes_All)) +': ' + msg) with open("database/quoteweenie.json", "w+") as outfile: outfile.write(json.dumps(Quotes_All)) elif str(message.author.id) not in admin: await client.send_message(message.channel, 'Only Admins can Add Quotes! If you would like to get admin please contact ' + client.bot_info.owner) commands.add_command(command_name='quoteadd', command_function=quoteadd_logic, alias='addquote') '''Edits quote.''' async def editquote_logic(message, client): e_quote = message.content.split(' ') edit_quote = int(e_quote[1]) if str(message.author.id) in admin: try: await client.send_message(message.channel, 'Editing Quote {}'.format(edit_quote)) msg = await client.wait_for_message(author=message.author) Quotes_All[edit_quote] = msg.content await client.send_message(message.channel, 'Quote Edited') with open("database/quoteweenie.json", "w+") as outfile: outfile.write(json.dumps(Quotes_All)) except IndexError: await client.send_message(message.channel, 'That quote doesn\'t exist!') elif str(message.author.id) not in admin: await client.send_message(message.channel, 'ERROR You are not Admin. If you would like to get admin contact another admin or ' + client.bot_info.owner) commands.add_command(command_name='editquote', command_function=editquote_logic, alias='quoteedit') '''Deletes quote.''' async def delquote_logic(message, client): open("database/quoteweenie.json", "r") try: del_q = message.content.split(' ') del_quote = int(del_q[1]) if str(message.author.id) in admin: try: del Quotes_All[del_quote] await client.send_message(message.channel, 'Quote {} Deleted'.format(del_quote)) with open("database/quoteweenie.json", "w+") as outfile: outfile.write(json.dumps(Quotes_All)) except IndexError: await client.send_message(message.channel, 'That quote doesn\'t exist!') elif str(message.author.id) not in admin: await client.send_message(message.channel, 'ERROR You are not Admin. If you would like to get admin please contact ' + client.bot_info.owner) except: pass commands.add_command(command_name='delquote', command_function=delquote_logic, alias='quotedel') '''Lists all admins''' async def admin_amount(message, client): names = [] ids = [] for i in admin: try: user = message.server.get_member(i) names.append(user.name) ids.append(user.id) except: names.append('**User not in current server!***') ids.append('**User not in current server!***') admin_details = discord.Embed(title='Admins', description='', colour=0x79CDCD) admin_details.add_field(name='Names:', value='\n'.join(names), inline=True) admin_details.add_field(name='ID\'s:', value='\n'.join(ids), inline=False) await client.send_message(message.channel, embed=admin_details) commands.add_command(command_name='admins', command_function=admin_amount, alias='adminlist, admin_amount') '''Purges channel of ALL messages!.''' async def purge(message, client): if str(message.author.id) in admin and message.author.permissions_in(message.channel).manage_messages: deleted = await client.purge_from(message.channel, limit=500, check=None) await asyncio.sleep(1) await client.send_message(message.channel, 'Deleted {} message(s)'.format(len(deleted))) elif str(message.author.id) not in admin: await client.send_message(message.channel, 'Only Admins can Purge channels!. If you would like to get admin please contact ' + client.bot_info.owner) commands.add_command(command_name='purge', command_function=purge, alias='nuke')
{ "repo_name": "Beefywhale/WeenieBot", "path": "modules/admin.py", "copies": "1", "size": "12589", "license": "mit", "hash": -6003198080018852000, "line_mean": 49.967611336, "line_max": 159, "alpha_frac": 0.6408769561, "autogenerated": false, "ratio": 3.8125378558449423, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9926400442582403, "avg_score": 0.005402873872507964, "num_lines": 247 }
#Admin commands v2.0.0 import discord import asyncio from discord.ext import commands from bot_globals import display_purges, server_list from checks import * class Admin(): def __init__(self, bot): self.bot = bot ## Purge messages @commands.group(pass_context=True) @prefix('$') @permission(manage_messages=True) async def purge(self, ctx): """Purge messages.""" #The user is in fact doing it wrong if ctx.invoked_subcommand is None: await self.bot.say("Usage: `$purge <all | user | role> <target>`") #Handle the actual purging async def purge_messages(self, location, message, limit, check): removed = await self.bot.purge_from(message.channel, limit=limit, before=message, check=check) #Show info about the purge if the config says so if display_purges: reply = await self.bot.say("{0} message(s) were purged from {1}." .format(len(removed), location)) await asyncio.sleep(4) await self.bot.delete_message(reply) @purge.command(pass_context=True) async def all(self, ctx, amt: int): """Remove all messages""" await self.purge_messages("everyone", ctx.message, amt, lambda e: True) @purge.command(pass_context=True) async def user(self, ctx, member: discord.Member, amt: int = 25): """Remove messages from a user""" who = member.mention await self.purge_messages(who, ctx.message, amt, lambda e: e.author == member) @purge.command(pass_context=True) async def role(self, ctx, role: discord.Role, amt: int = 25): """Remove messages from anyone with the specified role""" who = role.mention await self.purge_messages(who, ctx.message, amt, lambda e: role in e.author.roles) ## Change a user's nickname @commands.command() @prefix('$') @permission(manage_nicknames=True) async def nick(self, user: discord.Member, *, nick: str): """Change a user's nickname.""" try: #Remove nickname if the nick is set to '!none' if nick.lower() == "!none": await self.bot.change_nickname(user, None) else: await self.bot.change_nickname(user, nick) await self.bot.say("Nickname set.") except discord.Forbidden: await self.bot.say(forbidden) except discord.HTTPException as error: await bot.say("Unable to change nickname: {0}" .format(error)) ## Change the bot's status @commands.command() @prefix('$') @botmaster() async def playing(self, *, playing: str): """Change the bot's playing status.""" if playing.lower() == "!none": status = None else: status = discord.Game(name=playing) await self.bot.change_status(game=status) await self.bot.say("I'm playing {0}".format(playing)) ## Get an invite to a server the bot is connected to, if possible. @commands.command(pass_context=True) @prefix('$') @botmaster() async def inviteme(self, ctx, *, name: str): """Get an invite to a server the bot is connected to, if possible.""" for serv in server_list: if serv.name == name: try: invite = await self.bot.create_invite(serv.default_channel) await self.bot.send_message(ctx.message.author, "Invite to {0}: {1}".format(name, invite)) except HTTPException as error: await self.bot.say("Error getting invite: {0}" .format(error)) ## Make the bot leave a server @commands.command(pass_context=True) @prefix('$') @botmaster() async def leave(self, ctx): """Leave the server where this command was received""" await self.bot.say("Alright... I understand, I'm not wanted here...") await self.bot.leave_server(ctx.message.server) ## Random things go here. This changes periodically. @commands.command() @prefix('?') async def playingtest(self): """Has a varying effect depending on the bot's stage in development.""" self.bot.change_status("test") def setup(bot): bot.add_cog(Admin(bot))
{ "repo_name": "Qvalador/scorpion", "path": "run-bot/extensions/admin.py", "copies": "1", "size": "4376", "license": "mit", "hash": -8138042686970653000, "line_mean": 36.724137931, "line_max": 90, "alpha_frac": 0.5950639854, "autogenerated": false, "ratio": 3.99634703196347, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9988080155745456, "avg_score": 0.020666172323602836, "num_lines": 116 }
"""Admin configuration for Articles Article = ArticleAdmin """ from django.contrib import admin from .models import Article @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): """Admin for Articles display: title published id tags order by: date(hierarchy) id published title search: title filter: published tags modified(date) prepopulated: slug: title """ list_display = ( 'title', 'published', 'post_id', 'tags_count', ) ordering = ( '-post_id', 'published', 'title' ) search_fields = ( 'title', ) date_hierarchy = 'published' list_filter = ( 'published', 'tags', 'modified', ) filter_horizontal = ( 'tags', ) readonly_fields = ( 'post_id', ) prepopulated_fields = { "slug": ( "title", ) } view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'post_id', 'title', 'published', 'modified', ) }), ('Contents', { 'classes': ('full-width',), 'description': 'source can be selected', 'fields': ( 'body', ) }), ('Extras', { 'classes': ('collapse',), 'fields': ( 'headerimage', 'tags', 'slug', ) }), ) # future: status/draft or published/NO or publish/future # def suit_row_attributes(self, obj, request): # return {'class': 'error'} def tags_count(self, obj): """tags_count count the number of tags in Article Args: self: Admin object obj: Article object Returns: (int): no of tags Raises: None """ return obj.tags.count()
{ "repo_name": "efueger/harshp.com", "path": "articles/admin.py", "copies": "1", "size": "2098", "license": "mit", "hash": -2014707778746844700, "line_mean": 17.7321428571, "line_max": 60, "alpha_frac": 0.4313632031, "autogenerated": false, "ratio": 4.541125541125541, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 112 }
"""admin configuration for blogs """ from django.contrib import admin from .models import BlogPost @admin.register(BlogPost) class BlogPostAdmin(admin.ModelAdmin): """Admin for BlogPost display: title, published, post id, tags count order by: post id(descending) published title search: title filter: published tags modified prepopulated: tags """ list_display = ( 'title', 'published', 'post_id', 'tags_count', ) ordering = ( '-post_id', 'published', 'title' ) search_fields = ( 'title', ) date_hierarchy = 'published' list_filter = ( 'published', 'tags', 'modified', ) filter_horizontal = ( 'tags', ) readonly_fields = ( 'post_id', ) prepopulated_fields = { "slug": ( "title", ) } view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'post_id', 'title', 'published', 'modified', ) }), ('Contents', { 'classes': ('full-width',), 'description': 'source can be selected', 'fields': ( 'body', ) }), ('Extras', { 'classes': ('collapse',), 'fields': ( 'headerimage', 'tags', 'slug', ) }), ) # future: status/draft or published/NO or publish/future # def suit_row_attributes(self, obj, request): # return {'class': 'error'} def tags_count(self, obj): """tag count count the number of tags in blog post Args: self: blogpost admin object obj: blogpost object Returns: int: no of tags Raises: None """ return obj.tags.count()
{ "repo_name": "efueger/harshp.com", "path": "blog/admin.py", "copies": "1", "size": "2065", "license": "mit", "hash": 1508100513406297000, "line_mean": 17.9449541284, "line_max": 60, "alpha_frac": 0.4338983051, "autogenerated": false, "ratio": 4.46969696969697, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.540359527479697, "avg_score": null, "num_lines": null }
"""admin configuration for brainbank BrainBankIdea: BrainBankIdeaAdmin BrainBankPost: BrainBankPostAdmin BrainBankDemo: BrainBankDemoAdmin """ from django.contrib import admin from brainbank.models import BrainBankIdea from brainbank.models import BrainBankPost from brainbank.models import BrainBankDemo @admin.register(BrainBankIdea) class BrainBankIdeaAdmin(admin.ModelAdmin): """Admin for BrainBank Ideas List: ID, Title, Published, No of posts, No of demos Form: ID, Title, Published, Body Search: Title """ list_display = ( 'id', 'title', 'published', 'posts', 'demos', ) ordering = ( '-published', ) search_fields = ( 'title', ) date_hierarchy = 'published' readonly_fields = ( 'id', ) prepopulated_fields = { "slug": ( "title", ) } view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'id', 'title', 'slug', 'published' ) }), ('Contents', { 'classes': ('full-width',), 'description': 'source can be selected', 'fields': ( 'body', ) }), ) def posts(self, obj): """posts count count of posts associated with idea Args: self(BrainBankIdeaAdmin) obj(BrainBankIdea) Returns: int: no of posts associated with idea Raises: None """ return obj.brainbankpost_set.count() def demos(self, obj): """demos count count of demos associated with idea Args: self(BrainBankIdeaAdmin) obj(BrainBankIdea) Returns: int: no of demos associated with idea Raises: None """ return obj.brainbankdemo_set.count() @admin.register(BrainBankPost) class BrainBankPostAdmin(admin.ModelAdmin): """ Admin for BrainBank Posts List: ID, Title, Published, Idea Form: ID, Title, Published, Idea, Body, Tags Search: Title, Idea Filter: Idea, Tags """ list_display = ( 'id', 'title', 'published', 'idea', ) ordering = ( '-published', 'title', 'idea', ) search_fields = ( 'title', 'idea', ) date_hierarchy = 'published' list_filter = ( 'idea__title', 'tags', ) filter_horizontal = ( 'tags', ) readonly_fields = ( 'id', ) view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'id', 'title', 'published', 'slug', 'idea', ) }), ('Contents', { 'classes': ('full-width',), 'description': 'source can be selected', 'fields': ( 'body', ) }), ('Extras', { 'classes': ('collapse',), 'fields': ( 'tags', ) }), ) @admin.register(BrainBankDemo) class BrainBankDemoAdmin(admin.ModelAdmin): """ Admin for BrainBank Demos List: ID, Title, Idea Form: ID, Title, Idea, Body, CSS, JS Search: Title, Idea Filter: Idea """ list_display = ( 'id', 'title', 'idea', ) ordering = ( 'idea', 'title', ) search_fields = ( 'title', 'idea', ) list_filter = ( 'idea', ) readonly_fields = ( 'id', ) view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'id', 'title', 'slug', 'idea', ) }), ('Content', { 'classes': ('full-width',), 'description': 'source can be selected', 'fields': ( 'body', ) }), ('css', { 'classes': ('full-width',), 'fields': ( 'css', ) }), ('js', { 'classes': ('full-width',), 'fields': ( 'js', ) }), )
{ "repo_name": "efueger/harshp.com", "path": "brainbank/admin.py", "copies": "1", "size": "4417", "license": "mit", "hash": 5231088550812894000, "line_mean": 19.1689497717, "line_max": 56, "alpha_frac": 0.4349105728, "autogenerated": false, "ratio": 4.120335820895522, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 219 }
"""Admin Configuration for Improved User""" from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.utils.translation import ugettext_lazy as _ from .forms import UserChangeForm, UserCreationForm class UserAdmin(BaseUserAdmin): """Admin panel for Improved User, mimics Django's default""" fieldsets = ( (None, {"fields": ("email", "password")}), (_("Personal info"), {"fields": ("full_name", "short_name")}), ( _("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ), }, ), (_("Important dates"), {"fields": ("last_login", "date_joined")}), ) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("email", "short_name", "password1", "password2"), }, ), ) form = UserChangeForm add_form = UserCreationForm list_display = ("email", "full_name", "short_name", "is_staff") search_fields = ("email", "full_name", "short_name") ordering = ("email",)
{ "repo_name": "jambonsw/django-improved-user", "path": "src/improved_user/admin.py", "copies": "1", "size": "1257", "license": "bsd-2-clause", "hash": 5111556871163406000, "line_mean": 29.6585365854, "line_max": 76, "alpha_frac": 0.4892601432, "autogenerated": false, "ratio": 4.349480968858131, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5338741112058132, "avg_score": null, "num_lines": null }
"""admin configuration for poems Poem: PoemAdmin """ from django.contrib import admin from .models import Poem @admin.register(Poem) class PoemAdmin(admin.ModelAdmin): """Admin for Poem list: title, published, post id, tags count ordering: post id, published(hierarchy), title, search: title readonly: post id prepopulated: slug=title """ list_display = ( 'title', 'published', 'post_id', 'tags_count', ) ordering = ( '-post_id', 'published', 'title' ) search_fields = ( 'title', ) date_hierarchy = 'published' list_filter = ( 'published', 'tags', 'modified', ) filter_horizontal = ( 'tags', ) readonly_fields = ( 'post_id', ) prepopulated_fields = { "slug": ( "title", ) } view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'post_id', 'title', 'published', 'modified', ) }), ('Contents', { 'classes': ('full-width',), 'description': 'source can be selected', 'fields': ( 'body', ) }), ('Extras', { 'classes': ('collapse',), 'fields': ( 'headerimage', 'tags', 'slug', ) }), ) # future: status/draft or published/NO or publish/future # def suit_row_attributes(self, obj, request): # return {'class': 'error'} def tags_count(self, obj): """tag count count number of tags associated with poem Args: self(PoemAdmin) obj(Poem) Returns: int: no of tags Raises: None """ return obj.tags.count()
{ "repo_name": "efueger/harshp.com", "path": "poems/admin.py", "copies": "1", "size": "1953", "license": "mit", "hash": 6912991186489957000, "line_mean": 18.9285714286, "line_max": 60, "alpha_frac": 0.4439324117, "autogenerated": false, "ratio": 4.254901960784314, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5198834372484313, "avg_score": null, "num_lines": null }
"""Admin context processors.""" cached_admin_urls = [ (None, "Dashboard", "admin"), (None, "Configuration", "configuration"), (None, "Appearance", "appearance"), (None, "Members", "staff_members"), (None, "Events", "staff_events"), (None, "Emails", "staff_emails"), (None, "Backup", "backup"), ] loaded_plugins = False def admin_urls(request=None): """Return cached admin urls.""" from happening import plugins import importlib from django.conf import settings global cached_admin_urls global loaded_plugins if not loaded_plugins: loaded_plugins = True if hasattr(settings, "PLUGINS"): for plugin in settings.PLUGINS: p = importlib.import_module(plugin) if hasattr(p.Plugin, "admin_url_root") and\ hasattr(p.admin, "admin_links"): cached_admin_urls += [ (plugin, l[0], l[1]) for l in p.admin.admin_links] return {"admin_urls": [ # l[0] is for hardcoding (l[1], l[2]) for l in cached_admin_urls if l[0] is None or plugins.plugin_enabled(l[0])]}
{ "repo_name": "happeninghq/happening", "path": "src/admin/context_processors.py", "copies": "2", "size": "1163", "license": "mit", "hash": 2037102211255467300, "line_mean": 29.6052631579, "line_max": 74, "alpha_frac": 0.5726569218, "autogenerated": false, "ratio": 3.763754045307443, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5336410967107443, "avg_score": null, "num_lines": null }
"""Admin control CLI.""" # Copyright (c) Peter Parente # Distributed under the terms of the BSD 2-Clause License. import click from prettytable import PrettyTable from . import app from .model import db, User, Flock, Location @click.group() def admin(): """Admin access to BoF data.""" pass @admin.group() def user(): """Manage users.""" pass @user.command() def list(): """List all registered users.""" table = PrettyTable(['id', 'username', 'banned', 'admin']) with app.app_context(): for user in User.query.all(): table.add_row([user.id, user.username, user.banned, user.admin]) click.echo(table) def apply_ban(username, ban): with app.app_context(): user = User.query.filter_by(username=username).first() user.banned = ban db.session.commit() return user.to_dict() @user.command() @click.argument('username') def ban(username): """Ban a user.""" user = apply_ban(username, True) click.echo(user) @user.command() @click.argument('username') def unban(username): """Unban a user.""" user = apply_ban(username, False) click.echo(user) @admin.group() def flock(): """Manage flocks.""" pass @flock.command() def list(): """List all flocks.""" table = PrettyTable(['id', 'name', 'leader', 'birds']) with app.app_context(): for flock in Flock.query.all(): table.add_row([flock.id, flock.name, flock.leader.username, len(flock.birds)]) click.echo(table) @flock.command() @click.argument('id') @click.confirmation_option(prompt='Are you sure you want to delete the flock?') def remove(id): """Remove a flock.""" with app.app_context(): flock = Flock.query.get(id) db.session.delete(flock) db.session.commit() @flock.command() @click.argument('id') def edit(id): """Edit a flock.""" with app.app_context(): flock = Flock.query.get(id) flock.name = click.prompt('Name', default=flock.name) flock.description = click.prompt('Description', default=flock.description) flock.when = click.prompt('When', default=flock.when) flock.where = click.prompt('Where', default=flock.where) db.session.commit() @admin.group() def location(): """Manage location suggestions.""" pass @location.command() def list(): """List location suggestions.""" table = PrettyTable(['id', 'name', 'image']) with app.app_context(): for loc in Location.query.all(): table.add_row([loc.id, loc.name, loc.image_url]) click.echo(table) @location.command() @click.option('--name', '-n', prompt='Location name', help='Location name') @click.option('--image_url', '-i', prompt='Location image URL', help='Location image URL') def add(name, image_url): """Add a location suggestion.""" with app.app_context(): loc = Location(name, image_url) db.session.add(loc) db.session.commit() id = loc.id click.echo('Created location {}'.format(id)) @location.command() @click.argument('id') @click.confirmation_option(prompt='Are you sure you want to delete this location?') def remove(id): """Remove a location suggestion.""" with app.app_context(): loc = Location.query.get(id) db.session.delete(loc) db.session.commit() @admin.group() def data(): """Manage database.""" pass @data.command() def examples(): """Drop / create tables, and seed examples.""" with app.app_context(): click.confirm('Are you sure you want to reset {}?'.format(db.engine), abort=True) db.drop_all() db.create_all() admin = User('admin', admin=True) nobody = User('nobody') foobar = User('foobar') db.session.add(admin) db.session.add(foobar) db.session.add(nobody) db.session.commit() f1 = Flock(name='Jupyter and Drinks', description="Let's chat about all things Jupyter", where='front door', when='7 pm', leader=admin) f2 = Flock(name='the life of scipy', description="Where are we going next?", where='back door', when='7 pm', leader=nobody) db.session.add(f1) db.session.add(f2) db.session.commit() f1.birds.append(foobar) f1.birds.append(nobody) f2.birds.append(foobar) db.session.commit() db.session.add(Location('front door', 'http://placehold.it/350x150')) db.session.add(Location('back door', 'http://placehold.it/350x150')) db.session.add(Location('lobby', '')) db.session.commit() @data.command() def stress(): """Drop / create tables, and seed 200 card test.""" with app.app_context(): click.confirm('Are you sure you want to reset {}?'.format(db.engine), abort=True) db.drop_all() db.create_all() admin = User('admin', admin=True) db.session.add(admin) db.session.commit() for i in range(200): f = Flock(name='Flock {}'.format(i), description='Description of flock {}'.format(i), where='front door', when='later tonight', leader=admin) db.session.add(f) db.session.commit() db.session.add(Location('front door', 'http://placehold.it/350x150')) db.session.commit() @data.command() def empty(): """Create empty database tables.""" with app.app_context(): click.confirm('Are you sure you want to create tables in {}?'.format(db.engine), abort=True) db.create_all() @data.command() def reset(): """Drop and create empty database tables.""" with app.app_context(): click.confirm('Are you sure you want to reset {}?'.format(db.engine), abort=True) db.drop_all() db.create_all() if __name__ == '__main__': admin()
{ "repo_name": "parente/bof", "path": "bof/admin.py", "copies": "1", "size": "6224", "license": "bsd-2-clause", "hash": -5184402692389266000, "line_mean": 25.485106383, "line_max": 90, "alpha_frac": 0.5731041131, "autogenerated": false, "ratio": 3.671976401179941, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9744354349855474, "avg_score": 0.00014523288489341562, "num_lines": 235 }
"""Admin definition for Bonus Points widget.""" from django.shortcuts import render_to_response from django.template import RequestContext from apps.admin.admin import challenge_designer_site, challenge_manager_site, developer_site ''' Created on Aug 5, 2012 @author: Cam Moore ''' from django.contrib import admin from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from apps.widgets.bonus_points.models import BonusPoint from apps.managers.challenge_mgr import challenge_mgr class BonusPointAdmin(admin.ModelAdmin): """admin for Bonus Points.""" actions = ["delete_selected", "deactivate_selected", "view_selected", "print_selected"] readonly_fields = ["pk", "code", "point_value", "create_date", "is_active", "printed_or_distributed", "user"] fields = ["pk", "code", "point_value", "create_date", "is_active", "printed_or_distributed", "user"] list_display = ["pk", "code", "point_value", "create_date", "is_active", "printed_or_distributed", "user"] ordering = ["-create_date", "is_active"] list_filter = ["point_value", "is_active", "printed_or_distributed"] date_hierarchy = "create_date" def delete_selected(self, request, queryset): """override the delete selected method.""" _ = request for obj in queryset: obj.delete() delete_selected.short_description = "Delete the selected Bonus Points." def deactivate_selected(self, request, queryset): """Changes the is_active flag to false for the selected Bonus Points.""" _ = request queryset.update(is_active=False) deactivate_selected.short_description = "Deactivate the selected Bonus Points." def print_selected(self, request, queryset): """Changes the printed_or_distributed flag to True for the selected Bonus Points.""" _ = request queryset.update(printed_or_distributed=True) print_selected.short_description = "Set the printed or distributed flag." def view_selected(self, request, queryset): """Views the Bonus Points Codes for printing.""" _ = request _ = queryset return render_to_response("view_bonus_points.html", { "codes": queryset, "per_page": 10, }, context_instance=RequestContext(request)) view_selected.short_description = "View the selected Bonus Points." def view_codes(self, request, queryset): """Views the Bonus Points Codes for printing.""" _ = request _ = queryset response = HttpResponseRedirect(reverse("bonus_view_codes", args=())) return response admin.site.register(BonusPoint, BonusPointAdmin) challenge_designer_site.register(BonusPoint, BonusPointAdmin) challenge_manager_site.register(BonusPoint, BonusPointAdmin) developer_site.register(BonusPoint, BonusPointAdmin) challenge_mgr.register_designer_game_info_model("Smart Grid Game", BonusPoint) challenge_mgr.register_admin_game_info_model("Smart Grid Game", BonusPoint) challenge_mgr.register_developer_game_info_model("Smart Grid Game", BonusPoint)
{ "repo_name": "yongwen/makahiki", "path": "makahiki/apps/widgets/bonus_points/admin.py", "copies": "2", "size": "3188", "license": "mit", "hash": -3700096771988126700, "line_mean": 36.9523809524, "line_max": 92, "alpha_frac": 0.6803638645, "autogenerated": false, "ratio": 3.9406674907292953, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5621031355229296, "avg_score": null, "num_lines": null }
"""Admin definition for EmailUser.""" from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from .forms import EmailUserChangeForm, EmailUserCreationForm from .models import EmailUser class EmailUserAdmin(UserAdmin): """EmailUser Admin model.""" fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = (( None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2') } ), ) # The forms to add and change user instances form = EmailUserChangeForm add_form = EmailUserCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('email', 'is_staff') list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups') search_fields = ('email',) ordering = ('email',) filter_horizontal = ('groups', 'user_permissions',) # Register the new EmailUserAdmin admin.site.register(EmailUser, EmailUserAdmin)
{ "repo_name": "benkonrath/django-custom-user", "path": "custom_user/admin.py", "copies": "3", "size": "1387", "license": "bsd-3-clause", "hash": 199881736598889470, "line_mean": 32.0238095238, "line_max": 79, "alpha_frac": 0.6265320836, "autogenerated": false, "ratio": 4.140298507462687, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6266830591062686, "avg_score": null, "num_lines": null }
"""Admin definition for EmailUser.""" from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from . forms import EmailUserChangeForm, EmailUserCreationForm from . models import EmailUser class EmailUserAdmin(UserAdmin): """EmailUser Admin model.""" fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'display_name')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = (( None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2') } ), ) # The forms to add and change user instances form = EmailUserChangeForm add_form = EmailUserCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('email', 'is_staff', 'first_name', 'last_name', 'display_name') list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups') search_fields = ('first_name', 'last_name', 'display_name', 'email') ordering = ('email',) filter_horizontal = ('groups', 'user_permissions',) # Register the new EmailUserAdmin admin.site.register(EmailUser, EmailUserAdmin)
{ "repo_name": "contactr2m/remote_repo", "path": "src/accounts/admin.py", "copies": "1", "size": "1561", "license": "mit", "hash": -4152698902552867000, "line_mean": 35.3023255814, "line_max": 86, "alpha_frac": 0.6220371557, "autogenerated": false, "ratio": 4.0025641025641026, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0010389676865815343, "num_lines": 43 }
"""Admin definition for Smart Grid Game Library.""" from django.db import models from apps.managers.cache_mgr import cache_mgr from apps.managers.challenge_mgr import challenge_mgr from apps.utils import utils from django.contrib import admin from django import forms from django.forms.models import BaseInlineFormSet from django.forms.util import ErrorList from django.forms import TextInput, Textarea from apps.admin.admin import challenge_designer_site, challenge_manager_site, developer_site from apps.widgets.smartgrid_library.models import LibraryTextPromptQuestion, LibraryColumnName, \ LibraryActivity, LibraryQuestionChoice, LibraryEvent, LibraryCommitment, LibraryAction from django.db.utils import IntegrityError from apps.widgets.smartgrid_library.views import library_action_admin_list, library_action_admin class LibraryActionAdmin(admin.ModelAdmin): """Admin interface for LibraryActions.""" actions = ["delete_selected", "copy_action"] list_display = ["slug", "title", "type", "point_value"] search_fields = ["slug", "title"] list_filter = ["type", ] def delete_selected(self, request, queryset): """override the delete selected.""" _ = request for obj in queryset: obj.delete() delete_selected.short_description = "Delete the selected objects." def copy_action(self, request, queryset): """Copy the selected Actions.""" _ = request for obj in queryset: obj.id = None slug = obj.slug obj.slug = slug + "-copy" try: obj.save() except IntegrityError: # How do we indicate an error to the admin? pass copy_action.short_description = "Copy selected Action(s)" def get_urls(self): return redirect_urls(self, "change") admin.site.register(LibraryAction, LibraryActionAdmin) challenge_designer_site.register(LibraryAction, LibraryActionAdmin) challenge_manager_site.register(LibraryAction, LibraryActionAdmin) developer_site.register(LibraryAction, LibraryActionAdmin) challenge_mgr.register_designer_challenge_info_model("Smart Grid Game Library", 4, \ LibraryAction, 2) challenge_mgr.register_developer_challenge_info_model("Smart Grid Game Library", 4, \ LibraryAction, 2) class LibraryColumnNameAdmin(admin.ModelAdmin): """LibraryColumnName Admin.""" list_display = ["name"] prepopulated_fields = {"slug": ("name",)} fields = ["name", "slug"] admin.site.register(LibraryColumnName, LibraryColumnNameAdmin) challenge_designer_site.register(LibraryColumnName, LibraryColumnNameAdmin) challenge_manager_site.register(LibraryColumnName, LibraryColumnNameAdmin) developer_site.register(LibraryColumnName, LibraryColumnNameAdmin) challenge_mgr.register_designer_challenge_info_model("Smart Grid Game Library", 4, \ LibraryColumnName, 1) challenge_mgr.register_developer_challenge_info_model("Smart Grid Game Library", 4, \ LibraryColumnName, 1) class LibraryActivityAdminForm(forms.ModelForm): """Smart Grid Game Library Activity Admin Form.""" class Meta: """Meta""" model = LibraryActivity def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] utils.validate_form_predicates(data) return data def clean(self): """ Validates the admin form data based on a set of constraints. 1. If the verification type is "image" or "code", then a confirm prompt is required. 2. Either points or a point range needs to be specified. """ super(LibraryActivityAdminForm, self).clean() # Data that has passed validation. cleaned_data = self.cleaned_data #1 Check the verification type. confirm_type = cleaned_data.get("confirm_type") prompt = cleaned_data.get("confirm_prompt") if confirm_type != "text" and len(prompt) == 0: self._errors["confirm_prompt"] = ErrorList( [u"This confirmation type requires a confirmation prompt."]) del cleaned_data["confirm_type"] del cleaned_data["confirm_prompt"] #2 Either points or a point range needs to be specified. points = cleaned_data.get("point_value") point_range_start = cleaned_data.get("point_range_start") point_range_end = cleaned_data.get("point_range_end") if not points and not (point_range_start or point_range_end): self._errors["point_value"] = ErrorList( [u"Either a point value or a range needs to be specified."]) del cleaned_data["point_value"] elif points and (point_range_start or point_range_end): self._errors["point_value"] = ErrorList( [u"Please specify either a point_value or a range."]) del cleaned_data["point_value"] elif not points: point_range_start = cleaned_data.get("point_range_start") point_range_end = cleaned_data.get("point_range_end") if not point_range_start: self._errors["point_range_start"] = ErrorList( [u"Please specify a start value for the point range."]) del cleaned_data["point_range_start"] elif not point_range_end: self._errors["point_range_end"] = ErrorList( [u"Please specify a end value for the point range."]) del cleaned_data["point_range_end"] elif point_range_start >= point_range_end: self._errors["point_range_start"] = ErrorList( [u"The start value must be less than the end value."]) del cleaned_data["point_range_start"] del cleaned_data["point_range_end"] return cleaned_data def save(self, *args, **kwargs): activity = super(LibraryActivityAdminForm, self).save(*args, **kwargs) activity.type = 'activity' activity.save() cache_mgr.clear() # If the activity's confirmation type is text, make sure to save the questions. if self.cleaned_data.get("confirm_type") == "text": self.save_m2m() return activity class LibraryTextQuestionInlineFormSet(BaseInlineFormSet): """Custom formset model to override validation.""" def clean(self): """Validates the form data and checks if the activity confirmation type is text.""" # Form that represents the activity. activity = self.instance if not activity.pk: # If the activity is not saved, we don't care if this validates. return # Count the number of questions. count = 0 for form in self.forms: try: if form.cleaned_data: count += 1 except AttributeError: pass if activity.confirm_type == "text" and count == 0: # Why did I do this? # activity.delete() raise forms.ValidationError( "At least one question is required if the activity's confirmation type is text.") elif activity.confirm_type != "text" and count > 0: # activity.delete() raise forms.ValidationError("Questions are not required for this confirmation type.") class LibraryQuestionChoiceInline(admin.TabularInline): """Smart Grid Game Library Question Choice admin.""" model = LibraryQuestionChoice fieldset = ( (None, { 'fields': ('question', 'choice'), 'classes': ['wide', ], }) ) extra = 4 class LibraryTextQuestionInline(admin.TabularInline): """Text Question admin.""" model = LibraryTextPromptQuestion fieldset = ( (None, { 'fields': ('question', 'answer'), }) ) formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'rows': 2, 'cols': 70})}, } extra = 1 formset = LibraryTextQuestionInlineFormSet class LibraryActivityAdmin(admin.ModelAdmin): """Smart Grid Game Library Activities Admin.""" list_display = ["slug", 'title', 'expected_duration', 'point_value'] fieldsets = ( ("Basic Information", {'fields': (('name', ), ('slug', ), ('title', 'expected_duration'), 'image', 'description', ('video_id', 'video_source'), 'embedded_widget', ('unlock_condition', 'unlock_condition_text'), )}), ("Points", {"fields": (("point_value", "social_bonus"), ("point_range_start", "point_range_end"), )}), ("Admin Note", {'fields': ('admin_note',)}), ("Confirmation Type", {'fields': ('confirm_type', 'confirm_prompt')}), ) prepopulated_fields = {"slug": ("name",)} form = LibraryActivityAdminForm inlines = [LibraryTextQuestionInline] formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): return redirect_urls(self, "changelist") admin.site.register(LibraryActivity, LibraryActivityAdmin) challenge_designer_site.register(LibraryActivity, LibraryActivityAdmin) challenge_manager_site.register(LibraryActivity, LibraryActivityAdmin) developer_site.register(LibraryActivity, LibraryActivityAdmin) class LibraryCommitmentAdminForm(forms.ModelForm): """Smart Grid Game Library Commitment admin form""" class Meta: """meta""" model = LibraryCommitment def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] utils.validate_form_predicates(data) return data def save(self, *args, **kwargs): commitment = super(LibraryCommitmentAdminForm, self).save(*args, **kwargs) commitment.type = 'commitment' commitment.save() cache_mgr.clear() return commitment class LibraryCommitmentAdmin(admin.ModelAdmin): """Smart Grid Game Library Commitment Admin.""" list_display = ["slug", 'title', 'commitment_length', 'point_value'] fieldsets = ( ("Basic Information", { 'fields': (('name', ), ('slug', ), ('title', 'commitment_length'), 'image', 'description', 'unlock_condition', 'unlock_condition_text', ), }), ("Points", {"fields": (("point_value", 'social_bonus'), )}), ) prepopulated_fields = {"slug": ("name",)} form = LibraryCommitmentAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): """override the url definition.""" return redirect_urls(self, "changelist") admin.site.register(LibraryCommitment, LibraryCommitmentAdmin) challenge_designer_site.register(LibraryCommitment, LibraryCommitmentAdmin) challenge_manager_site.register(LibraryCommitment, LibraryCommitmentAdmin) developer_site.register(LibraryCommitment, LibraryCommitmentAdmin) class LibraryEventAdminForm(forms.ModelForm): """Smart Grid Game Library Event Admin Form.""" class Meta: """Meta""" model = LibraryEvent def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] utils.validate_form_predicates(data) return data def save(self, *args, **kwargs): event = super(LibraryEventAdminForm, self).save(*args, **kwargs) event.type = 'event' event.save() cache_mgr.clear() return event class LibraryEventAdmin(admin.ModelAdmin): """Smart Grid Game Library Event Admin""" list_display = ["slug", 'title', 'expected_duration', 'point_value'] fieldsets = ( ("Basic Information", {'fields': (('name',), ('slug',), ('title', 'expected_duration'), 'image', 'description', ('unlock_condition', 'unlock_condition_text'), )}), ("Points", {"fields": (("point_value", "social_bonus"),)}), ) prepopulated_fields = {"slug": ("name",)} form = LibraryEventAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): return redirect_urls(self, "changelist") admin.site.register(LibraryEvent, LibraryEventAdmin) challenge_designer_site.register(LibraryEvent, LibraryEventAdmin) challenge_manager_site.register(LibraryEvent, LibraryEventAdmin) developer_site.register(LibraryEvent, LibraryEventAdmin) def redirect_urls(model_admin, url_type): """change the url redirection.""" from django.conf.urls.defaults import patterns, url from functools import update_wrapper def wrap(view): """wrap the view fuction.""" def wrapper(*args, **kwargs): """return the wrapper.""" return model_admin.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = model_admin.model._meta.app_label, model_admin.model._meta.module_name urlpatterns = patterns('', url(r'^$', wrap(library_action_admin_list if url_type == "changelist" else \ model_admin.changelist_view), name='%s_%s_changelist' % info), url(r'^add/$', wrap(model_admin.add_view), name='%s_%s_add' % info), url(r'^(.+)/history/$', wrap(model_admin.history_view), name='%s_%s_history' % info), url(r'^(.+)/delete/$', wrap(model_admin.delete_view), name='%s_%s_delete' % info), url(r'^(.+)/$', wrap(library_action_admin if url_type == "change" else model_admin.change_view), name='%s_%s_change' % info), ) return urlpatterns
{ "repo_name": "MakahikiKTUH/makahiki-ktuh", "path": "makahiki/apps/widgets/smartgrid_library/admin.py", "copies": "1", "size": "14545", "license": "mit", "hash": -4686505920960314000, "line_mean": 36.199488491, "line_max": 100, "alpha_frac": 0.6067377106, "autogenerated": false, "ratio": 4.37706891363226, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.548380662423226, "avg_score": null, "num_lines": null }
"""Admin definition for Smart Grid Game Library.""" from django.db import models from apps.managers.cache_mgr import cache_mgr from apps.managers.challenge_mgr import challenge_mgr from django.contrib import admin from django import forms from django.forms.models import BaseInlineFormSet from django.forms.util import ErrorList from django.forms import TextInput, Textarea from apps.admin.admin import challenge_designer_site, challenge_manager_site, developer_site from apps.widgets.smartgrid_library.models import LibraryTextPromptQuestion, LibraryColumnName, \ LibraryActivity, LibraryQuestionChoice, LibraryEvent, LibraryCommitment, LibraryAction from django.db.utils import IntegrityError from apps.widgets.smartgrid_library.views import library_action_admin_list, library_action_admin from django.http import HttpResponseRedirect from apps.managers.predicate_mgr import predicate_mgr class LibraryActionAdmin(admin.ModelAdmin): """Admin interface for LibraryActions.""" actions = ["delete_selected", "copy_action"] list_display = ["slug", "title", "type", "point_value"] search_fields = ["slug", "title"] list_filter = ["type", ] def delete_selected(self, request, queryset): """override the delete selected.""" _ = request for obj in queryset: obj.delete() delete_selected.short_description = "Delete the selected objects." def copy_action(self, request, queryset): """Copy the selected Actions.""" _ = request for obj in queryset: obj.id = None slug = obj.slug obj.slug = slug + "-copy" try: obj.save() except IntegrityError: # How do we indicate an error to the admin? pass copy_action.short_description = "Copy selected Action(s)" def get_urls(self): return redirect_urls(self, "change") admin.site.register(LibraryAction, LibraryActionAdmin) challenge_designer_site.register(LibraryAction, LibraryActionAdmin) challenge_manager_site.register(LibraryAction, LibraryActionAdmin) developer_site.register(LibraryAction, LibraryActionAdmin) challenge_mgr.register_designer_challenge_info_model("Smart Grid Game Library", 4, \ LibraryAction, 2) challenge_mgr.register_developer_challenge_info_model("Smart Grid Game Library", 4, \ LibraryAction, 2) class LibraryColumnNameAdmin(admin.ModelAdmin): """LibraryColumnName Admin.""" list_display = ["name"] prepopulated_fields = {"slug": ("name",)} fields = ["name", "slug"] admin.site.register(LibraryColumnName, LibraryColumnNameAdmin) challenge_designer_site.register(LibraryColumnName, LibraryColumnNameAdmin) challenge_manager_site.register(LibraryColumnName, LibraryColumnNameAdmin) developer_site.register(LibraryColumnName, LibraryColumnNameAdmin) challenge_mgr.register_designer_challenge_info_model("Smart Grid Game Library", 4, \ LibraryColumnName, 1) challenge_mgr.register_developer_challenge_info_model("Smart Grid Game Library", 4, \ LibraryColumnName, 1) class LibraryActivityAdminForm(forms.ModelForm): """Smart Grid Game Library Activity Admin Form.""" class Meta: """Meta""" model = LibraryActivity def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] predicate_mgr.validate_form_predicates(data) return data def clean(self): """ Validates the admin form data based on a set of constraints. 1. If the verification type is "image" or "code", then a confirm prompt is required. 2. Either points or a point range needs to be specified. """ super(LibraryActivityAdminForm, self).clean() # Data that has passed validation. cleaned_data = self.cleaned_data #1 Check the verification type. confirm_type = cleaned_data.get("confirm_type") prompt = cleaned_data.get("confirm_prompt") if confirm_type != "text" and len(prompt) == 0: self._errors["confirm_prompt"] = ErrorList( [u"This confirmation type requires a confirmation prompt."]) del cleaned_data["confirm_type"] del cleaned_data["confirm_prompt"] #2 Either points or a point range needs to be specified. points = cleaned_data.get("point_value") point_range_start = cleaned_data.get("point_range_start") point_range_end = cleaned_data.get("point_range_end") if not points and not (point_range_start or point_range_end): self._errors["point_value"] = ErrorList( [u"Either a point value or a range needs to be specified."]) del cleaned_data["point_value"] elif points and (point_range_start or point_range_end): self._errors["point_value"] = ErrorList( [u"Please specify either a point_value or a range."]) del cleaned_data["point_value"] elif not points: point_range_start = cleaned_data.get("point_range_start") point_range_end = cleaned_data.get("point_range_end") if not point_range_start: self._errors["point_range_start"] = ErrorList( [u"Please specify a start value for the point range."]) del cleaned_data["point_range_start"] elif not point_range_end: self._errors["point_range_end"] = ErrorList( [u"Please specify a end value for the point range."]) del cleaned_data["point_range_end"] elif point_range_start >= point_range_end: self._errors["point_range_start"] = ErrorList( [u"The start value must be less than the end value."]) del cleaned_data["point_range_start"] del cleaned_data["point_range_end"] return cleaned_data def save(self, *args, **kwargs): """save""" activity = super(LibraryActivityAdminForm, self).save(*args, **kwargs) activity.type = 'activity' activity.save() cache_mgr.clear() # If the activity's confirmation type is text, make sure to save the questions. if self.cleaned_data.get("confirm_type") == "text": self.save_m2m() return activity class LibraryTextQuestionInlineFormSet(BaseInlineFormSet): """Custom formset model to override validation.""" def clean(self): """Validates the form data and checks if the activity confirmation type is text.""" # Form that represents the activity. activity = self.instance if not activity.pk: # If the activity is not saved, we don't care if this validates. return # Count the number of questions. count = 0 for form in self.forms: try: if form.cleaned_data: count += 1 except AttributeError: pass if activity.confirm_type == "text" and count == 0: # Why did I do this? # activity.delete() raise forms.ValidationError( "At least one question is required if the activity's confirmation type is text.") elif activity.confirm_type != "text" and count > 0: # activity.delete() raise forms.ValidationError("Questions are not required for this confirmation type.") class LibraryQuestionChoiceInline(admin.TabularInline): """Smart Grid Game Library Question Choice admin.""" model = LibraryQuestionChoice fieldset = ( (None, { 'fields': ('question', 'choice'), 'classes': ['wide', ], }) ) extra = 4 class LibraryTextQuestionInline(admin.TabularInline): """Text Question admin.""" model = LibraryTextPromptQuestion fieldset = ( (None, { 'fields': ('question', 'answer'), }) ) formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'rows': 2, 'cols': 70})}, } extra = 1 formset = LibraryTextQuestionInlineFormSet class LibraryActivityAdmin(admin.ModelAdmin): """Smart Grid Game Library Activities Admin.""" list_display = ["slug", 'title', 'expected_duration', 'point_value'] fieldsets = ( ("Basic Information", {'fields': (('name', ), ('slug', ), ('title', 'expected_duration'), 'image', 'description', ('video_id', 'video_source'), 'embedded_widget', ('unlock_condition', 'unlock_condition_text'), )}), ("Points", {"fields": (("point_value", "social_bonus"), ("point_range_start", "point_range_end"), )}), ("Admin Note", {'fields': ('admin_note',)}), ("Confirmation Type", {'fields': ('confirm_type', 'confirm_prompt')}), ) prepopulated_fields = {"slug": ("name",)} form = LibraryActivityAdminForm inlines = [LibraryTextQuestionInline] formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): return redirect_urls(self, "changelist") def response_change(self, request, obj): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/") def response_add(self, request, obj, post_url_continue=None): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/") admin.site.register(LibraryActivity, LibraryActivityAdmin) challenge_designer_site.register(LibraryActivity, LibraryActivityAdmin) challenge_manager_site.register(LibraryActivity, LibraryActivityAdmin) developer_site.register(LibraryActivity, LibraryActivityAdmin) class LibraryCommitmentAdminForm(forms.ModelForm): """Smart Grid Game Library Commitment admin form""" class Meta: """meta""" model = LibraryCommitment def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] predicate_mgr.validate_form_predicates(data) return data def save(self, *args, **kwargs): """save""" commitment = super(LibraryCommitmentAdminForm, self).save(*args, **kwargs) commitment.type = 'commitment' commitment.save() cache_mgr.clear() return commitment class LibraryCommitmentAdmin(admin.ModelAdmin): """Smart Grid Game Library Commitment Admin.""" list_display = ["slug", 'title', 'commitment_length', 'point_value'] fieldsets = ( ("Basic Information", { 'fields': (('name', ), ('slug', ), ('title', 'commitment_length'), 'image', 'description', 'unlock_condition', 'unlock_condition_text', ), }), ("Points", {"fields": (("point_value", 'social_bonus'), )}), ) prepopulated_fields = {"slug": ("name",)} form = LibraryCommitmentAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): """override the url definition.""" return redirect_urls(self, "changelist") def response_change(self, request, obj): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/") def response_add(self, request, obj, post_url_continue=None): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/") admin.site.register(LibraryCommitment, LibraryCommitmentAdmin) challenge_designer_site.register(LibraryCommitment, LibraryCommitmentAdmin) challenge_manager_site.register(LibraryCommitment, LibraryCommitmentAdmin) developer_site.register(LibraryCommitment, LibraryCommitmentAdmin) class LibraryEventAdminForm(forms.ModelForm): """Smart Grid Game Library Event Admin Form.""" class Meta: """Meta""" model = LibraryEvent def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] predicate_mgr.validate_form_predicates(data) return data def save(self, *args, **kwargs): """save""" event = super(LibraryEventAdminForm, self).save(*args, **kwargs) event.type = 'event' event.save() cache_mgr.clear() return event class LibraryEventAdmin(admin.ModelAdmin): """Smart Grid Game Library Event Admin""" list_display = ["slug", 'title', 'expected_duration', 'point_value'] fieldsets = ( ("Basic Information", {'fields': (('name',), ('slug',), ('title', 'expected_duration'), 'image', 'description', ('unlock_condition', 'unlock_condition_text'), )}), ("Points", {"fields": (("point_value", "social_bonus"),)}), ) prepopulated_fields = {"slug": ("name",)} form = LibraryEventAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): return redirect_urls(self, "changelist") def response_change(self, request, obj): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/") def response_add(self, request, obj, post_url_continue=None): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/") admin.site.register(LibraryEvent, LibraryEventAdmin) challenge_designer_site.register(LibraryEvent, LibraryEventAdmin) challenge_manager_site.register(LibraryEvent, LibraryEventAdmin) developer_site.register(LibraryEvent, LibraryEventAdmin) def redirect_urls(model_admin, url_type): """change the url redirection.""" from django.conf.urls import patterns, url from functools import update_wrapper def wrap(view): """wrap the view fuction.""" def wrapper(*args, **kwargs): """return the wrapper.""" return model_admin.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = model_admin.model._meta.app_label, model_admin.model._meta.module_name urlpatterns = patterns('', url(r'^$', wrap(library_action_admin_list if url_type == "changelist" else \ model_admin.changelist_view), name='%s_%s_changelist' % info), url(r'^add/$', wrap(model_admin.add_view), name='%s_%s_add' % info), url(r'^(.+)/history/$', wrap(model_admin.history_view), name='%s_%s_history' % info), url(r'^(.+)/delete/$', wrap(model_admin.delete_view), name='%s_%s_delete' % info), url(r'^(.+)/$', wrap(library_action_admin if url_type == "change" else model_admin.change_view), name='%s_%s_change' % info), ) return urlpatterns
{ "repo_name": "csdl/makahiki", "path": "makahiki/apps/widgets/smartgrid_library/admin.py", "copies": "2", "size": "16022", "license": "mit", "hash": -2932099876622113300, "line_mean": 36.6988235294, "line_max": 100, "alpha_frac": 0.6124079391, "autogenerated": false, "ratio": 4.416207276736494, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6028615215836495, "avg_score": null, "num_lines": null }
"""Admin definition for Smart Grid Game widget.""" from django.db import models from apps.managers.cache_mgr import cache_mgr from apps.managers.challenge_mgr import challenge_mgr from apps.utils import utils from apps.widgets.smartgrid_design.views import designer_action_admin, \ designer_action_admin_list from django.contrib import admin from django import forms from django.forms.models import BaseInlineFormSet from django.forms.util import ErrorList from django.forms import TextInput, Textarea from django.db.utils import IntegrityError from apps.admin.admin import challenge_designer_site, challenge_manager_site, developer_site from apps.widgets.smartgrid_design.models import DesignerAction, DesignerActivity, \ DesignerTextPromptQuestion, DesignerCommitment, DesignerEvent, DesignerFiller, \ DesignerColumnName, DesignerLevel, DesignerQuestionChoice class DesignerActionAdmin(admin.ModelAdmin): """abstract admin for action.""" actions = ["delete_selected", "copy_action"] list_display = ["slug", "title", "type", "point_value"] search_fields = ["slug", "title"] list_filter = ['type', ] def delete_selected(self, request, queryset): """override the delete selected.""" _ = request for obj in queryset: obj.delete() delete_selected.short_description = "Delete the selected objects." def copy_action(self, request, queryset): """Copy the selected Actions.""" _ = request for obj in queryset: obj.id = None slug = obj.slug obj.slug = slug + "-copy" try: obj.save() except IntegrityError: # How do we indicate an error to the admin? pass copy_action.short_description = "Copy selected Action(s)" def get_urls(self): return redirect_urls(self, "change") admin.site.register(DesignerAction, DesignerActionAdmin) challenge_designer_site.register(DesignerAction, DesignerActionAdmin) challenge_manager_site.register(DesignerAction, DesignerActionAdmin) developer_site.register(DesignerAction, DesignerActionAdmin) challenge_mgr.register_designer_challenge_info_model("Smart Grid Game Designer", 5, \ DesignerAction, 2) challenge_mgr.register_developer_challenge_info_model("Smart Grid Game Designer", 4, \ DesignerAction, 2) class DesignerActivityAdminForm(forms.ModelForm): """Activity Admin Form.""" class Meta: """Meta""" model = DesignerActivity def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] utils.validate_form_predicates(data) return data def clean(self): """ Validates the admin form data based on a set of constraints. 1. If the verification type is "image" or "code", then a confirm prompt is required. 2. Publication date must be before expiration date. 3. Either points or a point range needs to be specified. """ super(DesignerActivityAdminForm, self).clean() # Data that has passed validation. cleaned_data = self.cleaned_data #1 Check the verification type. confirm_type = cleaned_data.get("confirm_type") prompt = cleaned_data.get("confirm_prompt") if confirm_type != "text" and len(prompt) == 0: self._errors["confirm_prompt"] = ErrorList( [u"This confirmation type requires a confirmation prompt."]) del cleaned_data["confirm_type"] del cleaned_data["confirm_prompt"] #2 Publication date must be before the expiration date. if "pub_date" in cleaned_data and "expire_date" in cleaned_data: pub_date = cleaned_data.get("pub_date") expire_date = cleaned_data.get("expire_date") if expire_date and pub_date >= expire_date: self._errors["expire_date"] = ErrorList( [u"The expiration date must be after the pub date."]) del cleaned_data["expire_date"] #3 Either points or a point range needs to be specified. points = cleaned_data.get("point_value") point_range_start = cleaned_data.get("point_range_start") point_range_end = cleaned_data.get("point_range_end") if not points and not (point_range_start or point_range_end): self._errors["point_value"] = ErrorList( [u"Either a point value or a range needs to be specified."]) del cleaned_data["point_value"] elif points and (point_range_start or point_range_end): self._errors["point_value"] = ErrorList( [u"Please specify either a point_value or a range."]) del cleaned_data["point_value"] elif not points: point_range_start = cleaned_data.get("point_range_start") point_range_end = cleaned_data.get("point_range_end") if not point_range_start: self._errors["point_range_start"] = ErrorList( [u"Please specify a start value for the point range."]) del cleaned_data["point_range_start"] elif not point_range_end: self._errors["point_range_end"] = ErrorList( [u"Please specify a end value for the point range."]) del cleaned_data["point_range_end"] elif point_range_start >= point_range_end: self._errors["point_range_start"] = ErrorList( [u"The start value must be less than the end value."]) del cleaned_data["point_range_start"] del cleaned_data["point_range_end"] return cleaned_data def save(self, *args, **kwargs): activity = super(DesignerActivityAdminForm, self).save(*args, **kwargs) activity.type = 'activity' activity.save() cache_mgr.clear() # If the activity's confirmation type is text, make sure to save the questions. if self.cleaned_data.get("confirm_type") == "text": self.save_m2m() return activity class DesignerTextQuestionInlineFormSet(BaseInlineFormSet): """Custom formset model to override validation.""" def clean(self): """Validates the form data and checks if the activity confirmation type is text.""" # Form that represents the activity. activity = self.instance if not activity.pk: # If the activity is not saved, we don't care if this validates. return # Count the number of questions. count = 0 for form in self.forms: try: if form.cleaned_data: count += 1 except AttributeError: pass if activity.confirm_type == "text" and count == 0: # Why did I do this? # activity.delete() raise forms.ValidationError( "At least one question is required if the activity's confirmation type is text.") elif activity.confirm_type != "text" and count > 0: # activity.delete() raise forms.ValidationError("Questions are not required for this confirmation type.") class TextQuestionInline(admin.TabularInline): """Text Question admin.""" model = DesignerTextPromptQuestion fieldset = ( (None, { 'fields': ('question', 'answer'), }) ) formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'rows': 2, 'cols': 70})}, } extra = 1 formset = DesignerTextQuestionInlineFormSet class DesignerActivityAdmin(admin.ModelAdmin): """Activity Admin""" fieldsets = ( ("Basic Information", {'fields': (('name', ), ('slug', 'related_resource'), ('title', 'expected_duration'), 'image', 'description', ('video_id', 'video_source'), 'embedded_widget', ('pub_date', 'expire_date'), ('unlock_condition', 'unlock_condition_text'), )}), ("Points", {"fields": (("point_value", "social_bonus"), ("point_range_start", "point_range_end"), )}), ("Admin Note", {'fields': ('admin_note',)}), ("Confirmation Type", {'fields': ('confirm_type', 'confirm_prompt')}), ) prepopulated_fields = {"slug": ("name",)} form = DesignerActivityAdminForm inlines = [TextQuestionInline] formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): return redirect_urls(self, "changelist") admin.site.register(DesignerActivity, DesignerActivityAdmin) challenge_designer_site.register(DesignerActivity, DesignerActivityAdmin) challenge_manager_site.register(DesignerActivity, DesignerActivityAdmin) developer_site.register(DesignerActivity, DesignerActivityAdmin) class DesignerCommitmentAdminForm(forms.ModelForm): """admin form""" class Meta: """meta""" model = DesignerCommitment def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] utils.validate_form_predicates(data) return data def save(self, *args, **kwargs): commitment = super(DesignerCommitmentAdminForm, self).save(*args, **kwargs) commitment.type = 'commitment' commitment.save() cache_mgr.clear() return commitment class DesignerCommitmentAdmin(admin.ModelAdmin): """Commitment Admin.""" fieldsets = ( ("Basic Information", { 'fields': (('name', ), ('slug', 'related_resource'), ('title', 'commitment_length'), 'image', 'description', 'unlock_condition', 'unlock_condition_text', ), }), ("Points", {"fields": (("point_value", 'social_bonus'), )}), ) form = DesignerCommitmentAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): """override the url definition.""" return redirect_urls(self, "changelist") admin.site.register(DesignerCommitment, DesignerCommitmentAdmin) challenge_designer_site.register(DesignerCommitment, DesignerCommitmentAdmin) challenge_manager_site.register(DesignerCommitment, DesignerCommitmentAdmin) developer_site.register(DesignerCommitment, DesignerCommitmentAdmin) class DesignerEventAdminForm(forms.ModelForm): """Event Admin Form.""" class Meta: """Meta""" model = DesignerEvent def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] utils.validate_form_predicates(data) return data def clean(self): """ Validates the admin form data based on a set of constraints. 1. Events must have an event date. 2. Publication date must be before expiration date. """ # Data that has passed validation. cleaned_data = self.cleaned_data #1 Check that an event has an event date. event_date = cleaned_data.get("event_date") has_date = "event_date" in cleaned_data # Check if this is in the data dict. if has_date and not event_date: self._errors["event_date"] = ErrorList([u"Events require an event date."]) del cleaned_data["event_date"] #2 Publication date must be before the expiration date. if "pub_date" in cleaned_data and "expire_date" in cleaned_data: pub_date = cleaned_data.get("pub_date") expire_date = cleaned_data.get("expire_date") if expire_date and pub_date >= expire_date: self._errors["expire_date"] = ErrorList( [u"The expiration date must be after the pub date."]) del cleaned_data["expire_date"] return cleaned_data def save(self, *args, **kwargs): event = super(DesignerEventAdminForm, self).save(*args, **kwargs) event.type = 'event' event.save() cache_mgr.clear() return event class DesignerEventAdmin(admin.ModelAdmin): """Event Admin""" fieldsets = ( ("Basic Information", {'fields': (('name', ), ('slug', 'related_resource'), ('title', 'expected_duration'), 'image', 'description', ('pub_date', 'expire_date'), ('event_date', 'event_location', 'event_max_seat'), ('unlock_condition', 'unlock_condition_text'), )}), ("Points", {"fields": (("point_value", "social_bonus"),)}), ) form = DesignerEventAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): return redirect_urls(self, "changelist") admin.site.register(DesignerEvent, DesignerEventAdmin) challenge_designer_site.register(DesignerEvent, DesignerEventAdmin) challenge_manager_site.register(DesignerEvent, DesignerEventAdmin) developer_site.register(DesignerEvent, DesignerEventAdmin) class DesignerFillerAdminForm(forms.ModelForm): """admin form""" class Meta: """meta""" model = DesignerFiller def save(self, *args, **kwargs): filler = super(DesignerFillerAdminForm, self).save(*args, **kwargs) filler.type = 'filler' filler.unlock_condition = "False" filler.unlock_condition_text = "This cell is here only to fill out the grid. " \ "There is no action associated with it." filler.save() cache_mgr.clear() return filler class DesignerFillerAdmin(admin.ModelAdmin): """Commitment Admin.""" fieldsets = ( ("Basic Information", { 'fields': (('name', ), ('slug', ), ('title', ), ), }), ) prepopulated_fields = {"slug": ("name",)} form = DesignerFillerAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): """override the url definition.""" return redirect_urls(self, "changelist") admin.site.register(DesignerFiller, DesignerFillerAdmin) challenge_designer_site.register(DesignerFiller, DesignerFillerAdmin) challenge_manager_site.register(DesignerFiller, DesignerFillerAdmin) developer_site.register(DesignerFiller, DesignerFillerAdmin) class DesignerColumnNameAdmin(admin.ModelAdmin): """DesignerColumnName Administration""" list_display = ["name", ] prepopulated_fields = {"slug": ("name",)} admin.site.register(DesignerColumnName, DesignerColumnNameAdmin) challenge_designer_site.register(DesignerColumnName, DesignerColumnNameAdmin) challenge_manager_site.register(DesignerColumnName, DesignerColumnNameAdmin) developer_site.register(DesignerColumnName, DesignerColumnNameAdmin) class DesignerLevelAdminForm(forms.ModelForm): """admin form""" class Meta: """meta""" model = DesignerLevel def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] utils.validate_form_predicates(data) return data class DesignerLevelAdmin(admin.ModelAdmin): """Level Admin""" list_display = ["name", "priority", "unlock_condition"] form = DesignerLevelAdminForm prepopulated_fields = {"slug": ("name",)} admin.site.register(DesignerLevel, DesignerLevelAdmin) challenge_designer_site.register(DesignerLevel, DesignerLevelAdmin) challenge_manager_site.register(DesignerLevel, DesignerLevelAdmin) developer_site.register(DesignerLevel, DesignerLevelAdmin) class QuestionChoiceInline(admin.TabularInline): """Question Choice admin.""" model = DesignerQuestionChoice fieldset = ( (None, { 'fields': ('question', 'choice'), 'classes': ['wide', ], }) ) extra = 4 def redirect_urls(model_admin, url_type): """change the url redirection.""" from django.conf.urls.defaults import patterns, url from functools import update_wrapper def wrap(view): """wrap the view fuction.""" def wrapper(*args, **kwargs): """return the wrapper.""" return model_admin.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = model_admin.model._meta.app_label, model_admin.model._meta.module_name urlpatterns = patterns('', url(r'^$', wrap(designer_action_admin_list if url_type == "changelist" else \ model_admin.changelist_view), name='%s_%s_changelist' % info), url(r'^add/$', wrap(model_admin.add_view), name='%s_%s_add' % info), url(r'^(.+)/history/$', wrap(model_admin.history_view), name='%s_%s_history' % info), url(r'^(.+)/delete/$', wrap(model_admin.delete_view), name='%s_%s_delete' % info), url(r'^(.+)/$', wrap(designer_action_admin if url_type == "change" else model_admin.change_view), name='%s_%s_change' % info), ) return urlpatterns
{ "repo_name": "MakahikiKTUH/makahiki-ktuh", "path": "makahiki/apps/widgets/smartgrid_design/admin.py", "copies": "1", "size": "17991", "license": "mit", "hash": 3898640073692455400, "line_mean": 34.9101796407, "line_max": 100, "alpha_frac": 0.606858985, "autogenerated": false, "ratio": 4.242159867955671, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5349018852955671, "avg_score": null, "num_lines": null }
"""Admin definition for Smart Grid Game widget.""" from django.db import models from apps.managers.cache_mgr import cache_mgr from apps.managers.challenge_mgr import challenge_mgr from apps.widgets.smartgrid_design.views import designer_action_admin, \ designer_action_admin_list from django.contrib import admin from django import forms from django.forms.models import BaseInlineFormSet from django.forms.util import ErrorList from django.forms import TextInput, Textarea from django.db.utils import IntegrityError from apps.admin.admin import challenge_designer_site, challenge_manager_site, developer_site from apps.widgets.smartgrid_design.models import DesignerAction, DesignerActivity, \ DesignerTextPromptQuestion, DesignerCommitment, DesignerEvent, DesignerFiller, \ DesignerColumnName, DesignerLevel, DesignerQuestionChoice, Draft, DesignerColumnGrid, \ DesignerGrid from django.http import HttpResponseRedirect from apps.managers.predicate_mgr import predicate_mgr class DesignerDraftAdmin(admin.ModelAdmin): """Admin for Drafts.""" list_display = ["name", ] prepopulated_fields = {"slug": ("name",)} admin.site.register(Draft, DesignerDraftAdmin) challenge_designer_site.register(Draft, DesignerDraftAdmin) challenge_manager_site.register(Draft, DesignerDraftAdmin) developer_site.register(Draft, DesignerDraftAdmin) challenge_mgr.register_designer_challenge_info_model("Smart Grid Game Designer", 5, \ Draft, 1) challenge_mgr.register_developer_challenge_info_model("Smart Grid Game Designer", 4, \ Draft, 1) class DesignerActionAdmin(admin.ModelAdmin): """abstract admin for action.""" actions = ["delete_selected", "copy_action"] list_display = ["draft", "slug", "title", "type", "point_value"] search_fields = ["draft", "slug", "title"] list_filter = ['draft', 'type', ] def delete_selected(self, request, queryset): """override the delete selected.""" _ = request for obj in queryset: obj.delete() delete_selected.short_description = "Delete the selected objects." def copy_action(self, request, queryset): """Copy the selected Actions.""" _ = request for obj in queryset: obj.id = None slug = obj.slug obj.slug = slug + "-copy" try: obj.save() except IntegrityError: # How do we indicate an error to the admin? pass copy_action.short_description = "Copy selected Action(s)" def get_urls(self): return redirect_urls(self, "change") admin.site.register(DesignerAction, DesignerActionAdmin) challenge_designer_site.register(DesignerAction, DesignerActionAdmin) challenge_manager_site.register(DesignerAction, DesignerActionAdmin) developer_site.register(DesignerAction, DesignerActionAdmin) challenge_mgr.register_designer_challenge_info_model("Smart Grid Game Designer", 5, \ DesignerAction, 2) challenge_mgr.register_developer_challenge_info_model("Smart Grid Game Designer", 4, \ DesignerAction, 2) class DesignerActivityAdminForm(forms.ModelForm): """Activity Admin Form.""" class Meta: """Meta""" model = DesignerActivity def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] predicate_mgr.validate_form_predicates(data) return data def clean(self): """ Validates the admin form data based on a set of constraints. 1. If the verification type is "image" or "code", then a confirm prompt is required. 2. Publication date must be before expiration date. 3. Either points or a point range needs to be specified. """ super(DesignerActivityAdminForm, self).clean() # Data that has passed validation. cleaned_data = self.cleaned_data #1 Check the verification type. confirm_type = cleaned_data.get("confirm_type") prompt = cleaned_data.get("confirm_prompt") if confirm_type != "text" and len(prompt) == 0: self._errors["confirm_prompt"] = ErrorList( [u"This confirmation type requires a confirmation prompt."]) del cleaned_data["confirm_type"] del cleaned_data["confirm_prompt"] #2 Publication date must be before the expiration date. if "pub_date" in cleaned_data and "expire_date" in cleaned_data: pub_date = cleaned_data.get("pub_date") expire_date = cleaned_data.get("expire_date") if expire_date and pub_date >= expire_date: self._errors["expire_date"] = ErrorList( [u"The expiration date must be after the pub date."]) del cleaned_data["expire_date"] #3 Either points or a point range needs to be specified. points = cleaned_data.get("point_value") point_range_start = cleaned_data.get("point_range_start") point_range_end = cleaned_data.get("point_range_end") if not points and not (point_range_start or point_range_end): self._errors["point_value"] = ErrorList( [u"Either a point value or a range needs to be specified."]) del cleaned_data["point_value"] elif points and (point_range_start or point_range_end): self._errors["point_value"] = ErrorList( [u"Please specify either a point_value or a range."]) del cleaned_data["point_value"] elif not points: point_range_start = cleaned_data.get("point_range_start") point_range_end = cleaned_data.get("point_range_end") if not point_range_start: self._errors["point_range_start"] = ErrorList( [u"Please specify a start value for the point range."]) del cleaned_data["point_range_start"] elif not point_range_end: self._errors["point_range_end"] = ErrorList( [u"Please specify a end value for the point range."]) del cleaned_data["point_range_end"] elif point_range_start >= point_range_end: self._errors["point_range_start"] = ErrorList( [u"The start value must be less than the end value."]) del cleaned_data["point_range_start"] del cleaned_data["point_range_end"] return cleaned_data def save(self, *args, **kwargs): """save""" activity = super(DesignerActivityAdminForm, self).save(*args, **kwargs) activity.type = 'activity' activity.save() cache_mgr.clear() # If the activity's confirmation type is text, make sure to save the questions. if self.cleaned_data.get("confirm_type") == "text": self.save_m2m() return activity class DesignerTextQuestionInlineFormSet(BaseInlineFormSet): """Custom formset model to override validation.""" def clean(self): """Validates the form data and checks if the activity confirmation type is text.""" # Form that represents the activity. activity = self.instance if not activity.pk: # If the activity is not saved, we don't care if this validates. return # Count the number of questions. count = 0 for form in self.forms: try: if form.cleaned_data: count += 1 except AttributeError: pass if activity.confirm_type == "text" and count == 0: # Why did I do this? # activity.delete() raise forms.ValidationError( "At least one question is required if the activity's confirmation type is text.") elif activity.confirm_type != "text" and count > 0: # activity.delete() raise forms.ValidationError("Questions are not required for this confirmation type.") class TextQuestionInline(admin.TabularInline): """Text Question admin.""" model = DesignerTextPromptQuestion fieldset = ( (None, { 'fields': ('question', 'answer'), }) ) formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'rows': 2, 'cols': 70})}, } extra = 1 formset = DesignerTextQuestionInlineFormSet class DesignerActivityAdmin(admin.ModelAdmin): """Activity Admin""" fieldsets = ( ("Basic Information", {'fields': (('name', ), ('slug', 'related_resource'), ('title', 'expected_duration'), 'image', 'description', ('video_id', 'video_source'), 'embedded_widget', ('pub_date', 'expire_date'), ('unlock_condition', 'unlock_condition_text'), )}), ("Points", {"fields": (("point_value", "social_bonus"), ("point_range_start", "point_range_end"), )}), ("Admin Note", {'fields': ('admin_note',)}), ("Confirmation Type", {'fields': ('confirm_type', 'confirm_prompt')}), ) prepopulated_fields = {"slug": ("name",)} form = DesignerActivityAdminForm inlines = [TextQuestionInline] formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): return redirect_urls(self, "changelist") def response_change(self, request, obj): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) def response_add(self, request, obj, post_url_continue=None): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) admin.site.register(DesignerActivity, DesignerActivityAdmin) challenge_designer_site.register(DesignerActivity, DesignerActivityAdmin) challenge_manager_site.register(DesignerActivity, DesignerActivityAdmin) developer_site.register(DesignerActivity, DesignerActivityAdmin) class DesignerCommitmentAdminForm(forms.ModelForm): """admin form""" class Meta: """meta""" model = DesignerCommitment def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] predicate_mgr.validate_form_predicates(data) return data def save(self, *args, **kwargs): """save""" commitment = super(DesignerCommitmentAdminForm, self).save(*args, **kwargs) commitment.type = 'commitment' commitment.save() cache_mgr.clear() return commitment class DesignerCommitmentAdmin(admin.ModelAdmin): """Commitment Admin.""" fieldsets = ( ("Basic Information", { 'fields': (('name', ), ('slug', 'related_resource'), ('title', 'commitment_length'), 'image', 'description', 'unlock_condition', 'unlock_condition_text', ), }), ("Points", {"fields": (("point_value", 'social_bonus'), )}), ) form = DesignerCommitmentAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): """override the url definition.""" return redirect_urls(self, "changelist") def response_change(self, request, obj): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) def response_add(self, request, obj, post_url_continue=None): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) admin.site.register(DesignerCommitment, DesignerCommitmentAdmin) challenge_designer_site.register(DesignerCommitment, DesignerCommitmentAdmin) challenge_manager_site.register(DesignerCommitment, DesignerCommitmentAdmin) developer_site.register(DesignerCommitment, DesignerCommitmentAdmin) class DesignerEventAdminForm(forms.ModelForm): """Event Admin Form.""" class Meta: """Meta""" model = DesignerEvent def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] predicate_mgr.validate_form_predicates(data) return data def clean(self): """ Validates the admin form data based on a set of constraints. 1. Events must have an event date. 2. Publication date must be before expiration date. """ # Data that has passed validation. cleaned_data = self.cleaned_data #1 Check that an event has an event date. event_date = cleaned_data.get("event_date") has_date = "event_date" in cleaned_data # Check if this is in the data dict. if has_date and not event_date: self._errors["event_date"] = ErrorList([u"Events require an event date."]) del cleaned_data["event_date"] #2 Publication date must be before the expiration date. if "pub_date" in cleaned_data and "expire_date" in cleaned_data: pub_date = cleaned_data.get("pub_date") expire_date = cleaned_data.get("expire_date") if expire_date and pub_date >= expire_date: self._errors["expire_date"] = ErrorList( [u"The expiration date must be after the pub date."]) del cleaned_data["expire_date"] return cleaned_data def save(self, *args, **kwargs): """save""" event = super(DesignerEventAdminForm, self).save(*args, **kwargs) event.type = 'event' event.save() cache_mgr.clear() return event class DesignerEventAdmin(admin.ModelAdmin): """Event Admin""" fieldsets = ( ("Basic Information", {'fields': (('name', ), ('slug', 'related_resource'), ('title', 'expected_duration'), 'image', 'description', ('pub_date', 'expire_date'), ('event_date', 'event_location', 'event_max_seat'), ('unlock_condition', 'unlock_condition_text'), )}), ("Points", {"fields": (("point_value", "social_bonus"),)}), ) form = DesignerEventAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): return redirect_urls(self, "changelist") def response_change(self, request, obj): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) def response_add(self, request, obj, post_url_continue=None): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) admin.site.register(DesignerEvent, DesignerEventAdmin) challenge_designer_site.register(DesignerEvent, DesignerEventAdmin) challenge_manager_site.register(DesignerEvent, DesignerEventAdmin) developer_site.register(DesignerEvent, DesignerEventAdmin) class DesignerFillerAdminForm(forms.ModelForm): """admin form""" class Meta: """meta""" model = DesignerFiller def save(self, *args, **kwargs): """save""" filler = super(DesignerFillerAdminForm, self).save(*args, **kwargs) filler.type = 'filler' filler.unlock_condition = "False" filler.unlock_condition_text = "This cell is here only to fill out the grid. " \ "There is no action associated with it." filler.save() cache_mgr.clear() return filler class DesignerFillerAdmin(admin.ModelAdmin): """Commitment Admin.""" fieldsets = ( ("Basic Information", { 'fields': (('name', ), ('slug', ), ('title', ), ), }), ) prepopulated_fields = {"slug": ("name",)} form = DesignerFillerAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): """override the url definition.""" return redirect_urls(self, "changelist") def response_change(self, request, obj): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) def response_add(self, request, obj, post_url_continue=None): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) admin.site.register(DesignerFiller, DesignerFillerAdmin) challenge_designer_site.register(DesignerFiller, DesignerFillerAdmin) challenge_manager_site.register(DesignerFiller, DesignerFillerAdmin) developer_site.register(DesignerFiller, DesignerFillerAdmin) class DesignerColumnNameAdmin(admin.ModelAdmin): """DesignerColumnName Administration""" list_display = ["name", ] prepopulated_fields = {"slug": ("name",)} def response_change(self, request, obj): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) def response_add(self, request, obj, post_url_continue=None): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) admin.site.register(DesignerColumnName, DesignerColumnNameAdmin) challenge_designer_site.register(DesignerColumnName, DesignerColumnNameAdmin) challenge_manager_site.register(DesignerColumnName, DesignerColumnNameAdmin) developer_site.register(DesignerColumnName, DesignerColumnNameAdmin) class DesignerLevelAdminForm(forms.ModelForm): """admin form""" class Meta: """meta""" model = DesignerLevel def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] predicate_mgr.validate_form_predicates(data) return data class DesignerLevelAdmin(admin.ModelAdmin): """Level Admin""" list_display = ["draft", "name", "priority", "unlock_condition"] form = DesignerLevelAdminForm prepopulated_fields = {"slug": ("name",)} def response_change(self, request, obj): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) def response_add(self, request, obj, post_url_continue=None): """This makes the response go to the newly created model's change page without using reverse""" return HttpResponseRedirect("/sgg_designer/?draft=%s" % obj.draft.slug) admin.site.register(DesignerLevel, DesignerLevelAdmin) challenge_designer_site.register(DesignerLevel, DesignerLevelAdmin) challenge_manager_site.register(DesignerLevel, DesignerLevelAdmin) developer_site.register(DesignerLevel, DesignerLevelAdmin) challenge_mgr.register_designer_challenge_info_model("Smart Grid Game Designer", 4, \ DesignerLevel, 3) challenge_mgr.register_developer_challenge_info_model("Smart Grid Game Designer", 4, \ DesignerLevel, 3) class DesignerColumnGridAdminForm(forms.ModelForm): """Admin Form for DesignerColumnGrids.""" class Meta: """meta""" model = DesignerColumnGrid class DesignerColumnGridAdmin(admin.ModelAdmin): """DesignerColumnGrid Admin interface.""" list_display = ["draft", "level", "column", "name"] form = DesignerColumnGridAdminForm list_filter = ['draft', ] admin.site.register(DesignerColumnGrid, DesignerColumnGridAdmin) developer_site.register(DesignerColumnGrid, DesignerColumnGridAdmin) challenge_mgr.register_developer_challenge_info_model("Smart Grid Game Designer", 4, \ DesignerColumnGrid, 3) class DesignerGridAdminForm(forms.ModelForm): """Admin Form for DesignerGrid.""" class Meta: """meta""" model = DesignerGrid class DesignerGridAdmin(admin.ModelAdmin): """DesignerGrid Admin interface.""" list_display = ["draft", "level", "column", "row", "action"] form = DesignerGridAdminForm list_filter = ["draft", ] admin.site.register(DesignerGrid, DesignerGridAdmin) developer_site.register(DesignerGrid, DesignerGridAdmin) challenge_mgr.register_developer_challenge_info_model("Smart Grid Game Designer", 4, \ DesignerGrid, 4) class QuestionChoiceInline(admin.TabularInline): """Question Choice admin.""" model = DesignerQuestionChoice fieldset = ( (None, { 'fields': ('question', 'choice'), 'classes': ['wide', ], }) ) extra = 4 def redirect_urls(model_admin, url_type): """change the url redirection.""" from django.conf.urls import patterns, url from functools import update_wrapper def wrap(view): """wrap the view fuction.""" def wrapper(*args, **kwargs): """return the wrapper.""" return model_admin.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = model_admin.model._meta.app_label, model_admin.model._meta.module_name urlpatterns = patterns('', url(r'^$', wrap(designer_action_admin_list if url_type == "changelist" else \ model_admin.changelist_view), name='%s_%s_changelist' % info), url(r'^add/$', wrap(model_admin.add_view), name='%s_%s_add' % info), url(r'^(.+)/history/$', wrap(model_admin.history_view), name='%s_%s_history' % info), url(r'^(.+)/delete/$', wrap(model_admin.delete_view), name='%s_%s_delete' % info), url(r'^(.+)/$', wrap(designer_action_admin if url_type == "change" else model_admin.change_view), name='%s_%s_change' % info), ) return urlpatterns
{ "repo_name": "csdl/makahiki", "path": "makahiki/apps/widgets/smartgrid_design/admin.py", "copies": "2", "size": "23538", "license": "mit", "hash": 3619352038341596700, "line_mean": 36.4808917197, "line_max": 100, "alpha_frac": 0.6187866429, "autogenerated": false, "ratio": 4.253342970726418, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5872129613626418, "avg_score": null, "num_lines": null }
"""Admin definition for Smart Grid Game widget.""" from django.db import models from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext import markdown from apps.managers.cache_mgr import cache_mgr from apps.managers.challenge_mgr import challenge_mgr from apps.utils import utils from apps.widgets.smartgrid.models import ActionMember, Activity, Category, Event, \ Commitment, ConfirmationCode, TextPromptQuestion, \ QuestionChoice, Level, Action, Filler, \ EmailReminder, TextReminder from apps.widgets.smartgrid.views import action_admin, action_admin_list from django.contrib import admin from django import forms from django.forms.models import BaseInlineFormSet from django.forms.util import ErrorList from django.forms import TextInput, Textarea from django.core.urlresolvers import reverse from django.contrib import messages from django.db.utils import IntegrityError from apps.admin.admin import challenge_designer_site, challenge_manager_site, developer_site class ConfirmationCodeAdmin(admin.ModelAdmin): """admin for Bonus Points.""" actions = ["delete_selected", "view_selected", "print_selected"] list_display = ["pk", "code", "create_date", "is_active", "printed_or_distributed", "user"] ordering = ["-create_date", "is_active"] list_filter = ["is_active", "printed_or_distributed"] date_hierarchy = "create_date" def delete_selected(self, request, queryset): """override the delete selected method.""" _ = request for obj in queryset: obj.delete() delete_selected.short_description = "Delete the selected codes." def view_selected(self, request, queryset): """Views the Codes for printing.""" return render_to_response("admin/view_codes.html", { "activity": queryset[0].action, "codes": queryset, "per_page": 10, }, context_instance=RequestContext(request)) view_selected.short_description = "view the selected codes." def print_selected(self, request, queryset): """Changes the printed_or_distributed flag to True for the selected Confirmation Codes.""" _ = request queryset.update(printed_or_distributed=True) print_selected.short_description = "Set the printed or distributed flag." def view_codes(self, request, queryset): """Views the Codes for printing.""" _ = request _ = queryset response = HttpResponseRedirect(reverse("activity_view_codes", args=())) return response admin.site.register(ConfirmationCode, ConfirmationCodeAdmin) challenge_designer_site.register(ConfirmationCode, ConfirmationCodeAdmin) challenge_manager_site.register(ConfirmationCode, ConfirmationCodeAdmin) developer_site.register(ConfirmationCode, ConfirmationCodeAdmin) class TextQuestionInlineFormSet(BaseInlineFormSet): """Custom formset model to override validation.""" def clean(self): """Validates the form data and checks if the activity confirmation type is text.""" # Form that represents the activity. activity = self.instance if not activity.pk: # If the activity is not saved, we don't care if this validates. return # Count the number of questions. count = 0 for form in self.forms: try: if form.cleaned_data: count += 1 except AttributeError: pass if activity.confirm_type == "text" and count == 0: # Why did I do this? # activity.delete() raise forms.ValidationError( "At least one question is required if the activity's confirmation type is text.") elif activity.confirm_type != "text" and count > 0: # activity.delete() raise forms.ValidationError("Questions are not required for this confirmation type.") class QuestionChoiceInline(admin.TabularInline): """Question Choice admin.""" model = QuestionChoice fieldset = ( (None, { 'fields': ('question', 'choice'), 'classes': ['wide', ], }) ) extra = 4 class TextQuestionInline(admin.TabularInline): """Text Question admin.""" model = TextPromptQuestion fieldset = ( (None, { 'fields': ('question', 'answer'), }) ) formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'rows': 2, 'cols': 70})}, } extra = 1 formset = TextQuestionInlineFormSet class ActivityAdminForm(forms.ModelForm): """Activity Admin Form.""" class Meta: """Meta""" model = Activity def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] utils.validate_form_predicates(data) return data def clean(self): """ Validates the admin form data based on a set of constraints. 1. If the verification type is "image" or "code", then a confirm prompt is required. 2. Publication date must be before expiration date. 3. Either points or a point range needs to be specified. """ super(ActivityAdminForm, self).clean() # Data that has passed validation. cleaned_data = self.cleaned_data #1 Check the verification type. confirm_type = cleaned_data.get("confirm_type") prompt = cleaned_data.get("confirm_prompt") if confirm_type != "text" and len(prompt) == 0: self._errors["confirm_prompt"] = ErrorList( [u"This confirmation type requires a confirmation prompt."]) del cleaned_data["confirm_type"] del cleaned_data["confirm_prompt"] #2 Publication date must be before the expiration date. if "pub_date" in cleaned_data and "expire_date" in cleaned_data: pub_date = cleaned_data.get("pub_date") expire_date = cleaned_data.get("expire_date") if expire_date and pub_date >= expire_date: self._errors["expire_date"] = ErrorList( [u"The expiration date must be after the pub date."]) del cleaned_data["expire_date"] #3 Either points or a point range needs to be specified. points = cleaned_data.get("point_value") point_range_start = cleaned_data.get("point_range_start") point_range_end = cleaned_data.get("point_range_end") if not points and not (point_range_start or point_range_end): self._errors["point_value"] = ErrorList( [u"Either a point value or a range needs to be specified."]) del cleaned_data["point_value"] elif points and (point_range_start or point_range_end): self._errors["point_value"] = ErrorList( [u"Please specify either a point_value or a range."]) del cleaned_data["point_value"] elif not points: point_range_start = cleaned_data.get("point_range_start") point_range_end = cleaned_data.get("point_range_end") if not point_range_start: self._errors["point_range_start"] = ErrorList( [u"Please specify a start value for the point range."]) del cleaned_data["point_range_start"] elif not point_range_end: self._errors["point_range_end"] = ErrorList( [u"Please specify a end value for the point range."]) del cleaned_data["point_range_end"] elif point_range_start >= point_range_end: self._errors["point_range_start"] = ErrorList( [u"The start value must be less than the end value."]) del cleaned_data["point_range_start"] del cleaned_data["point_range_end"] return cleaned_data def save(self, *args, **kwargs): activity = super(ActivityAdminForm, self).save(*args, **kwargs) activity.type = "activity" activity.save() cache_mgr.clear() # If the activity's confirmation type is text, make sure to save the questions. if self.cleaned_data.get("confirm_type") == "text": self.save_m2m() return activity class EventAdminForm(forms.ModelForm): """Event Admin Form.""" class Meta: """Meta""" model = Event def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] utils.validate_form_predicates(data) return data def clean(self): """ Validates the admin form data based on a set of constraints. 1. Events must have an event date. 2. Publication date must be before expiration date. """ # Data that has passed validation. cleaned_data = self.cleaned_data #1 Check that an event has an event date. event_date = cleaned_data.get("event_date") has_date = "event_date" in cleaned_data # Check if this is in the data dict. if has_date and not event_date: self._errors["event_date"] = ErrorList([u"Events require an event date."]) del cleaned_data["event_date"] #2 Publication date must be before the expiration date. if "pub_date" in cleaned_data and "expire_date" in cleaned_data: pub_date = cleaned_data.get("pub_date") expire_date = cleaned_data.get("expire_date") if expire_date and pub_date >= expire_date: self._errors["expire_date"] = ErrorList( [u"The expiration date must be after the pub date."]) del cleaned_data["expire_date"] return cleaned_data def save(self, *args, **kwargs): event = super(EventAdminForm, self).save(*args, **kwargs) if event.is_excursion: event.type = "excursion" else: event.type = "event" event.save() cache_mgr.clear() return event class CommitmentAdminForm(forms.ModelForm): """admin form""" class Meta: """meta""" model = Commitment def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] utils.validate_form_predicates(data) return data def save(self, *args, **kwargs): commitment = super(CommitmentAdminForm, self).save(*args, **kwargs) commitment.type = "commitment" commitment.save() cache_mgr.clear() return commitment class FillerAdminForm(forms.ModelForm): """admin form""" class Meta: """meta""" model = Filler def save(self, *args, **kwargs): filler = super(FillerAdminForm, self).save(*args, **kwargs) filler.type = "filler" filler.unlock_condition = "False" filler.unlock_condition_text = "This cell is here only to fill out the grid. " \ "There is no action associated with it." filler.save() cache_mgr.clear() return filler class LevelAdminForm(forms.ModelForm): """admin form""" class Meta: """meta""" model = Level def clean_unlock_condition(self): """Validates the unlock conditions of the action.""" data = self.cleaned_data["unlock_condition"] utils.validate_form_predicates(data) return data class LevelAdmin(admin.ModelAdmin): """Level Admin""" list_display = ["name", "priority", "unlock_condition"] form = LevelAdminForm admin.site.register(Level, LevelAdmin) challenge_designer_site.register(Level, LevelAdmin) challenge_manager_site.register(Level, LevelAdmin) developer_site.register(Level, LevelAdmin) challenge_mgr.register_designer_game_info_model("Smart Grid Game", Level) challenge_mgr.register_developer_game_info_model("Smart Grid Game", Level) class CategoryAdmin(admin.ModelAdmin): """Category Admin""" list_display = ["name", "priority"] prepopulated_fields = {"slug": ("name",)} admin.site.register(Category, CategoryAdmin) challenge_designer_site.register(Category, CategoryAdmin) challenge_manager_site.register(Category, CategoryAdmin) developer_site.register(Category, CategoryAdmin) challenge_mgr.register_designer_game_info_model("Smart Grid Game", Category) challenge_mgr.register_developer_game_info_model("Smart Grid Game", Category) def redirect_urls(model_admin, url_type): """change the url redirection.""" from django.conf.urls.defaults import patterns, url from functools import update_wrapper def wrap(view): """wrap the view fuction.""" def wrapper(*args, **kwargs): """return the wrapper.""" return model_admin.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = model_admin.model._meta.app_label, model_admin.model._meta.module_name urlpatterns = patterns('', url(r'^$', wrap(action_admin_list if url_type == "changelist" else model_admin.changelist_view), name='%s_%s_changelist' % info), url(r'^add/$', wrap(model_admin.add_view), name='%s_%s_add' % info), url(r'^(.+)/history/$', wrap(model_admin.history_view), name='%s_%s_history' % info), url(r'^(.+)/delete/$', wrap(model_admin.delete_view), name='%s_%s_delete' % info), url(r'^(.+)/$', wrap(action_admin if url_type == "change" else model_admin.change_view), name='%s_%s_change' % info), ) return urlpatterns class ActionAdmin(admin.ModelAdmin): """abstract admin for action.""" actions = ["delete_selected", "increment_priority", "decrement_priority", "change_level", "change_category", "clear_level", "clear_category", "clear_level_category", "copy_action"] list_display = ["slug", "title", "level", "category", "priority", "type", "point_value"] search_fields = ["slug", "title"] list_filter = ["type", 'level', 'category'] def delete_selected(self, request, queryset): """override the delete selected.""" _ = request for obj in queryset: obj.delete() delete_selected.short_description = "Delete the selected objects." def increment_priority(self, request, queryset): """increment priority.""" _ = request for obj in queryset: obj.priority += 1 obj.save() increment_priority.short_description = "Increment selected objects' priority by 1." def decrement_priority(self, request, queryset): """decrement priority.""" _ = request for obj in queryset: obj.priority -= 1 obj.save() decrement_priority.short_description = "Decrement selected objects' priority by 1." def clear_level(self, request, queryset): """decrement priority.""" _ = request for obj in queryset: obj.level = None obj.save() clear_level.short_description = "Set the level to (None)." def clear_category(self, request, queryset): """decrement priority.""" _ = request for obj in queryset: obj.category = None obj.save() clear_category.short_description = "Set the category to (None)." def clear_level_category(self, request, queryset): """decrement priority.""" _ = request for obj in queryset: obj.level = None obj.category = None obj.save() clear_level_category.short_description = "Set the level and category to (None)." def change_level(self, request, queryset): """change level.""" _ = queryset selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME) return HttpResponseRedirect(reverse("bulk_change", args=("action", "level",)) + "?ids=%s" % (",".join(selected))) change_level.short_description = "Change the level." def change_category(self, request, queryset): """change level.""" _ = queryset selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME) return HttpResponseRedirect(reverse("bulk_change", args=("action", "category",)) + "?ids=%s" % (",".join(selected))) change_category.short_description = "Change the category." def copy_action(self, request, queryset): """Copy the selected Actions.""" _ = request for obj in queryset: obj.id = None obj.level = None obj.category = None slug = obj.slug obj.slug = slug + "-copy" try: obj.save() except IntegrityError: # How do we indicate an error to the admin? pass copy_action.short_description = "Copy selected Action(s)" def get_urls(self): return redirect_urls(self, "change") class ActivityAdmin(admin.ModelAdmin): """Activity Admin""" fieldsets = ( ("Basic Information", {'fields': (('name', ), ('slug', 'related_resource'), ('title', 'duration'), 'image', 'description', ('video_id', 'video_source'), 'embedded_widget', ('pub_date', 'expire_date'), ('unlock_condition', 'unlock_condition_text'), )}), ("Points", {"fields": (("point_value", "social_bonus"), ("point_range_start", "point_range_end"), )}), ("Ordering", {"fields": (("level", "category", "priority"), )}), ("Admin Note", {'fields': ('admin_note',)}), ("Confirmation Type", {'fields': ('confirm_type', 'confirm_prompt')}), ) prepopulated_fields = {"slug": ("name",)} form = ActivityAdminForm inlines = [TextQuestionInline] formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): return redirect_urls(self, "changelist") admin.site.register(Action, ActionAdmin) challenge_designer_site.register(Action, ActionAdmin) challenge_manager_site.register(Action, ActionAdmin) developer_site.register(Action, ActionAdmin) challenge_mgr.register_designer_game_info_model("Smart Grid Game", Action) challenge_mgr.register_developer_game_info_model("Smart Grid Game", Action) admin.site.register(Activity, ActivityAdmin) challenge_designer_site.register(Activity, ActivityAdmin) challenge_manager_site.register(Activity, ActivityAdmin) developer_site.register(Activity, ActivityAdmin) class EventAdmin(admin.ModelAdmin): """Event Admin""" fieldsets = ( ("Basic Information", {'fields': (('name', "is_excursion"), ('slug', 'related_resource'), ('title', 'duration'), 'image', 'description', ('pub_date', 'expire_date'), ('event_date', 'event_location', 'event_max_seat'), ('unlock_condition', 'unlock_condition_text'), )}), ("Points", {"fields": (("point_value", "social_bonus"),)}), ("Ordering", {"fields": (("level", "category", "priority"), )}), ) prepopulated_fields = {"slug": ("name",)} form = EventAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): return redirect_urls(self, "changelist") admin.site.register(Event, EventAdmin) challenge_designer_site.register(Event, EventAdmin) challenge_manager_site.register(Event, EventAdmin) developer_site.register(Event, EventAdmin) class CommitmentAdmin(admin.ModelAdmin): """Commitment Admin.""" fieldsets = ( ("Basic Information", { 'fields': (('name', ), ('slug', 'related_resource'), ('title', 'duration'), 'image', 'description', 'unlock_condition', 'unlock_condition_text', ), }), ("Points", {"fields": (("point_value", 'social_bonus'), )}), ("Ordering", {"fields": (("level", "category", "priority"), )}), ) prepopulated_fields = {"slug": ("name",)} form = CommitmentAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): """override the url definition.""" return redirect_urls(self, "changelist") admin.site.register(Commitment, CommitmentAdmin) challenge_designer_site.register(Commitment, CommitmentAdmin) challenge_manager_site.register(Commitment, CommitmentAdmin) developer_site.register(Commitment, CommitmentAdmin) class FillerAdmin(admin.ModelAdmin): """Commitment Admin.""" fieldsets = ( ("Basic Information", { 'fields': (('name', ), ('slug', ), ('title', ), ), }), ("Ordering", {"fields": (("level", "category", "priority"), )}), ) prepopulated_fields = {"slug": ("name",)} form = FillerAdminForm formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '80'})}, } def get_urls(self): """override the url definition.""" return redirect_urls(self, "changelist") admin.site.register(Filler, FillerAdmin) challenge_designer_site.register(Filler, FillerAdmin) challenge_manager_site.register(Filler, FillerAdmin) developer_site.register(Filler, FillerAdmin) class ActionMemberAdminForm(forms.ModelForm): """Activity Member admin.""" def __init__(self, *args, **kwargs): """Override to dynamically change the form if the activity specifies a point range..""" super(ActionMemberAdminForm, self).__init__(*args, **kwargs) # Instance points to an instance of the model. member = self.instance if member and member.action: action = member.action message = "Specify the number of points to award. " if not action.point_value: message += "This default points for this action should be between %d and %d." % ( action.activity.point_range_start, action.activity.point_range_end) else: message += "The default points for this action is %d." % ( action.point_value) self.fields["points_awarded"].help_text = message class Meta: """Meta""" model = ActionMember def clean(self): """Custom validator that checks values for variable point activities.""" # Data that has passed validation. cleaned_data = self.cleaned_data status = cleaned_data.get("approval_status") action = self.instance.action if status == "approved" and not action.point_value: # Check if the point value is filled in. if "points_awarded" not in cleaned_data: self._errors["points_awarded"] = ErrorList( [u"This action requires that you specify the number of points to award."]) # Check if the point value is valid. elif cleaned_data["points_awarded"] < action.activity.point_range_start or \ cleaned_data["points_awarded"] > action.activity.point_range_end: message = "The points to award must be between %d and %d" % ( action.activity.point_range_start, action.activity.point_range_end) self._errors["points_awarded"] = ErrorList([message]) del cleaned_data["points_awarded"] return cleaned_data class ActionMemberAdmin(admin.ModelAdmin): """ActionMember Admin.""" radio_fields = {"approval_status": admin.HORIZONTAL} readonly_fields = ( "user", "action", "admin_link", "question", "admin_note", "full_response", "social_email") list_display = ( "action", "submission_date", "user_link", "approval_status", "short_question", "short_response") list_filter = ["approval_status", "action__type"] actions = ["approve_selected", "delete_selected"] search_fields = ["action__slug", "action__title", "user__username"] date_hierarchy = "submission_date" ordering = ["submission_date"] form = ActionMemberAdminForm def get_object(self, request, object_id): obj = super(ActionMemberAdmin, self).get_object(request, object_id) if obj and not obj.points_awarded: obj.points_awarded = obj.action.point_value return obj def short_question(self, obj): """return the short question.""" return "%s" % (obj.question) short_question.short_description = 'Question' def short_response(self, obj): """return the short response""" return "%s" % obj.response[:160] short_response.short_description = 'Response' def full_response(self, obj): """return the full response.""" return "%s" % (obj.response).replace("\n", "<br/>") full_response.short_description = 'Response' full_response.allow_tags = True def admin_note(self, obj): """return the short question.""" if obj.action.activity.admin_note: note = markdown.markdown(obj.action.activity.admin_note) else: note = None return "%s<a href='/admin/smartgrid/activity/%d'> [Edit Admin Note]</a>" % \ (note, obj.action.pk) admin_note.short_description = 'Admin note' admin_note.allow_tags = True def changelist_view(self, request, extra_context=None): """ Set the default filter of the admin view to pending. Based on iridescent's answer to http://stackoverflow.com/questions/851636/default-filter-in-django-admin """ if 'HTTP_REFERER' in request.META and 'PATH_INFO' in request.META: test = request.META['HTTP_REFERER'].split(request.META['PATH_INFO']) if test[-1] and test[-1].startswith('?'): return super(ActionMemberAdmin, self).changelist_view(request, extra_context=extra_context) if not 'approval_status__exact' in request.GET: q = request.GET.copy() q['approval_status__exact'] = 'pending' request.GET = q request.META['QUERY_STRING'] = request.GET.urlencode() if not 'action__type__exact' in request.GET: q = request.GET.copy() q['action__type__exact'] = 'activity' request.GET = q request.META['QUERY_STRING'] = request.GET.urlencode() return super(ActionMemberAdmin, self).changelist_view(request, extra_context=extra_context) def approve_selected(self, request, queryset): """delete priority.""" _ = request for obj in queryset: obj.approval_status = "approved" obj.admin_comment = "" obj.save() messages.success(request, "%s approved." % obj.action) approve_selected.short_description = "Approve the selected objects (USE CAUTIONS)" def delete_selected(self, request, queryset): """override the delete selected.""" _ = request for obj in queryset: obj.delete() delete_selected.short_description = "Delete the selected objects." def get_form(self, request, obj=None, **kwargs): """Override to remove the points_awarded field if the action does not have variable points.""" if obj and not obj.action.point_value: self.fields = ( "user", "action", "admin_link", "question", "admin_note", "full_response", "image", "social_email", "approval_status", "points_awarded", "admin_comment") else: if obj.action.type == "activity": self.fields = ( "user", "action", "admin_link", "question", "admin_note", "full_response", "image", "social_email", "approval_status", "points_awarded", "admin_comment") else: self.fields = ( "user", "action", "admin_link", "social_email", "completion_date", "points_awarded", "approval_status") return super(ActionMemberAdmin, self).get_form(request, obj, **kwargs) admin.site.register(ActionMember, ActionMemberAdmin) challenge_designer_site.register(ActionMember, ActionMemberAdmin) challenge_manager_site.register(ActionMember, ActionMemberAdmin) developer_site.register(ActionMember, ActionMemberAdmin) challenge_mgr.register_admin_game_info_model("Smart Grid Game", ActionMember) challenge_mgr.register_developer_game_info_model("Smart Grid Game", ActionMember) class EmailReminderAdmin(admin.ModelAdmin): """reminder admin""" readonly_fields = ('user', 'action', 'sent') fields = ("send_at", "email_address", 'user', 'action', 'sent') list_display = ('send_at', 'user', 'email_address', 'action', 'sent') search_fields = ('user__username', 'email_address', 'action__title') class TextReminderAdmin(admin.ModelAdmin): """reminder admin""" readonly_fields = ('user', 'action', 'sent') fields = ("send_at", "text_number", 'user', 'action', 'sent') list_display = ('send_at', 'user', 'text_number', 'action', 'sent') search_fields = ('user__username', 'text_number', 'action__title') admin.site.register(EmailReminder, EmailReminderAdmin) challenge_designer_site.register(EmailReminder, EmailReminderAdmin) challenge_manager_site.register(EmailReminder, EmailReminderAdmin) developer_site.register(EmailReminder, EmailReminderAdmin) admin.site.register(TextReminder, TextReminderAdmin) challenge_designer_site.register(TextReminder, TextReminderAdmin) challenge_manager_site.register(TextReminder, TextReminderAdmin) developer_site.register(TextReminder, TextReminderAdmin) challenge_mgr.register_admin_challenge_info_model("Notifications", 2, EmailReminder, 2) challenge_mgr.register_admin_challenge_info_model("Notifications", 2, TextReminder, 3) challenge_mgr.register_developer_challenge_info_model("Status", 3, EmailReminder, 7) challenge_mgr.register_developer_challenge_info_model("Status", 3, TextReminder, 8)
{ "repo_name": "KendyllD/boukenda-project", "path": "makahiki/apps/widgets/smartgrid/admin.py", "copies": "5", "size": "31229", "license": "mit", "hash": 8717994276306669000, "line_mean": 36.0011848341, "line_max": 100, "alpha_frac": 0.6034134939, "autogenerated": false, "ratio": 4.217855213398163, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0008886609542019539, "num_lines": 844 }
"""Admin definitions for the Skipjack usage in Django's admin site.""" from django.conf import settings from django.contrib import admin from django.contrib.admin import helpers from django.contrib.admin.util import get_deleted_objects from django.contrib import messages from django.core.exceptions import PermissionDenied from django.db import router from django.template.response import TemplateResponse from django.utils.encoding import force_unicode from django.utils.translation import ugettext_lazy as _ from skipjack.models import Transaction, TransactionError """ #-------------------------------------------- # SimpleListFilter is available in Django 1.4+ from django.contrib.admin import SimpleListFilter class IsApprovedListFilter(SimpleListFilter): title = _('Approved transactions') # Parameter for the filter that will be used in the URL query. parameter_name = 'is_approved' def lookups(self, request, model_admin): "Filter based on our is_approved method." return ( (True, _('yes')), (False, _('no')), ) def queryset(self, request, queryset): "Filter based on the is_approved logic." return queryset.filter(approved='1').exclude(auth_code='', auth_response_code='') #-------------------------------------------- """ class TransactionAdmin(admin.ModelAdmin): """Admin model for the Transaction model.""" actions = ['delete_transactions', 'refund_transactions', 'settle_transactions', 'update_transactions'] search_fields = ('transaction_id', 'amount', 'order_number', 'auth_code', 'auth_response_code') date_hierarchy = 'creation_date' list_display = ('transaction_id', 'order_number', 'approved', 'is_approved', 'auth_code', 'current_status', 'pending_status', 'amount', 'creation_date', 'mod_date', 'is_live', 'return_code') list_filter = ('is_live', 'approved', 'creation_date', 'current_status', 'pending_status') readonly_fields = ('transaction_id', 'auth_code', 'amount', 'auth_decline_message', 'avs_code', 'avs_message', 'order_number', 'auth_response_code', 'approved', 'cvv2_response_code', 'cvv2_response_message', 'return_code', 'cavv_response', 'is_live', 'creation_date', 'mod_date', 'status_text', 'status_date', 'current_status', 'pending_status') fieldsets = ( (None, { 'fields': (('transaction_id', 'return_code', 'is_live'), 'creation_date', 'amount') }), (_('Authorization'), { 'classes': ('collapse', 'collapse-closed', 'wide',), 'fields' : (('approved', 'auth_decline_message', 'auth_code', 'auth_response_code'), ) }), (_('Card verification value (CVV2)'), { 'classes': ('collapse', 'collapse-closed', 'wide',), 'fields' : [('cvv2_response_code', 'cvv2_response_message')] }), (_('Address verification service (AVS)'), { 'classes': ('collapse', 'collapse-closed', 'wide',), 'fields' : [('avs_code', 'avs_message',)] }), (_('Status'), { 'classes': ('collapse', 'collapse-closed', 'wide',), 'fields' : (('status_text', 'status_date'), ('current_status', 'pending_status')) }), ) def is_approved(self, object_): """ Transform Transaction.is_approved into a boolean for display purposes. See: http://www.peterbe.com/plog/dislike-for-booleans-and-django-admin """ return object_.is_approved is_approved.short_description = u'Approved?' is_approved.boolean = True def get_actions(self, request): """Don't use the generic delete_selected action.""" actions = super(TransactionAdmin, self).get_actions(request) if 'delete_selected' in actions: del actions['delete_selected'] return actions def delete_transactions(self, request, queryset): """ Delete transactions, ensuring we delete them from Skipjack. Offers up a confirmation page. Basically ripped from `django.contrib.admin.actions.delete_selected`. Supports the standard Django admin and the Grappelli look and feel with templates for both provided and selected automatically. """ opts = self.model._meta app_label = opts.app_label # Check that the user has the delete permission. if not self.has_delete_permission(request): raise PermissionDenied using = router.db_for_write(self.model) # Populate deletable_objects, a data structure of all related objects # that will also be deleted. deletable_objects, perms_needed, protected = get_deleted_objects( queryset, opts, request.user, self.admin_site, using) # The user has already confirmed the deletion. # Do the deletion and return None to display the change list view again. if request.POST.get('post'): rows_updated = 0 for obj in queryset: obj_display = force_unicode(obj) self.log_deletion(request, obj, obj_display) # NB: obj.delete() calls obj.delete_transaction() # which deletes the Transaction from Skipjack if possible. try: obj.delete() rows_updated += 1 except TransactionError: messages.error(request, "Transaction %s could not be deleted." % obj.transaction_id) # Send a success message. if rows_updated > 0: if rows_updated == 1: message_bit = "1 transaction was" else: message_bit = "%s transactions were" % rows_updated messages.success(request, "%s successfully deleted." % message_bit) # Return None to display the change list page again. return None if len(queryset) == 1: objects_name = force_unicode(opts.verbose_name) else: objects_name = force_unicode(opts.verbose_name_plural) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": objects_name} else: title = _("Are you sure?") context = { "title": title, "objects_name": objects_name, "deletable_objects": [deletable_objects], 'queryset': queryset, "perms_lacking": perms_needed, "protected": protected, "opts": opts, "app_label": app_label, "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME, } # Display the confirmation page if "grappelli" in settings.INSTALLED_APPS: template_list = [ "admin/%s/%s/delete_selected_transactions.grp.html" % ( app_label, opts.object_name.lower()), "admin/%s/delete_selected_transactions.grp.html" % app_label, "admin/delete_selected_transactions.grp.html"] else: template_list = [ "admin/%s/%s/delete_selected_transactions.html" % ( app_label, opts.object_name.lower()), "admin/%s/delete_selected_transactions.html" % app_label, "admin/delete_selected_transactions.html"] return TemplateResponse(request, template_list, context, current_app=self.admin_site.name) delete_transactions.short_description = "Delete selected transactions..." def settle_transactions(self, request, queryset): """Settle (Charge) selected transactions with Skipjack.""" rows_updated = 0 for obj in queryset: try: obj.settle() self.log_change(request, obj, 'Settled %s' % force_unicode(obj)) rows_updated += 1 except TransactionError: messages.error(request, "Transaction %s could not be settled." % obj.transaction_id) obj.update_status() # Send a success message. if rows_updated > 0: if rows_updated == 1: message_bit = "1 transaction was" else: message_bit = "%s transactions were" % rows_updated messages.success(request, "%s successfully added to the " \ "settlement que." % message_bit) settle_transactions.short_description = "Settle selected transactions" def refund_transactions(self, request, queryset): """Fully refund selected transactions with Skipjack.""" opts = self.model._meta app_label = opts.app_label # Check that the user has the change permission. if not self.has_change_permission(request): raise PermissionDenied # The user has already confirmed the refunds. # Do the refunds and return None to display the change list view again. if request.POST.get('post'): rows_updated = 0 for obj in queryset: try: obj.refund() self.log_change(request, obj, 'Refunded %s' % force_unicode(obj)) rows_updated += 1 except TransactionError: messages.error(request, "Transaction %s could not be refunded." % obj.transaction_id) obj.update_status() # Send a success message. if rows_updated > 0: if rows_updated == 1: message_bit = "1 transaction was" else: message_bit = "%s transactions were" % rows_updated messages.success(request, "%s successfully refunded." % message_bit) # Return None to display the change list page again. return None if len(queryset) == 1: objects_name = force_unicode(opts.verbose_name) else: objects_name = force_unicode(opts.verbose_name_plural) title = _("Are you sure?") change_url_name = '%s:%s_%s_change' % (self.admin_site.name, opts.app_label, opts.object_name.lower()) context = { "title": title, "objects_name": objects_name, "queryset": queryset, "opts": opts, "app_label": app_label, "change_url_name": change_url_name, "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME, } # Display the confirmation page if "grappelli" in settings.INSTALLED_APPS: template_list = [ "admin/%s/%s/refund_selected_transactions.grp.html" % ( app_label, opts.object_name.lower()), "admin/%s/refund_selected_transactions.grp.html" % app_label, "admin/refund_selected_transactions.grp.html"] else: template_list = [ "admin/%s/%s/refund_selected_transactions.html" % ( app_label, opts.object_name.lower()), "admin/%s/refund_selected_transactions.html" % app_label, "admin/refund_selected_transactions.html"] return TemplateResponse(request, template_list, context, current_app=self.admin_site.name) refund_transactions.short_description = "Refund selected transactions..." def update_transactions(self, request, queryset): """Update the status of selected transactions with Skipjack.""" rows_updated = 0 for obj in queryset: try: obj.update_status() self.log_change(request, obj, 'Updated %s' % force_unicode(obj)) rows_updated += 1 except TransactionError: messages.error(request, "Transaction %s could not be updated." % obj.transaction_id) # Send a success message. if rows_updated > 0: if rows_updated == 1: message_bit = "1 transaction was" else: message_bit = "%s transactions were" % rows_updated messages.success(request, "%s successfully updated." % message_bit) update_transactions.short_description = "Update status of selected transactions" admin.site.register(Transaction, TransactionAdmin)
{ "repo_name": "richardbolt/django-skipjack", "path": "skipjack/admin.py", "copies": "1", "size": "14058", "license": "mit", "hash": -3064137480732968400, "line_mean": 40.9641791045, "line_max": 84, "alpha_frac": 0.5123772941, "autogenerated": false, "ratio": 4.908519553072626, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5920896847172626, "avg_score": null, "num_lines": null }
"""Admin extensions for django-reversion.""" from functools import partial from django import template from django.db import models, transaction, connection from django.conf.urls.defaults import patterns, url from django.contrib import admin from django.contrib.admin import helpers, options from django.contrib.admin.util import unquote, quote from django.contrib.contenttypes.generic import GenericInlineModelAdmin, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.core.exceptions import ImproperlyConfigured from django.forms.formsets import all_valid from django.forms.models import model_to_dict from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render_to_response from django.utils.dateformat import format from django.utils.html import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext as _ from django.utils.encoding import force_unicode from reversion.models import Revision, Version, has_int_pk, VERSION_ADD, VERSION_CHANGE, VERSION_DELETE from reversion.revisions import default_revision_manager, RegistrationError class VersionAdmin(admin.ModelAdmin): """Abstract admin class for handling version controlled models.""" object_history_template = "reversion/object_history.html" change_list_template = "reversion/change_list.html" revision_form_template = None recover_list_template = None recover_form_template = None # The revision manager instance used to manage revisions. revision_manager = default_revision_manager # The serialization format to use when registering models with reversion. reversion_format = "json" # Whether to ignore duplicate revision data. ignore_duplicate_revisions = False # If True, then the default ordering of object_history and recover lists will be reversed. history_latest_first = False def _autoregister(self, model, follow=None): """Registers a model with reversion, if required.""" if model._meta.proxy: raise RegistrationError("Proxy models cannot be used with django-reversion, register the parent class instead") if not self.revision_manager.is_registered(model): follow = follow or [] for parent_cls, field in model._meta.parents.items(): follow.append(field.name) self._autoregister(parent_cls) self.revision_manager.register(model, follow=follow, format=self.reversion_format) @property def revision_context_manager(self): """The revision context manager for this VersionAdmin.""" return self.revision_manager._revision_context_manager def __init__(self, *args, **kwargs): """Initializes the VersionAdmin""" super(VersionAdmin, self).__init__(*args, **kwargs) # Automatically register models if required. if not self.revision_manager.is_registered(self.model): inline_fields = [] for inline in self.inlines: inline_model = inline.model self._autoregister(inline_model) if issubclass(inline, GenericInlineModelAdmin): ct_field = inline.ct_field ct_fk_field = inline.ct_fk_field for field in self.model._meta.many_to_many: if isinstance(field, GenericRelation) and field.rel.to == inline_model and field.object_id_field_name == ct_fk_field and field.content_type_field_name == ct_field: inline_fields.append(field.name) elif issubclass(inline, options.InlineModelAdmin): fk_name = inline.fk_name if not fk_name: for field in inline_model._meta.fields: if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(self.model, field.rel.to): fk_name = field.name if not inline_model._meta.get_field(fk_name).rel.is_hidden(): accessor = inline_model._meta.get_field(fk_name).related.get_accessor_name() inline_fields.append(accessor) self._autoregister(self.model, inline_fields) # Wrap own methods in manual revision management. self.add_view = self.revision_context_manager.create_revision(manage_manually=True)(self.add_view) self.change_view = self.revision_context_manager.create_revision(manage_manually=True)(self.change_view) self.delete_view = self.revision_context_manager.create_revision(manage_manually=True)(self.delete_view) self.recover_view = self.revision_context_manager.create_revision(manage_manually=True)(self.recover_view) self.revision_view = self.revision_context_manager.create_revision(manage_manually=True)(self.revision_view) self.changelist_view = self.revision_context_manager.create_revision(manage_manually=True)(self.changelist_view) def _get_template_list(self, template_name): opts = self.model._meta return ( "reversion/%s/%s/%s" % (opts.app_label, opts.object_name.lower(), template_name), "reversion/%s/%s" % (opts.app_label, template_name), "reversion/%s" % template_name, ) def get_urls(self): """Returns the additional urls used by the Reversion admin.""" urls = super(VersionAdmin, self).get_urls() admin_site = self.admin_site opts = self.model._meta info = opts.app_label, opts.module_name, reversion_urls = patterns("", url("^recover/$", admin_site.admin_view(self.recoverlist_view), name='%s_%s_recoverlist' % info), url("^recover/([^/]+)/$", admin_site.admin_view(self.recover_view), name='%s_%s_recover' % info), url("^([^/]+)/history/([^/]+)/$", admin_site.admin_view(self.revision_view), name='%s_%s_revision' % info),) return reversion_urls + urls def get_revision_instances(self, request, object): """Returns all the instances to be used in the object's revision.""" return [object] def get_revision_data(self, request, object, flag): """Returns all the revision data to be used in the object's revision.""" return dict( (o, self.revision_manager.get_adapter(o.__class__).get_version_data(o, flag)) for o in self.get_revision_instances(request, object) ) def log_addition(self, request, object): """Sets the version meta information.""" super(VersionAdmin, self).log_addition(request, object) self.revision_manager.save_revision( self.get_revision_data(request, object, VERSION_ADD), user = request.user, comment = _(u"Initial version."), ignore_duplicates = self.ignore_duplicate_revisions, db = self.revision_context_manager.get_db(), ) def log_change(self, request, object, message): """Sets the version meta information.""" super(VersionAdmin, self).log_change(request, object, message) self.revision_manager.save_revision( self.get_revision_data(request, object, VERSION_CHANGE), user = request.user, comment = message, ignore_duplicates = self.ignore_duplicate_revisions, db = self.revision_context_manager.get_db(), ) def log_deletion(self, request, object, object_repr): """Sets the version meta information.""" super(VersionAdmin, self).log_deletion(request, object, object_repr) self.revision_manager.save_revision( self.get_revision_data(request, object, VERSION_DELETE), user = request.user, comment = _(u"Deleted %(verbose_name)s.") % {"verbose_name": self.model._meta.verbose_name}, ignore_duplicates = self.ignore_duplicate_revisions, db = self.revision_context_manager.get_db(), ) def _order_version_queryset(self, queryset): """Applies the correct ordering to the given version queryset.""" if self.history_latest_first: return queryset.order_by("-pk") return queryset.order_by("pk") def recoverlist_view(self, request, extra_context=None): """Displays a deleted model to allow recovery.""" model = self.model opts = model._meta deleted = self._order_version_queryset(self.revision_manager.get_deleted(self.model)) context = { "opts": opts, "app_label": opts.app_label, "module_name": capfirst(opts.verbose_name), "title": _("Recover deleted %(name)s") % {"name": force_unicode(opts.verbose_name_plural)}, "deleted": deleted, "changelist_url": reverse("%s:%s_%s_changelist" % (self.admin_site.name, opts.app_label, opts.module_name)), } extra_context = extra_context or {} context.update(extra_context) return render_to_response(self.recover_list_template or self._get_template_list("recover_list.html"), context, template.RequestContext(request)) def get_revision_form_data(self, request, obj, version): """ Returns a dictionary of data to set in the admin form in order to revert to the given revision. """ return version.field_dict def get_related_versions(self, obj, version, FormSet): """Retreives all the related Version objects for the given FormSet.""" object_id = obj.pk # Get the fk name. try: fk_name = FormSet.fk.name except AttributeError: # This is a GenericInlineFormset, or similar. fk_name = FormSet.ct_fk_field.name # Look up the revision data. revision_versions = version.revision.version_set.all() related_versions = dict([(related_version.object_id, related_version) for related_version in revision_versions if ContentType.objects.get_for_id(related_version.content_type_id).model_class() == FormSet.model and unicode(related_version.field_dict[fk_name]) == unicode(object_id)]) return related_versions def _hack_inline_formset_initial(self, FormSet, formset, obj, version, revert, recover): """Hacks the given formset to contain the correct initial data.""" # Now we hack it to push in the data from the revision! initial = [] related_versions = self.get_related_versions(obj, version, FormSet) formset.related_versions = related_versions for related_obj in formset.queryset: if unicode(related_obj.pk) in related_versions: initial.append(related_versions.pop(unicode(related_obj.pk)).field_dict) else: initial_data = model_to_dict(related_obj) initial_data["DELETE"] = True initial.append(initial_data) for related_version in related_versions.values(): initial_row = related_version.field_dict pk_name = ContentType.objects.get_for_id(related_version.content_type_id).model_class()._meta.pk.name del initial_row[pk_name] initial.append(initial_row) # Reconstruct the forms with the new revision data. formset.initial = initial formset.forms = [formset._construct_form(n) for n in xrange(len(initial))] # Hack the formset to force a save of everything. def get_changed_data(form): return [field.name for field in form.fields] for form in formset.forms: form.has_changed = lambda: True form._get_changed_data = partial(get_changed_data, form=form) def total_form_count_hack(count): return lambda: count formset.total_form_count = total_form_count_hack(len(initial)) def render_revision_form(self, request, obj, version, context, revert=False, recover=False): """Renders the object revision form.""" model = self.model opts = model._meta object_id = obj.pk # Generate the model form. ModelForm = self.get_form(request, obj) formsets = [] if request.method == "POST": # This section is copied directly from the model admin change view # method. Maybe one day there will be a hook for doing this better. form = ModelForm(request.POST, request.FILES, instance=obj, initial=self.get_revision_form_data(request, obj, version)) if form.is_valid(): form_validated = True new_object = self.save_form(request, form, change=True) # HACK: If the value of a file field is None, remove the file from the model. for field in new_object._meta.fields: if isinstance(field, models.FileField) and field.name in form.cleaned_data and form.cleaned_data[field.name] is None: setattr(new_object, field.name, None) else: form_validated = False new_object = obj prefixes = {} for FormSet, inline in zip(self.get_formsets(request, new_object), self.get_inline_instances(request)): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(request.POST, request.FILES, instance=new_object, prefix=prefix, queryset=inline.queryset(request)) self._hack_inline_formset_initial(FormSet, formset, obj, version, revert, recover) # Add this hacked formset to the form. formsets.append(formset) if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, change=True) form.save_m2m() for formset in formsets: # HACK: If the value of a file field is None, remove the file from the model. related_objects = formset.save(commit=False) for related_obj, related_form in zip(related_objects, formset.saved_forms): for field in related_obj._meta.fields: if isinstance(field, models.FileField) and field.name in related_form.cleaned_data and related_form.cleaned_data[field.name] is None: setattr(related_obj, field.name, None) related_obj.save() formset.save_m2m() change_message = _(u"Reverted to previous version, saved on %(datetime)s") % {"datetime": format(version.revision.date_created, _('DATETIME_FORMAT'))} self.log_change(request, new_object, change_message) self.message_user(request, _(u'The %(model)s "%(name)s" was reverted successfully. You may edit it again below.') % {"model": force_unicode(opts.verbose_name), "name": unicode(obj)}) # Redirect to the model change form. if revert: return HttpResponseRedirect("../../") elif recover: return HttpResponseRedirect("../../%s/" % quote(object_id)) else: assert False else: # This is a mutated version of the code in the standard model admin # change_view. Once again, a hook for this kind of functionality # would be nice. Unfortunately, it results in doubling the number # of queries required to construct the formets. form = ModelForm(instance=obj, initial=self.get_revision_form_data(request, obj, version)) prefixes = {} for FormSet, inline in zip(self.get_formsets(request, obj), self.get_inline_instances(request)): # This code is standard for creating the formset. prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(instance=obj, prefix=prefix, queryset=inline.queryset(request)) self._hack_inline_formset_initial(FormSet, formset, obj, version, revert, recover) # Add this hacked formset to the form. formsets.append(formset) # Generate admin form helper. adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields, self.get_readonly_fields(request, obj), model_admin=self) media = self.media + adminForm.media # Generate formset helpers. inline_admin_formsets = [] for inline, formset in zip(self.get_inline_instances(request), formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(inline.get_readonly_fields(request, obj)) prepopulated = inline.get_prepopulated_fields(request, obj) inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets, prepopulated, readonly, model_admin=self) inline_admin_formsets.append(inline_admin_formset) media = media + inline_admin_formset.media # Generate the context. context.update({"adminform": adminForm, "object_id": object_id, "original": obj, "is_popup": False, "media": mark_safe(media), "inline_admin_formsets": inline_admin_formsets, "errors": helpers.AdminErrorList(form, formsets), "app_label": opts.app_label, "add": False, "change": True, "revert": revert, "recover": recover, "has_add_permission": self.has_add_permission(request), "has_change_permission": self.has_change_permission(request, obj), "has_delete_permission": self.has_delete_permission(request, obj), "has_file_field": True, "has_absolute_url": False, "ordered_objects": opts.get_ordered_objects(), "form_url": mark_safe(request.path), "opts": opts, "content_type_id": ContentType.objects.get_for_model(self.model).id, "save_as": False, "save_on_top": self.save_on_top, "changelist_url": reverse("%s:%s_%s_changelist" % (self.admin_site.name, opts.app_label, opts.module_name)), "change_url": reverse("%s:%s_%s_change" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(obj.pk),)), "history_url": reverse("%s:%s_%s_history" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(obj.pk),)), "recoverlist_url": reverse("%s:%s_%s_recoverlist" % (self.admin_site.name, opts.app_label, opts.module_name))}) # Render the form. if revert: form_template = self.revision_form_template or self._get_template_list("revision_form.html") elif recover: form_template = self.recover_form_template or self._get_template_list("recover_form.html") else: assert False return render_to_response(form_template, context, template.RequestContext(request)) @transaction.commit_on_success def recover_view(self, request, version_id, extra_context=None): """Displays a form that can recover a deleted model.""" version = get_object_or_404(Version, pk=version_id) obj = version.object_version.object context = {"title": _("Recover %(name)s") % {"name": version.object_repr},} context.update(extra_context or {}) return self.render_revision_form(request, obj, version, context, recover=True) @transaction.commit_on_success def revision_view(self, request, object_id, version_id, extra_context=None): """Displays the contents of the given revision.""" object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F" obj = get_object_or_404(self.model, pk=object_id) version = get_object_or_404(Version, pk=version_id, object_id=unicode(obj.pk)) # Generate the context. context = {"title": _("Revert %(name)s") % {"name": force_unicode(self.model._meta.verbose_name)},} context.update(extra_context or {}) return self.render_revision_form(request, obj, version, context, revert=True) def changelist_view(self, request, extra_context=None): """Renders the change view.""" opts = self.model._meta context = {"recoverlist_url": reverse("%s:%s_%s_recoverlist" % (self.admin_site.name, opts.app_label, opts.module_name)), "add_url": reverse("%s:%s_%s_add" % (self.admin_site.name, opts.app_label, opts.module_name)),} context.update(extra_context or {}) return super(VersionAdmin, self).changelist_view(request, context) def history_view(self, request, object_id, extra_context=None): """Renders the history view.""" object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F" opts = self.model._meta action_list = [ { "revision": version.revision, "url": reverse("%s:%s_%s_revision" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(version.object_id), version.id)), } for version in self._order_version_queryset(self.revision_manager.get_for_object_reference( self.model, object_id, ).select_related("revision__user")) ] # Compile the context. context = {"action_list": action_list} context.update(extra_context or {}) return super(VersionAdmin, self).history_view(request, object_id, context) class VersionMetaAdmin(VersionAdmin): """ An enhanced VersionAdmin that annotates the given object with information about the last version that was saved. """ def queryset(self, request): """Returns the annotated queryset.""" content_type = ContentType.objects.get_for_model(self.model) pk = self.model._meta.pk if has_int_pk(self.model): version_table_field = "object_id_int" else: version_table_field = "object_id" return super(VersionMetaAdmin, self).queryset(request).extra( select = { "date_modified": """ SELECT MAX(%(revision_table)s.date_created) FROM %(version_table)s JOIN %(revision_table)s ON %(revision_table)s.id = %(version_table)s.revision_id WHERE %(version_table)s.content_type_id = %%s AND %(version_table)s.%(version_table_field)s = %(table)s.%(pk)s """ % { "revision_table": connection.ops.quote_name(Revision._meta.db_table), "version_table": connection.ops.quote_name(Version._meta.db_table), "table": connection.ops.quote_name(self.model._meta.db_table), "pk": connection.ops.quote_name(pk.db_column or pk.attname), "version_table_field": connection.ops.quote_name(version_table_field), } }, select_params = (content_type.id,), ) def get_date_modified(self, obj): """Displays the last modified date of the given object, typically for use in a change list.""" return format(obj.date_modified, _('DATETIME_FORMAT')) get_date_modified.short_description = "date modified"
{ "repo_name": "vipins/ccccms", "path": "env/Lib/site-packages/reversion/admin.py", "copies": "1", "size": "24664", "license": "bsd-3-clause", "hash": -6604788029634679000, "line_mean": 52.8515283843, "line_max": 198, "alpha_frac": 0.6026192021, "autogenerated": false, "ratio": 4.2730422730422735, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5375661475142274, "avg_score": null, "num_lines": null }
"""Admin extensions for django-reversion.""" from functools import partial from django import template from django.db import models, transaction, connection from django.conf.urls import patterns, url from django.contrib import admin from django.contrib.admin import helpers, options from django.contrib.admin.util import unquote, quote from django.contrib.contenttypes.generic import GenericInlineModelAdmin, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.forms.formsets import all_valid from django.forms.models import model_to_dict from django.http import HttpResponseRedirect from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404, render_to_response from django.utils.html import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext as _ from django.utils.encoding import force_unicode from django.utils.formats import localize from reversion.models import Revision, Version, has_int_pk, VERSION_ADD, VERSION_CHANGE, VERSION_DELETE from reversion.revisions import default_revision_manager, RegistrationError class VersionAdmin(admin.ModelAdmin): """Abstract admin class for handling version controlled models.""" object_history_template = "reversion/object_history.html" change_list_template = "reversion/change_list.html" revision_form_template = None recover_list_template = None recover_form_template = None # The revision manager instance used to manage revisions. revision_manager = default_revision_manager # The serialization format to use when registering models with reversion. reversion_format = "json" # Whether to ignore duplicate revision data. ignore_duplicate_revisions = False # If True, then the default ordering of object_history and recover lists will be reversed. history_latest_first = False def _autoregister(self, model, follow=None): """Registers a model with reversion, if required.""" if model._meta.proxy: raise RegistrationError("Proxy models cannot be used with django-reversion, register the parent class instead") if not self.revision_manager.is_registered(model): follow = follow or [] for parent_cls, field in model._meta.parents.items(): follow.append(field.name) self._autoregister(parent_cls) self.revision_manager.register(model, follow=follow, format=self.reversion_format) @property def revision_context_manager(self): """The revision context manager for this VersionAdmin.""" return self.revision_manager._revision_context_manager def __init__(self, *args, **kwargs): """Initializes the VersionAdmin""" super(VersionAdmin, self).__init__(*args, **kwargs) # Automatically register models if required. if not self.revision_manager.is_registered(self.model): inline_fields = [] for inline in self.inlines: inline_model = inline.model if issubclass(inline, GenericInlineModelAdmin): ct_field = inline.ct_field ct_fk_field = inline.ct_fk_field for field in self.model._meta.many_to_many: if isinstance(field, GenericRelation) and field.rel.to == inline_model and field.object_id_field_name == ct_fk_field and field.content_type_field_name == ct_field: inline_fields.append(field.name) self._autoregister(inline_model) elif issubclass(inline, options.InlineModelAdmin): fk_name = inline.fk_name if not fk_name: for field in inline_model._meta.fields: if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(self.model, field.rel.to): fk_name = field.name self._autoregister(inline_model, follow=[fk_name]) if not inline_model._meta.get_field(fk_name).rel.is_hidden(): accessor = inline_model._meta.get_field(fk_name).related.get_accessor_name() inline_fields.append(accessor) self._autoregister(self.model, inline_fields) # Wrap own methods in manual revision management. self.add_view = self.revision_context_manager.create_revision(manage_manually=True)(self.add_view) self.change_view = self.revision_context_manager.create_revision(manage_manually=True)(self.change_view) self.delete_view = self.revision_context_manager.create_revision(manage_manually=True)(self.delete_view) self.recover_view = self.revision_context_manager.create_revision(manage_manually=True)(self.recover_view) self.revision_view = self.revision_context_manager.create_revision(manage_manually=True)(self.revision_view) self.changelist_view = self.revision_context_manager.create_revision(manage_manually=True)(self.changelist_view) def _get_template_list(self, template_name): opts = self.model._meta return ( "reversion/%s/%s/%s" % (opts.app_label, opts.object_name.lower(), template_name), "reversion/%s/%s" % (opts.app_label, template_name), "reversion/%s" % template_name, ) def get_urls(self): """Returns the additional urls used by the Reversion admin.""" urls = super(VersionAdmin, self).get_urls() admin_site = self.admin_site opts = self.model._meta info = opts.app_label, opts.module_name, reversion_urls = patterns("", url("^recover/$", admin_site.admin_view(self.recoverlist_view), name='%s_%s_recoverlist' % info), url("^recover/([^/]+)/$", admin_site.admin_view(self.recover_view), name='%s_%s_recover' % info), url("^([^/]+)/history/([^/]+)/$", admin_site.admin_view(self.revision_view), name='%s_%s_revision' % info),) return reversion_urls + urls def get_revision_instances(self, request, object): """Returns all the instances to be used in the object's revision.""" return [object] def get_revision_data(self, request, object, flag): """Returns all the revision data to be used in the object's revision.""" return dict( (o, self.revision_manager.get_adapter(o.__class__).get_version_data(o, flag)) for o in self.get_revision_instances(request, object) ) def log_addition(self, request, object): """Sets the version meta information.""" super(VersionAdmin, self).log_addition(request, object) self.revision_manager.save_revision( self.get_revision_data(request, object, VERSION_ADD), user = request.user, comment = _(u"Initial version."), ignore_duplicates = self.ignore_duplicate_revisions, db = self.revision_context_manager.get_db(), ) def log_change(self, request, object, message): """Sets the version meta information.""" super(VersionAdmin, self).log_change(request, object, message) self.revision_manager.save_revision( self.get_revision_data(request, object, VERSION_CHANGE), user = request.user, comment = message, ignore_duplicates = self.ignore_duplicate_revisions, db = self.revision_context_manager.get_db(), ) def log_deletion(self, request, object, object_repr): """Sets the version meta information.""" super(VersionAdmin, self).log_deletion(request, object, object_repr) self.revision_manager.save_revision( self.get_revision_data(request, object, VERSION_DELETE), user = request.user, comment = _(u"Deleted %(verbose_name)s.") % {"verbose_name": self.model._meta.verbose_name}, ignore_duplicates = self.ignore_duplicate_revisions, db = self.revision_context_manager.get_db(), ) def _order_version_queryset(self, queryset): """Applies the correct ordering to the given version queryset.""" if self.history_latest_first: return queryset.order_by("-pk") return queryset.order_by("pk") def recoverlist_view(self, request, extra_context=None): """Displays a deleted model to allow recovery.""" # check if user has change or add permissions for model if not self.has_change_permission(request) and not self.has_add_permission(request): raise PermissionDenied model = self.model opts = model._meta deleted = self._order_version_queryset(self.revision_manager.get_deleted(self.model)) context = { "opts": opts, "app_label": opts.app_label, "module_name": capfirst(opts.verbose_name), "title": _("Recover deleted %(name)s") % {"name": force_unicode(opts.verbose_name_plural)}, "deleted": deleted, "changelist_url": reverse("%s:%s_%s_changelist" % (self.admin_site.name, opts.app_label, opts.module_name)), } extra_context = extra_context or {} context.update(extra_context) return render_to_response(self.recover_list_template or self._get_template_list("recover_list.html"), context, template.RequestContext(request)) def get_revision_form_data(self, request, obj, version): """ Returns a dictionary of data to set in the admin form in order to revert to the given revision. """ return version.field_dict def get_related_versions(self, obj, version, FormSet): """Retreives all the related Version objects for the given FormSet.""" object_id = obj.pk # Get the fk name. try: fk_name = FormSet.fk.name except AttributeError: # This is a GenericInlineFormset, or similar. fk_name = FormSet.ct_fk_field.name # Look up the revision data. revision_versions = version.revision.version_set.all() related_versions = dict([(related_version.object_id, related_version) for related_version in revision_versions if ContentType.objects.get_for_id(related_version.content_type_id).model_class() == FormSet.model and unicode(related_version.field_dict[fk_name]) == unicode(object_id)]) return related_versions def _hack_inline_formset_initial(self, FormSet, formset, obj, version, revert, recover): """Hacks the given formset to contain the correct initial data.""" # Now we hack it to push in the data from the revision! initial = [] related_versions = self.get_related_versions(obj, version, FormSet) formset.related_versions = related_versions for related_obj in formset.queryset: if unicode(related_obj.pk) in related_versions: initial.append(related_versions.pop(unicode(related_obj.pk)).field_dict) else: initial_data = model_to_dict(related_obj) initial_data["DELETE"] = True initial.append(initial_data) for related_version in related_versions.values(): initial_row = related_version.field_dict pk_name = ContentType.objects.get_for_id(related_version.content_type_id).model_class()._meta.pk.name del initial_row[pk_name] initial.append(initial_row) # Reconstruct the forms with the new revision data. formset.initial = initial formset.forms = [formset._construct_form(n) for n in xrange(len(initial))] # Hack the formset to force a save of everything. def get_changed_data(form): return [field.name for field in form.fields] for form in formset.forms: form.has_changed = lambda: True form._get_changed_data = partial(get_changed_data, form=form) def total_form_count_hack(count): return lambda: count formset.total_form_count = total_form_count_hack(len(initial)) def render_revision_form(self, request, obj, version, context, revert=False, recover=False): """Renders the object revision form.""" model = self.model opts = model._meta object_id = obj.pk # Generate the model form. ModelForm = self.get_form(request, obj) formsets = [] if request.method == "POST": # This section is copied directly from the model admin change view # method. Maybe one day there will be a hook for doing this better. form = ModelForm(request.POST, request.FILES, instance=obj, initial=self.get_revision_form_data(request, obj, version)) if form.is_valid(): form_validated = True new_object = self.save_form(request, form, change=True) # HACK: If the value of a file field is None, remove the file from the model. for field in new_object._meta.fields: if isinstance(field, models.FileField) and field.name in form.cleaned_data and form.cleaned_data[field.name] is None: setattr(new_object, field.name, None) else: form_validated = False new_object = obj prefixes = {} for FormSet, inline in zip(self.get_formsets(request, new_object), self.get_inline_instances(request)): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(request.POST, request.FILES, instance=new_object, prefix=prefix, queryset=inline.queryset(request)) self._hack_inline_formset_initial(FormSet, formset, obj, version, revert, recover) # Add this hacked formset to the form. formsets.append(formset) if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, change=True) form.save_m2m() for formset in formsets: # HACK: If the value of a file field is None, remove the file from the model. related_objects = formset.save(commit=False) for related_obj, related_form in zip(related_objects, formset.saved_forms): for field in related_obj._meta.fields: if isinstance(field, models.FileField) and field.name in related_form.cleaned_data and related_form.cleaned_data[field.name] is None: setattr(related_obj, field.name, None) related_obj.save() formset.save_m2m() change_message = _(u"Reverted to previous version, saved on %(datetime)s") % {"datetime": localize(version.revision.date_created)} self.log_change(request, new_object, change_message) self.message_user(request, _(u'The %(model)s "%(name)s" was reverted successfully. You may edit it again below.') % {"model": force_unicode(opts.verbose_name), "name": unicode(obj)}) # Redirect to the model change form. if revert: return HttpResponseRedirect("../../") elif recover: return HttpResponseRedirect("../../%s/" % quote(object_id)) else: assert False else: # This is a mutated version of the code in the standard model admin # change_view. Once again, a hook for this kind of functionality # would be nice. Unfortunately, it results in doubling the number # of queries required to construct the formets. form = ModelForm(instance=obj, initial=self.get_revision_form_data(request, obj, version)) prefixes = {} for FormSet, inline in zip(self.get_formsets(request, obj), self.get_inline_instances(request)): # This code is standard for creating the formset. prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(instance=obj, prefix=prefix, queryset=inline.queryset(request)) self._hack_inline_formset_initial(FormSet, formset, obj, version, revert, recover) # Add this hacked formset to the form. formsets.append(formset) # Generate admin form helper. adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields, self.get_readonly_fields(request, obj), model_admin=self) media = self.media + adminForm.media # Generate formset helpers. inline_admin_formsets = [] for inline, formset in zip(self.get_inline_instances(request), formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(inline.get_readonly_fields(request, obj)) prepopulated = inline.get_prepopulated_fields(request, obj) inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets, prepopulated, readonly, model_admin=self) inline_admin_formsets.append(inline_admin_formset) media = media + inline_admin_formset.media # Generate the context. context.update({"adminform": adminForm, "object_id": object_id, "original": obj, "is_popup": False, "media": mark_safe(media), "inline_admin_formsets": inline_admin_formsets, "errors": helpers.AdminErrorList(form, formsets), "app_label": opts.app_label, "add": False, "change": True, "revert": revert, "recover": recover, "has_add_permission": self.has_add_permission(request), "has_change_permission": self.has_change_permission(request, obj), "has_delete_permission": self.has_delete_permission(request, obj), "has_file_field": True, "has_absolute_url": False, "ordered_objects": opts.get_ordered_objects(), "form_url": mark_safe(request.path), "opts": opts, "content_type_id": ContentType.objects.get_for_model(self.model).id, "save_as": False, "save_on_top": self.save_on_top, "changelist_url": reverse("%s:%s_%s_changelist" % (self.admin_site.name, opts.app_label, opts.module_name)), "change_url": reverse("%s:%s_%s_change" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(obj.pk),)), "history_url": reverse("%s:%s_%s_history" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(obj.pk),)), "recoverlist_url": reverse("%s:%s_%s_recoverlist" % (self.admin_site.name, opts.app_label, opts.module_name))}) # Render the form. if revert: form_template = self.revision_form_template or self._get_template_list("revision_form.html") elif recover: form_template = self.recover_form_template or self._get_template_list("recover_form.html") else: assert False return render_to_response(form_template, context, template.RequestContext(request)) @transaction.commit_on_success def recover_view(self, request, version_id, extra_context=None): """Displays a form that can recover a deleted model.""" # check if user has change or add permissions for model if not self.has_change_permission(request) and not self.has_add_permission(request): raise PermissionDenied version = get_object_or_404(Version, pk=version_id) obj = version.object_version.object context = {"title": _("Recover %(name)s") % {"name": version.object_repr},} context.update(extra_context or {}) return self.render_revision_form(request, obj, version, context, recover=True) @transaction.commit_on_success def revision_view(self, request, object_id, version_id, extra_context=None): """Displays the contents of the given revision.""" # check if user has change or add permissions for model if not self.has_change_permission(request): raise PermissionDenied object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F" obj = get_object_or_404(self.model, pk=object_id) version = get_object_or_404(Version, pk=version_id, object_id=unicode(obj.pk)) # Generate the context. context = {"title": _("Revert %(name)s") % {"name": force_unicode(self.model._meta.verbose_name)},} context.update(extra_context or {}) return self.render_revision_form(request, obj, version, context, revert=True) def changelist_view(self, request, extra_context=None): """Renders the change view.""" opts = self.model._meta context = {"recoverlist_url": reverse("%s:%s_%s_recoverlist" % (self.admin_site.name, opts.app_label, opts.module_name)), "add_url": reverse("%s:%s_%s_add" % (self.admin_site.name, opts.app_label, opts.module_name)),} context.update(extra_context or {}) return super(VersionAdmin, self).changelist_view(request, context) def history_view(self, request, object_id, extra_context=None): """Renders the history view.""" # check if user has change or add permissions for model if not self.has_change_permission(request): raise PermissionDenied object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F" opts = self.model._meta action_list = [ { "revision": version.revision, "url": reverse("%s:%s_%s_revision" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(version.object_id), version.id)), } for version in self._order_version_queryset(self.revision_manager.get_for_object_reference( self.model, object_id, ).select_related("revision__user")) ] # Compile the context. context = {"action_list": action_list} context.update(extra_context or {}) return super(VersionAdmin, self).history_view(request, object_id, context) class VersionMetaAdmin(VersionAdmin): """ An enhanced VersionAdmin that annotates the given object with information about the last version that was saved. """ def queryset(self, request): """Returns the annotated queryset.""" content_type = ContentType.objects.get_for_model(self.model) pk = self.model._meta.pk if has_int_pk(self.model): version_table_field = "object_id_int" else: version_table_field = "object_id" return super(VersionMetaAdmin, self).queryset(request).extra( select = { "date_modified": """ SELECT MAX(%(revision_table)s.date_created) FROM %(version_table)s JOIN %(revision_table)s ON %(revision_table)s.id = %(version_table)s.revision_id WHERE %(version_table)s.content_type_id = %%s AND %(version_table)s.%(version_table_field)s = %(table)s.%(pk)s """ % { "revision_table": connection.ops.quote_name(Revision._meta.db_table), "version_table": connection.ops.quote_name(Version._meta.db_table), "table": connection.ops.quote_name(self.model._meta.db_table), "pk": connection.ops.quote_name(pk.db_column or pk.attname), "version_table_field": connection.ops.quote_name(version_table_field), } }, select_params = (content_type.id,), ) def get_date_modified(self, obj): """Displays the last modified date of the given object, typically for use in a change list.""" return localize(obj.date_modified) get_date_modified.short_description = "date modified"
{ "repo_name": "cbrepo/django-reversion", "path": "src/reversion/admin.py", "copies": "1", "size": "25371", "license": "bsd-3-clause", "hash": 4993114446315546000, "line_mean": 52.8662420382, "line_max": 198, "alpha_frac": 0.6042725947, "autogenerated": false, "ratio": 4.289989854582347, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.014836549432487765, "num_lines": 471 }
"""Admin extensions for django-reversion.""" from django import template from django.db import models, transaction from django.conf.urls.defaults import patterns, url from django.contrib import admin from django.contrib.admin import helpers, options from django.contrib.admin.util import unquote from django.contrib.contenttypes.generic import GenericInlineModelAdmin, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.forms.formsets import all_valid from django.forms.models import model_to_dict from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render_to_response from django.utils.dateformat import format from django.utils.html import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext as _ from django.utils.encoding import force_unicode from reversion.models import Version from reversion.revisions import revision_context_manager, default_revision_manager class VersionAdmin(admin.ModelAdmin): """Abstract admin class for handling version controlled models.""" object_history_template = "reversion/object_history.html" change_list_template = "reversion/change_list.html" revision_form_template = None recover_list_template = None recover_form_template = None # The revision manager instance used to manage revisions. revision_manager = default_revision_manager # The serialization format to use when registering models with reversion. reversion_format = "json" # Whether to ignore duplicate revision data. ignore_duplicate_revisions = False # If True, then the default ordering of object_history and recover lists will be reversed. history_latest_first = False def _autoregister(self, model, follow=None): """Registers a model with reversion, if required.""" if not self.revision_manager.is_registered(model): follow = follow or [] for parent_cls, field in model._meta.parents.items(): follow.append(field.name) self._autoregister(parent_cls) self.revision_manager.register(model, follow=follow, format=self.reversion_format) def __init__(self, *args, **kwargs): """Initializes the VersionAdmin""" super(VersionAdmin, self).__init__(*args, **kwargs) # Automatically register models if required. if not self.revision_manager.is_registered(self.model): inline_fields = [] for inline in self.inlines: inline_model = inline.model self._autoregister(inline_model) if issubclass(inline, GenericInlineModelAdmin): ct_field = inline.ct_field ct_fk_field = inline.ct_fk_field for field in self.model._meta.many_to_many: if isinstance(field, GenericRelation) and field.rel.to == inline_model and field.object_id_field_name == ct_fk_field and field.content_type_field_name == ct_field: inline_fields.append(field.name) elif issubclass(inline, options.InlineModelAdmin): fk_name = inline.fk_name if not fk_name: for field in inline_model._meta.fields: if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(self.model, field.rel.to): fk_name = field.name if not inline_model._meta.get_field(fk_name).rel.is_hidden(): accessor = inline_model._meta.get_field(fk_name).related.get_accessor_name() inline_fields.append(accessor) self._autoregister(self.model, inline_fields) def _get_template_list(self, template_name): opts = self.model._meta return ( "reversion/%s/%s/%s" % (opts.app_label, opts.object_name.lower(), template_name), "reversion/%s/%s" % (opts.app_label, template_name), "reversion/%s" % template_name, ) def get_urls(self): """Returns the additional urls used by the Reversion admin.""" urls = super(VersionAdmin, self).get_urls() admin_site = self.admin_site opts = self.model._meta info = opts.app_label, opts.module_name, reversion_urls = patterns("", url("^recover/$", admin_site.admin_view(self.recoverlist_view), name='%s_%s_recoverlist' % info), url("^recover/([^/]+)/$", admin_site.admin_view(self.recover_view), name='%s_%s_recover' % info), url("^([^/]+)/history/([^/]+)/$", admin_site.admin_view(self.revision_view), name='%s_%s_revision' % info),) return reversion_urls + urls def log_addition(self, request, object): """Sets the version meta information.""" super(VersionAdmin, self).log_addition(request, object) revision_context_manager.set_user(request.user) revision_context_manager.set_comment(_(u"Initial version.")) revision_context_manager.set_ignore_duplicates(self.ignore_duplicate_revisions) def log_change(self, request, object, message): """Sets the version meta information.""" super(VersionAdmin, self).log_change(request, object, message) revision_context_manager.set_user(request.user) revision_context_manager.set_comment(message) revision_context_manager.set_ignore_duplicates(self.ignore_duplicate_revisions) def log_deletion(self, request, object, object_repr): """Sets the version meta information.""" super(VersionAdmin, self).log_deletion(request, object, object_repr) revision_context_manager.set_user(request.user) revision_context_manager.set_comment(_(u"Deleted %(verbose_name)s.") % {"verbose_name": self.model._meta.verbose_name}) revision_context_manager.set_ignore_duplicates(self.ignore_duplicate_revisions) def _order_version_queryset(self, queryset): """Applies the correct ordering to the given version queryset.""" if self.history_latest_first: return queryset.order_by("-pk") return queryset.order_by("pk") def recoverlist_view(self, request, extra_context=None): """Displays a deleted model to allow recovery.""" model = self.model opts = model._meta deleted = self._order_version_queryset(self.revision_manager.get_deleted(self.model)) context = { "opts": opts, "app_label": opts.app_label, "module_name": capfirst(opts.verbose_name), "title": _("Recover deleted %(name)s") % {"name": force_unicode(opts.verbose_name_plural)}, "deleted": deleted, "changelist_url": reverse("%s:%s_%s_changelist" % (self.admin_site.name, opts.app_label, opts.module_name)), } extra_context = extra_context or {} context.update(extra_context) return render_to_response(self.recover_list_template or self._get_template_list("recover_list.html"), context, template.RequestContext(request)) def get_revision_form_data(self, request, obj, version): """ Returns a dictionary of data to set in the admin form in order to revert to the given revision. """ return version.field_dict def get_related_versions(self, obj, version, FormSet): """Retreives all the related Version objects for the given FormSet.""" object_id = obj.pk # Get the fk name. try: fk_name = FormSet.fk.name except AttributeError: # This is a GenericInlineFormset, or similar. fk_name = FormSet.ct_fk_field.name # Look up the revision data. revision_versions = version.revision.version_set.all() related_versions = dict([(related_version.object_id, related_version) for related_version in revision_versions if ContentType.objects.get_for_id(related_version.content_type_id).model_class() == FormSet.model and unicode(related_version.field_dict[fk_name]) == unicode(object_id)]) return related_versions def _hack_inline_formset_initial(self, FormSet, formset, obj, version, revert, recover): """Hacks the given formset to contain the correct initial data.""" # Now we hack it to push in the data from the revision! initial = [] related_versions = self.get_related_versions(obj, version, FormSet) formset.related_versions = related_versions for related_obj in formset.queryset: if unicode(related_obj.pk) in related_versions: initial.append(related_versions.pop(unicode(related_obj.pk)).field_dict) else: initial_data = model_to_dict(related_obj) initial_data["DELETE"] = True initial.append(initial_data) for related_version in related_versions.values(): initial_row = related_version.field_dict pk_name = ContentType.objects.get_for_id(related_version.content_type_id).model_class()._meta.pk.name del initial_row[pk_name] initial.append(initial_row) # Reconstruct the forms with the new revision data. formset.initial = initial formset.forms = [formset._construct_form(n) for n in xrange(len(initial))] # Hack the formset to force a save of everything. for form in formset.forms: form.has_changed = lambda: True form._get_changed_data = lambda: [field.name for field in form.fields] # TODO: Scope this in a partial function. def total_form_count_hack(count): return lambda: count formset.total_form_count = total_form_count_hack(len(initial)) def render_revision_form(self, request, obj, version, context, revert=False, recover=False): """Renders the object revision form.""" model = self.model opts = model._meta object_id = obj.pk # Generate the model form. ModelForm = self.get_form(request, obj) formsets = [] if request.method == "POST": # This section is copied directly from the model admin change view # method. Maybe one day there will be a hook for doing this better. form = ModelForm(request.POST, request.FILES, instance=obj, initial=self.get_revision_form_data(request, obj, version)) if form.is_valid(): form_validated = True new_object = self.save_form(request, form, change=True) # HACK: If the value of a file field is None, remove the file from the model. for field in new_object._meta.fields: if isinstance(field, models.FileField) and field.name in form.cleaned_data and form.cleaned_data[field.name] is None: setattr(new_object, field.name, None) else: form_validated = False new_object = obj prefixes = {} for FormSet, inline in zip(self.get_formsets(request, new_object), self.inline_instances): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(request.POST, request.FILES, instance=new_object, prefix=prefix, queryset=inline.queryset(request)) self._hack_inline_formset_initial(FormSet, formset, obj, version, revert, recover) # Add this hacked formset to the form. formsets.append(formset) if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, change=True) form.save_m2m() for formset in formsets: # HACK: If the value of a file field is None, remove the file from the model. related_objects = formset.save(commit=False) for related_obj, related_form in zip(related_objects, formset.saved_forms): for field in related_obj._meta.fields: if isinstance(field, models.FileField) and field.name in related_form.cleaned_data and related_form.cleaned_data[field.name] is None: setattr(related_obj, field.name, None) related_obj.save() formset.save_m2m() change_message = _(u"Reverted to previous version, saved on %(datetime)s") % {"datetime": format(version.revision.date_created, _('DATETIME_FORMAT'))} self.log_change(request, new_object, change_message) self.message_user(request, _(u'The %(model)s "%(name)s" was reverted successfully. You may edit it again below.') % {"model": force_unicode(opts.verbose_name), "name": unicode(obj)}) # Redirect to the model change form. if revert: return HttpResponseRedirect("../../") elif recover: return HttpResponseRedirect("../../%s/" % object_id) else: assert False else: # This is a mutated version of the code in the standard model admin # change_view. Once again, a hook for this kind of functionality # would be nice. Unfortunately, it results in doubling the number # of queries required to construct the formets. form = ModelForm(instance=obj, initial=self.get_revision_form_data(request, obj, version)) prefixes = {} for FormSet, inline in zip(self.get_formsets(request, obj), self.inline_instances): # This code is standard for creating the formset. prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(instance=obj, prefix=prefix, queryset=inline.queryset(request)) self._hack_inline_formset_initial(FormSet, formset, obj, version, revert, recover) # Add this hacked formset to the form. formsets.append(formset) # Generate admin form helper. adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields, self.get_readonly_fields(request, obj), model_admin=self) media = self.media + adminForm.media # Generate formset helpers. inline_admin_formsets = [] for inline, formset in zip(self.inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(inline.get_readonly_fields(request, obj)) inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets, readonly, model_admin=self) inline_admin_formsets.append(inline_admin_formset) media = media + inline_admin_formset.media # Generate the context. context.update({"adminform": adminForm, "object_id": object_id, "original": obj, "is_popup": False, "media": mark_safe(media), "inline_admin_formsets": inline_admin_formsets, "errors": helpers.AdminErrorList(form, formsets), "app_label": opts.app_label, "add": False, "change": True, "revert": revert, "recover": recover, "has_add_permission": self.has_add_permission(request), "has_change_permission": self.has_change_permission(request, obj), "has_delete_permission": self.has_delete_permission(request, obj), "has_file_field": True, "has_absolute_url": False, "ordered_objects": opts.get_ordered_objects(), "form_url": mark_safe(request.path), "opts": opts, "content_type_id": ContentType.objects.get_for_model(self.model).id, "save_as": False, "save_on_top": self.save_on_top, "changelist_url": reverse("%s:%s_%s_changelist" % (self.admin_site.name, opts.app_label, opts.module_name)), "change_url": reverse("%s:%s_%s_change" % (self.admin_site.name, opts.app_label, opts.module_name), args=(obj.pk,)), "history_url": reverse("%s:%s_%s_history" % (self.admin_site.name, opts.app_label, opts.module_name), args=(obj.pk,)), "recoverlist_url": reverse("%s:%s_%s_recoverlist" % (self.admin_site.name, opts.app_label, opts.module_name))}) # Render the form. if revert: form_template = self.revision_form_template or self._get_template_list("revision_form.html") elif recover: form_template = self.recover_form_template or self._get_template_list("recover_form.html") else: assert False return render_to_response(form_template, context, template.RequestContext(request)) @transaction.commit_on_success @revision_context_manager.create_revision() def recover_view(self, request, version_id, extra_context=None): """Displays a form that can recover a deleted model.""" version = get_object_or_404(Version, pk=version_id) obj = version.object_version.object context = {"title": _("Recover %(name)s") % {"name": version.object_repr},} context.update(extra_context or {}) return self.render_revision_form(request, obj, version, context, recover=True) @transaction.commit_on_success @revision_context_manager.create_revision() def revision_view(self, request, object_id, version_id, extra_context=None): """Displays the contents of the given revision.""" object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F" obj = get_object_or_404(self.model, pk=object_id) version = get_object_or_404(Version, pk=version_id, object_id=unicode(obj.pk)) # Generate the context. context = {"title": _("Revert %(name)s") % {"name": force_unicode(self.model._meta.verbose_name)},} context.update(extra_context or {}) return self.render_revision_form(request, obj, version, context, revert=True) @transaction.commit_on_success @revision_context_manager.create_revision() def add_view(self, *args, **kwargs): """Adds a new model to the application.""" return super(VersionAdmin, self).add_view(*args, **kwargs) @transaction.commit_on_success @revision_context_manager.create_revision() def change_view(self, *args, **kwargs): """Modifies an existing model.""" return super(VersionAdmin, self).change_view(*args, **kwargs) @transaction.commit_on_success @revision_context_manager.create_revision() def delete_view(self, *args, **kwargs): """Deletes an existing model.""" return super(VersionAdmin, self).delete_view(*args, **kwargs) @transaction.commit_on_success @revision_context_manager.create_revision() def changelist_view(self, request, extra_context=None): """Renders the change view.""" opts = self.model._meta context = {"recoverlist_url": reverse("%s:%s_%s_recoverlist" % (self.admin_site.name, opts.app_label, opts.module_name)), "add_url": reverse("%s:%s_%s_add" % (self.admin_site.name, opts.app_label, opts.module_name)),} context.update(extra_context or {}) return super(VersionAdmin, self).changelist_view(request, context) def history_view(self, request, object_id, extra_context=None): """Renders the history view.""" object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F" opts = self.model._meta action_list = [ { "revision": version.revision, "url": reverse("%s:%s_%s_revision" % (self.admin_site.name, opts.app_label, opts.module_name), args=(version.object_id, version.id)), } for version in self._order_version_queryset(self.revision_manager.get_for_object_reference( self.model, object_id, ).select_related("revision__user")) ] # Compile the context. context = {"action_list": action_list} context.update(extra_context or {}) return super(VersionAdmin, self).history_view(request, object_id, context)
{ "repo_name": "HubSpot/django-reversion", "path": "src/reversion/admin.py", "copies": "1", "size": "21506", "license": "bsd-3-clause", "hash": -7384514509626076000, "line_mean": 52.8997493734, "line_max": 198, "alpha_frac": 0.6031340091, "autogenerated": false, "ratio": 4.277247414478918, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.014110005008783639, "num_lines": 399 }
"""Admin extensions for django-reversion.""" from __future__ import unicode_literals from contextlib import contextmanager from django.db import models, transaction, connection from django.conf.urls import patterns, url from django.contrib import admin from django.contrib.admin import options try: from django.contrib.admin.utils import unquote, quote except ImportError: # Django < 1.7 pragma: no cover from django.contrib.admin.util import unquote, quote try: from django.contrib.contenttypes.admin import GenericInlineModelAdmin from django.contrib.contenttypes.fields import GenericRelation except ImportError: # Django < 1.9 pragma: no cover from django.contrib.contenttypes.generic import GenericInlineModelAdmin, GenericRelation from django.core.urlresolvers import reverse from django.core.exceptions import PermissionDenied, ImproperlyConfigured from django.shortcuts import get_object_or_404, render from django.utils.text import capfirst from django.utils.translation import ugettext as _ from django.utils.encoding import force_text from django.utils.formats import localize from reversion.models import Version from reversion.revisions import default_revision_manager class RollBackRevisionView(Exception): pass class VersionAdmin(admin.ModelAdmin): """Abstract admin class for handling version controlled models.""" object_history_template = "reversion/object_history.html" change_list_template = "reversion/change_list.html" revision_form_template = None recover_list_template = None recover_form_template = None # The revision manager instance used to manage revisions. revision_manager = default_revision_manager # The serialization format to use when registering models with reversion. reversion_format = "json" # Whether to ignore duplicate revision data. ignore_duplicate_revisions = False # If True, then the default ordering of object_history and recover lists will be reversed. history_latest_first = False # Revision helpers. @property def revision_context_manager(self): """The revision context manager for this VersionAdmin.""" return self.revision_manager._revision_context_manager def _get_template_list(self, template_name): opts = self.model._meta return ( "reversion/%s/%s/%s" % (opts.app_label, opts.object_name.lower(), template_name), "reversion/%s/%s" % (opts.app_label, template_name), "reversion/%s" % template_name, ) def _order_version_queryset(self, queryset): """Applies the correct ordering to the given version queryset.""" if self.history_latest_first: return queryset.order_by("-pk") return queryset.order_by("pk") @contextmanager def _create_revision(self, request): with transaction.atomic(), self.revision_context_manager.create_revision(): self.revision_context_manager.set_user(request.user) yield # Messages. def log_addition(self, request, object): self.revision_context_manager.set_comment(_("Initial version.")) super(VersionAdmin, self).log_addition(request, object) def log_change(self, request, object, message): self.revision_context_manager.set_comment(message) super(VersionAdmin, self).log_change(request, object, message) # Auto-registration. def _autoregister(self, model, follow=None): """Registers a model with reversion, if required.""" if not self.revision_manager.is_registered(model): follow = follow or [] # Use model_meta.concrete_model to catch proxy models for parent_cls, field in model._meta.concrete_model._meta.parents.items(): follow.append(field.name) self._autoregister(parent_cls) self.revision_manager.register(model, follow=follow, format=self.reversion_format) def _introspect_inline_admin(self, inline): """Introspects the given inline admin, returning a tuple of (inline_model, follow_field).""" inline_model = None follow_field = None fk_name = None if issubclass(inline, GenericInlineModelAdmin): inline_model = inline.model ct_field = inline.ct_field fk_name = inline.ct_fk_field for field in self.model._meta.virtual_fields: if isinstance(field, GenericRelation) and field.rel.to == inline_model and field.object_id_field_name == fk_name and field.content_type_field_name == ct_field: follow_field = field.name break elif issubclass(inline, options.InlineModelAdmin): inline_model = inline.model fk_name = inline.fk_name if not fk_name: for field in inline_model._meta.fields: if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(self.model, field.rel.to): fk_name = field.name break if fk_name and not inline_model._meta.get_field(fk_name).rel.is_hidden(): accessor = inline_model._meta.get_field(fk_name).related.get_accessor_name() follow_field = accessor return inline_model, follow_field, fk_name def __init__(self, *args, **kwargs): """Initializes the VersionAdmin""" super(VersionAdmin, self).__init__(*args, **kwargs) # Check that database transactions are supported. if not connection.features.uses_savepoints: # pragma: no cover raise ImproperlyConfigured("Cannot use VersionAdmin with a database that does not support savepoints.") # Automatically register models if required. if not self.revision_manager.is_registered(self.model): inline_fields = [] for inline in self.inlines: inline_model, follow_field, _ = self._introspect_inline_admin(inline) if inline_model: self._autoregister(inline_model) if follow_field: inline_fields.append(follow_field) self._autoregister(self.model, inline_fields) def get_urls(self): """Returns the additional urls used by the Reversion admin.""" urls = super(VersionAdmin, self).get_urls() admin_site = self.admin_site opts = self.model._meta info = opts.app_label, opts.model_name, reversion_urls = patterns("", url("^recover/$", admin_site.admin_view(self.recoverlist_view), name='%s_%s_recoverlist' % info), url("^recover/([^/]+)/$", admin_site.admin_view(self.recover_view), name='%s_%s_recover' % info), url("^([^/]+)/history/([^/]+)/$", admin_site.admin_view(self.revision_view), name='%s_%s_revision' % info),) return reversion_urls + urls # Views. def add_view(self, request, form_url='', extra_context=None): with self._create_revision(request): return super(VersionAdmin, self).add_view(request, form_url, extra_context) def change_view(self, request, object_id, form_url='', extra_context=None): with self._create_revision(request): return super(VersionAdmin, self).change_view(request, object_id, form_url, extra_context) def revisionform_view(self, request, version, template_name, extra_context=None): try: with transaction.atomic(): # Revert the revision. version.revision.revert(delete=True) # Run the normal changeform view. with self._create_revision(request): response = self.changeform_view(request, version.object_id, request.path, extra_context) # Decide on whether the keep the changes. if request.method == "POST" and response.status_code == 302: self.revision_context_manager.set_comment(_("Reverted to previous version, saved on %(datetime)s") % {"datetime": localize(version.revision.date_created)}) else: response.template_name = template_name # Set the template name to the correct template. response.render() # Eagerly render the response, so it's using the latest version of the database. raise RollBackRevisionView # Raise an exception to undo the transaction and the revision. except RollBackRevisionView: pass return response def recover_view(self, request, version_id, extra_context=None): """Displays a form that can recover a deleted model.""" version = get_object_or_404(Version, pk=version_id) return self.revisionform_view(request, version, self.recover_form_template or self._get_template_list("recover_form.html"), { "title": _("Recover %(name)s") % {"name": version.object_repr}, }) def revision_view(self, request, object_id, version_id, extra_context=None): """Displays the contents of the given revision.""" object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F" version = get_object_or_404(Version, pk=version_id, object_id=object_id) return self.revisionform_view(request, version, self.revision_form_template or self._get_template_list("revision_form.html"), { "title": _("Revert %(name)s") % {"name": version.object_repr}, }) def changelist_view(self, request, extra_context=None): """Renders the change view.""" with self._create_revision(request): return super(VersionAdmin, self).changelist_view(request, extra_context) def recoverlist_view(self, request, extra_context=None): """Displays a deleted model to allow recovery.""" # check if user has change or add permissions for model if not self.has_change_permission(request) and not self.has_add_permission(request): # pragma: no cover raise PermissionDenied model = self.model opts = model._meta deleted = self._order_version_queryset(self.revision_manager.get_deleted(self.model)) # Get the site context. try: each_context = self.admin_site.each_context(request) except TypeError: # Django <= 1.7 pragma: no cover each_context = self.admin_site.each_context() # Get the rest of the context. context = dict( each_context, opts = opts, app_label = opts.app_label, module_name = capfirst(opts.verbose_name), title = _("Recover deleted %(name)s") % {"name": force_text(opts.verbose_name_plural)}, deleted = deleted, ) context.update(extra_context or {}) return render(request, self.recover_list_template or self._get_template_list("recover_list.html"), context) def history_view(self, request, object_id, extra_context=None): """Renders the history view.""" # Check if user has change permissions for model if not self.has_change_permission(request): # pragma: no cover raise PermissionDenied object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F" opts = self.model._meta action_list = [ { "revision": version.revision, "url": reverse("%s:%s_%s_revision" % (self.admin_site.name, opts.app_label, opts.model_name), args=(quote(version.object_id), version.id)), } for version in self._order_version_queryset(self.revision_manager.get_for_object_reference( self.model, object_id, ).select_related("revision__user")) ] # Compile the context. context = {"action_list": action_list} context.update(extra_context or {}) return super(VersionAdmin, self).history_view(request, object_id, context)
{ "repo_name": "pydanny/django-reversion", "path": "src/reversion/admin.py", "copies": "1", "size": "12165", "license": "bsd-3-clause", "hash": -8451940769084538000, "line_mean": 45.4312977099, "line_max": 179, "alpha_frac": 0.6385532265, "autogenerated": false, "ratio": 4.26991926991927, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002498698327184311, "num_lines": 262 }
"""Admin extensions for django-reversion.""" from __future__ import unicode_literals from functools import partial from django import template from django.db import models, transaction, connection from django.conf.urls import patterns, url from django.contrib import admin from django.contrib.admin import helpers, options from django.contrib.admin.util import unquote, quote from django.contrib.contenttypes.generic import GenericInlineModelAdmin, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.forms.formsets import all_valid from django.forms.models import model_to_dict from django.http import HttpResponseRedirect from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404, render_to_response from django.utils.html import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext as _ from django.utils.encoding import force_text from django.utils.formats import localize from reversion.models import Revision, Version, has_int_pk from reversion.revisions import default_revision_manager, RegistrationError class VersionAdmin(admin.ModelAdmin): """Abstract admin class for handling version controlled models.""" object_history_template = "reversion/object_history.html" change_list_template = "reversion/change_list.html" revision_form_template = None recover_list_template = None recover_form_template = None # The revision manager instance used to manage revisions. revision_manager = default_revision_manager # The serialization format to use when registering models with reversion. reversion_format = "json" # Whether to ignore duplicate revision data. ignore_duplicate_revisions = False # If True, then the default ordering of object_history and recover lists will be reversed. history_latest_first = False def _autoregister(self, model, follow=None): """Registers a model with reversion, if required.""" if not self.revision_manager.is_registered(model): follow = follow or [] # Use model_meta.concrete_model to catch proxy models for parent_cls, field in model._meta.concrete_model._meta.parents.items(): follow.append(field.name) self._autoregister(parent_cls) self.revision_manager.register(model, follow=follow, format=self.reversion_format) @property def revision_context_manager(self): """The revision context manager for this VersionAdmin.""" return self.revision_manager._revision_context_manager def _introspect_inline_admin(self, inline): """Introspects the given inline admin, returning a tuple of (inline_model, follow_field).""" inline_model = None follow_field = None if issubclass(inline, GenericInlineModelAdmin): inline_model = inline.model ct_field = inline.ct_field ct_fk_field = inline.ct_fk_field for field in self.model._meta.virtual_fields: if isinstance(field, GenericRelation) and field.rel.to == inline_model and field.object_id_field_name == ct_fk_field and field.content_type_field_name == ct_field: follow_field = field.name break elif issubclass(inline, options.InlineModelAdmin): inline_model = inline.model fk_name = inline.fk_name if not fk_name: for field in inline_model._meta.fields: if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(self.model, field.rel.to): fk_name = field.name break if fk_name and not inline_model._meta.get_field(fk_name).rel.is_hidden(): accessor = inline_model._meta.get_field(fk_name).related.get_accessor_name() follow_field = accessor return inline_model, follow_field def __init__(self, *args, **kwargs): """Initializes the VersionAdmin""" super(VersionAdmin, self).__init__(*args, **kwargs) # Automatically register models if required. if not self.revision_manager.is_registered(self.model): inline_fields = [] for inline in self.inlines: inline_model, follow_field = self._introspect_inline_admin(inline) if inline_model: self._autoregister(inline_model) if follow_field: inline_fields.append(follow_field) self._autoregister(self.model, inline_fields) # Wrap own methods in manual revision management. self.add_view = self.revision_context_manager.create_revision(manage_manually=True)(self.add_view) self.change_view = self.revision_context_manager.create_revision(manage_manually=True)(self.change_view) self.recover_view = self.revision_context_manager.create_revision(manage_manually=True)(self.recover_view) self.revision_view = self.revision_context_manager.create_revision(manage_manually=True)(self.revision_view) self.changelist_view = self.revision_context_manager.create_revision(manage_manually=True)(self.changelist_view) def _get_template_list(self, template_name): opts = self.model._meta return ( "reversion/%s/%s/%s" % (opts.app_label, opts.object_name.lower(), template_name), "reversion/%s/%s" % (opts.app_label, template_name), "reversion/%s" % template_name, ) def get_urls(self): """Returns the additional urls used by the Reversion admin.""" urls = super(VersionAdmin, self).get_urls() admin_site = self.admin_site opts = self.model._meta info = opts.app_label, opts.model_name, reversion_urls = patterns("", url("^recover/$", admin_site.admin_view(self.recoverlist_view), name='%s_%s_recoverlist' % info), url("^recover/([^/]+)/$", admin_site.admin_view(self.recover_view), name='%s_%s_recover' % info), url("^([^/]+)/history/([^/]+)/$", admin_site.admin_view(self.revision_view), name='%s_%s_revision' % info),) return reversion_urls + urls def get_revision_instances(self, request, object): """Returns all the instances to be used in the object's revision.""" return [object] def get_revision_data(self, request, object): """Returns all the revision data to be used in the object's revision.""" return dict( (o, self.revision_manager.get_adapter(o.__class__).get_version_data(o)) for o in self.get_revision_instances(request, object) ) def log_addition(self, request, object): """Sets the version meta information.""" super(VersionAdmin, self).log_addition(request, object) self.revision_manager.save_revision( self.get_revision_data(request, object), user = request.user, comment = _("Initial version."), ignore_duplicates = self.ignore_duplicate_revisions, db = self.revision_context_manager.get_db(), ) def log_change(self, request, object, message): """Sets the version meta information.""" super(VersionAdmin, self).log_change(request, object, message) self.revision_manager.save_revision( self.get_revision_data(request, object), user = request.user, comment = message, ignore_duplicates = self.ignore_duplicate_revisions, db = self.revision_context_manager.get_db(), ) def _order_version_queryset(self, queryset): """Applies the correct ordering to the given version queryset.""" if self.history_latest_first: return queryset.order_by("-pk") return queryset.order_by("pk") def recoverlist_view(self, request, extra_context=None): """Displays a deleted model to allow recovery.""" # check if user has change or add permissions for model if not self.has_change_permission(request) and not self.has_add_permission(request): raise PermissionDenied model = self.model opts = model._meta deleted = self._order_version_queryset(self.revision_manager.get_deleted(self.model)) context = { "opts": opts, "app_label": opts.app_label, "module_name": capfirst(opts.verbose_name), "title": _("Recover deleted %(name)s") % {"name": force_text(opts.verbose_name_plural)}, "deleted": deleted, "changelist_url": reverse("%s:%s_%s_changelist" % (self.admin_site.name, opts.app_label, opts.model_name)), } extra_context = extra_context or {} context.update(extra_context) return render_to_response(self.recover_list_template or self._get_template_list("recover_list.html"), context, template.RequestContext(request)) def get_revision_form_data(self, request, obj, version): """ Returns a dictionary of data to set in the admin form in order to revert to the given revision. """ return version.field_dict def get_related_versions(self, obj, version, FormSet): """Retreives all the related Version objects for the given FormSet.""" object_id = obj.pk # Get the fk name. try: fk_name = FormSet.fk.name except AttributeError: # This is a GenericInlineFormset, or similar. fk_name = FormSet.ct_fk_field.name # Look up the revision data. revision_versions = version.revision.version_set.all() related_versions = dict([(related_version.object_id, related_version) for related_version in revision_versions if ContentType.objects.get_for_id(related_version.content_type_id).model_class() == FormSet.model and force_text(related_version.field_dict[fk_name]) == force_text(object_id)]) return related_versions def _hack_inline_formset_initial(self, inline, FormSet, formset, obj, version, revert, recover): """Hacks the given formset to contain the correct initial data.""" # if the FK this inline formset represents is not being followed, don't process data for it. # see https://github.com/etianen/django-reversion/issues/222 _, follow_field = self._introspect_inline_admin(inline.__class__) if follow_field not in self.revision_manager.get_adapter(self.model).follow: return # Now we hack it to push in the data from the revision! initial = [] related_versions = self.get_related_versions(obj, version, FormSet) formset.related_versions = related_versions for related_obj in formset.queryset: if force_text(related_obj.pk) in related_versions: initial.append(related_versions.pop(force_text(related_obj.pk)).field_dict) else: initial_data = model_to_dict(related_obj) initial_data["DELETE"] = True initial.append(initial_data) for related_version in related_versions.values(): initial_row = related_version.field_dict pk_name = ContentType.objects.get_for_id(related_version.content_type_id).model_class()._meta.pk.name del initial_row[pk_name] initial.append(initial_row) # Reconstruct the forms with the new revision data. formset.initial = initial formset.forms = [formset._construct_form(n) for n in range(len(initial))] # Hack the formset to force a save of everything. def get_changed_data(form): return [field.name for field in form.fields] for form in formset.forms: form.has_changed = lambda: True form._get_changed_data = partial(get_changed_data, form=form) def total_form_count_hack(count): return lambda: count formset.total_form_count = total_form_count_hack(len(initial)) def render_revision_form(self, request, obj, version, context, revert=False, recover=False): """Renders the object revision form.""" model = self.model opts = model._meta object_id = obj.pk # Generate the model form. ModelForm = self.get_form(request, obj) formsets = [] if request.method == "POST": # This section is copied directly from the model admin change view # method. Maybe one day there will be a hook for doing this better. form = ModelForm(request.POST, request.FILES, instance=obj, initial=self.get_revision_form_data(request, obj, version)) if form.is_valid(): form_validated = True new_object = self.save_form(request, form, change=True) # HACK: If the value of a file field is None, remove the file from the model. for field in new_object._meta.fields: if isinstance(field, models.FileField) and field.name in form.cleaned_data and form.cleaned_data[field.name] is None: setattr(new_object, field.name, None) else: form_validated = False new_object = obj prefixes = {} for FormSet, inline in zip(self.get_formsets(request, new_object), self.get_inline_instances(request)): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(request.POST, request.FILES, instance=new_object, prefix=prefix, queryset=inline.queryset(request)) self._hack_inline_formset_initial(inline, FormSet, formset, obj, version, revert, recover) # Add this hacked formset to the form. formsets.append(formset) if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, change=True) form.save_m2m() for formset in formsets: # HACK: If the value of a file field is None, remove the file from the model. related_objects = formset.save(commit=False) for related_obj, related_form in zip(related_objects, formset.saved_forms): for field in related_obj._meta.fields: if isinstance(field, models.FileField) and field.name in related_form.cleaned_data and related_form.cleaned_data[field.name] is None: setattr(related_obj, field.name, None) related_obj.save() formset.save_m2m() change_message = _("Reverted to previous version, saved on %(datetime)s") % {"datetime": localize(version.revision.date_created)} self.log_change(request, new_object, change_message) self.message_user(request, _('The %(model)s "%(name)s" was reverted successfully. You may edit it again below.') % {"model": force_text(opts.verbose_name), "name": force_text(obj)}) # Redirect to the model change form. if revert: return HttpResponseRedirect("../../") elif recover: return HttpResponseRedirect("../../%s/" % quote(object_id)) else: assert False else: # This is a mutated version of the code in the standard model admin # change_view. Once again, a hook for this kind of functionality # would be nice. Unfortunately, it results in doubling the number # of queries required to construct the formets. form = ModelForm(instance=obj, initial=self.get_revision_form_data(request, obj, version)) prefixes = {} for FormSet, inline in zip(self.get_formsets(request, obj), self.get_inline_instances(request)): # This code is standard for creating the formset. prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(instance=obj, prefix=prefix, queryset=inline.queryset(request)) self._hack_inline_formset_initial(inline, FormSet, formset, obj, version, revert, recover) # Add this hacked formset to the form. formsets.append(formset) # Generate admin form helper. adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields, self.get_readonly_fields(request, obj), model_admin=self) media = self.media + adminForm.media # Generate formset helpers. inline_admin_formsets = [] for inline, formset in zip(self.get_inline_instances(request), formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(inline.get_readonly_fields(request, obj)) prepopulated = inline.get_prepopulated_fields(request, obj) inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets, prepopulated, readonly, model_admin=self) inline_admin_formsets.append(inline_admin_formset) media = media + inline_admin_formset.media # Generate the context. context.update({"adminform": adminForm, "object_id": object_id, "original": obj, "is_popup": False, "media": mark_safe(media), "inline_admin_formsets": inline_admin_formsets, "errors": helpers.AdminErrorList(form, formsets), "app_label": opts.app_label, "add": False, "change": True, "revert": revert, "recover": recover, "has_add_permission": self.has_add_permission(request), "has_change_permission": self.has_change_permission(request, obj), "has_delete_permission": self.has_delete_permission(request, obj), "has_file_field": True, "has_absolute_url": False, "form_url": mark_safe(request.path), "opts": opts, "content_type_id": ContentType.objects.get_for_model(self.model).id, "save_as": False, "save_on_top": self.save_on_top, "changelist_url": reverse("%s:%s_%s_changelist" % (self.admin_site.name, opts.app_label, opts.model_name)), "change_url": reverse("%s:%s_%s_change" % (self.admin_site.name, opts.app_label, opts.model_name), args=(quote(obj.pk),)), "history_url": reverse("%s:%s_%s_history" % (self.admin_site.name, opts.app_label, opts.model_name), args=(quote(obj.pk),)), "recoverlist_url": reverse("%s:%s_%s_recoverlist" % (self.admin_site.name, opts.app_label, opts.model_name))}) # Render the form. if revert: form_template = self.revision_form_template or self._get_template_list("revision_form.html") elif recover: form_template = self.recover_form_template or self._get_template_list("recover_form.html") else: assert False return render_to_response(form_template, context, template.RequestContext(request)) @transaction.atomic def recover_view(self, request, version_id, extra_context=None): """Displays a form that can recover a deleted model.""" # check if user has change or add permissions for model if not self.has_change_permission(request) and not self.has_add_permission(request): raise PermissionDenied version = get_object_or_404(Version, pk=version_id) obj = version.object_version.object context = {"title": _("Recover %(name)s") % {"name": version.object_repr},} context.update(extra_context or {}) return self.render_revision_form(request, obj, version, context, recover=True) @transaction.atomic def revision_view(self, request, object_id, version_id, extra_context=None): """Displays the contents of the given revision.""" # check if user has change or add permissions for model if not self.has_change_permission(request): raise PermissionDenied object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F" obj = get_object_or_404(self.model, pk=object_id) version = get_object_or_404(Version, pk=version_id, object_id=force_text(obj.pk)) # Generate the context. context = {"title": _("Revert %(name)s") % {"name": force_text(self.model._meta.verbose_name)},} context.update(extra_context or {}) return self.render_revision_form(request, obj, version, context, revert=True) def changelist_view(self, request, extra_context=None): """Renders the change view.""" opts = self.model._meta context = {"recoverlist_url": reverse("%s:%s_%s_recoverlist" % (self.admin_site.name, opts.app_label, opts.model_name)), "add_url": reverse("%s:%s_%s_add" % (self.admin_site.name, opts.app_label, opts.model_name)),} context.update(extra_context or {}) return super(VersionAdmin, self).changelist_view(request, context) def history_view(self, request, object_id, extra_context=None): """Renders the history view.""" # check if user has change or add permissions for model if not self.has_change_permission(request): raise PermissionDenied object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F" opts = self.model._meta action_list = [ { "revision": version.revision, "url": reverse("%s:%s_%s_revision" % (self.admin_site.name, opts.app_label, opts.model_name), args=(quote(version.object_id), version.id)), } for version in self._order_version_queryset(self.revision_manager.get_for_object_reference( self.model, object_id, ).select_related("revision__user")) ] # Compile the context. context = {"action_list": action_list} context.update(extra_context or {}) return super(VersionAdmin, self).history_view(request, object_id, context) class VersionMetaAdmin(VersionAdmin): """ An enhanced VersionAdmin that annotates the given object with information about the last version that was saved. """ def get_queryset(self, request): """Returns the annotated queryset.""" content_type = ContentType.objects.get_for_model(self.model) pk = self.model._meta.pk if has_int_pk(self.model): version_table_field = "object_id_int" else: version_table_field = "object_id" return super(VersionMetaAdmin, self).get_queryset(request).extra( select = { "date_modified": """ SELECT MAX(%(revision_table)s.date_created) FROM %(version_table)s JOIN %(revision_table)s ON %(revision_table)s.id = %(version_table)s.revision_id WHERE %(version_table)s.content_type_id = %%s AND %(version_table)s.%(version_table_field)s = %(table)s.%(pk)s """ % { "revision_table": connection.ops.quote_name(Revision._meta.db_table), "version_table": connection.ops.quote_name(Version._meta.db_table), "table": connection.ops.quote_name(self.model._meta.db_table), "pk": connection.ops.quote_name(pk.db_column or pk.attname), "version_table_field": connection.ops.quote_name(version_table_field), } }, select_params = (content_type.id,), ) def get_date_modified(self, obj): """Displays the last modified date of the given object, typically for use in a change list.""" return localize(obj.date_modified) get_date_modified.short_description = "date modified"
{ "repo_name": "adonm/django-reversion", "path": "src/reversion/admin.py", "copies": "3", "size": "25200", "license": "bsd-3-clause", "hash": -4173467357610651000, "line_mean": 51.719665272, "line_max": 197, "alpha_frac": 0.6054761905, "autogenerated": false, "ratio": 4.279164544065206, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6384640734565206, "avg_score": null, "num_lines": null }
"""Admin extension tags.""" from django import template from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _, ugettext_lazy from modoboa.core import signals as core_signals from modoboa.lib.templatetags.lib_tags import render_link from modoboa.lib.web_utils import render_actions from .. import signals register = template.Library() genders = { "Enabled": (ugettext_lazy("enabled_m"), ugettext_lazy("enabled_f")) } @register.simple_tag def domains_menu(selection, user, ajax_mode=True): """Specific menu for domain related operations. Corresponds to the menu visible on the left column when you go to *Domains*. :param str selection: menu entry currently selected :param ``User`` user: connected user :rtype: str :return: rendered menu (as HTML) """ domain_list_url = ( "list/" if ajax_mode else reverse("admin:domain_list") ) entries = [ {"name": "domains", "label": _("List domains"), "img": "fa fa-user", "class": "ajaxnav navigation", "url": domain_list_url}, ] if user.has_perm("admin.add_domain"): extra_entries = signals.extra_domain_menu_entries.send( sender="domains_menu", user=user) for entry in extra_entries: entries += entry[1] entries += [ {"name": "import", "label": _("Import"), "img": "fa fa-folder-open", "url": reverse("admin:domain_import"), "modal": True, "modalcb": "admin.importform_cb"}, {"name": "export", "label": _("Export"), "img": "fa fa-share-alt", "url": reverse("admin:domain_export"), "modal": True, "modalcb": "admin.exportform_cb"} ] return render_to_string('common/menulist.html', { "entries": entries, "selection": selection, "user": user }) @register.simple_tag def identities_menu(user, selection=None, ajax_mode=True): """Menu specific to the Identities page. :param ``User`` user: the connecter user :rtype: str :return: the rendered menu """ nav_classes = "navigation" if ajax_mode: identity_list_url = "list/" quota_list_url = "quotas/" nav_classes += " ajaxnav" else: identity_list_url = reverse("admin:identity_list") quota_list_url = identity_list_url + "#quotas/" entries = [ {"name": "identities", "label": _("List identities"), "img": "fa fa-user", "class": nav_classes, "url": identity_list_url}, {"name": "quotas", "label": _("List quotas"), "img": "fa fa-hdd-o", "class": nav_classes, "url": quota_list_url}, {"name": "import", "label": _("Import"), "img": "fa fa-folder-open", "url": reverse("admin:identity_import"), "modal": True, "modalcb": "admin.importform_cb"}, {"name": "export", "label": _("Export"), "img": "fa fa-share-alt", "url": reverse("admin:identity_export"), "modal": True, "modalcb": "admin.exportform_cb"} ] return render_to_string('common/menulist.html', { "entries": entries, "user": user }) @register.simple_tag def domain_actions(user, domain): actions = [ {"name": "listidentities", "url": u"{0}#list/?searchquery=@{1}".format( reverse("admin:identity_list"), domain.name), "title": _("View the domain's identities"), "img": "fa fa-user"} ] if user.has_perm("admin.change_domain"): actions.append({ "name": "editdomain", "title": _("Edit {}").format(domain), "url": reverse("admin:domain_change", args=[domain.pk]), "modal": True, "modalcb": "admin.domainform_cb", "img": "fa fa-edit" }) if user.has_perm("admin.delete_domain"): actions.append({ "name": "deldomain", "url": reverse("admin:domain_delete", args=[domain.id]), "title": _("Delete %s?" % domain.name), "img": "fa fa-trash" }) responses = signals.extra_domain_actions.send( sender=None, user=user, domain=domain) for receiver, response in responses: if response: actions += response return render_actions(actions) @register.simple_tag def identity_actions(user, ident): name = ident.__class__.__name__ objid = ident.id if name == "User": actions = [] result = core_signals.extra_account_actions.send( sender="identity_actions", account=ident) for action in result: actions += action[1] url = ( reverse("admin:account_change", args=[objid]) + "?active_tab=default" ) actions += [ {"name": "changeaccount", "url": url, "img": "fa fa-edit", "modal": True, "modalcb": "admin.editaccount_cb", "title": _("Edit {}").format(ident.username)}, {"name": "delaccount", "url": reverse("admin:account_delete", args=[objid]), "img": "fa fa-trash", "title": _("Delete %s?" % ident.username)}, ] else: actions = [ {"name": "changealias", "url": reverse("admin:alias_change", args=[objid]), "img": "fa fa-edit", "modal": True, "modalcb": "admin.aliasform_cb", "title": _("Edit {}").format(ident)}, {"name": "delalias", "url": "{}?selection={}".format( reverse("admin:alias_delete"), objid), "img": "fa fa-trash", "title": _("Delete %s?" % ident.address)}, ] return render_actions(actions) @register.simple_tag def check_identity_status(identity): """Check if identity is enabled or not.""" if identity.__class__.__name__ == "User": if hasattr(identity, "mailbox") \ and not identity.mailbox.domain.enabled: return False elif not identity.is_active: return False elif not identity.enabled or not identity.domain.enabled: return False return True @register.simple_tag def domain_aliases(domain): """Display domain aliases of this domain. :param domain: :rtype: str """ if not domain.aliases.count(): return '---' res = '' for alias in domain.aliases.all(): res += '%s<br/>' % alias.name return mark_safe(res) @register.simple_tag def identity_modify_link(identity, active_tab='default'): """Return the appropriate modification link. According to the identity type, a specific modification link (URL) must be used. :param identity: a ``User`` or ``Alias`` instance :param str active_tab: the tab to display :rtype: str """ linkdef = {"label": identity.identity, "modal": True} if identity.__class__.__name__ == "User": linkdef["url"] = reverse("admin:account_change", args=[identity.id]) linkdef["url"] += "?active_tab=%s" % active_tab linkdef["modalcb"] = "admin.editaccount_cb" else: linkdef["url"] = reverse("admin:alias_change", args=[identity.id]) linkdef["modalcb"] = "admin.aliasform_cb" return render_link(linkdef) @register.simple_tag def domadmin_actions(daid, domid): actions = [{ "name": "removeperm", "url": "{0}?domid={1}&daid={2}".format( reverse("admin:permission_remove"), domid, daid), "img": "fa fa-trash", "title": _("Remove this permission") }] return render_actions(actions) @register.filter def gender(value, target): if value in genders: trans = target == "m" and genders[value][0] or genders[value][1] if trans.find("_") == -1: return trans return value @register.simple_tag def get_extra_admin_content(user, target, currentpage): results = signals.extra_admin_content.send( sender="get_extra_admin_content", user=user, location=target, currentpage=currentpage) if not results: return "" results = reduce(lambda a, b: a + b, [result[1] for result in results]) return mark_safe("".join(results))
{ "repo_name": "carragom/modoboa", "path": "modoboa/admin/templatetags/admin_tags.py", "copies": "1", "size": "8571", "license": "isc", "hash": 1376989862339531500, "line_mean": 30.0543478261, "line_max": 76, "alpha_frac": 0.5583945864, "autogenerated": false, "ratio": 3.8229259589652096, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.488132054536521, "avg_score": null, "num_lines": null }
"""Admin extension tags.""" from functools import reduce from django import template from django.template.loader import render_to_string from django.urls import reverse from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _, ugettext_lazy from modoboa.core import signals as core_signals from modoboa.lib.templatetags.lib_tags import render_link from modoboa.lib.web_utils import render_actions from .. import signals register = template.Library() genders = { "Enabled": (ugettext_lazy("enabled_m"), ugettext_lazy("enabled_f")) } @register.simple_tag def domains_menu(selection, user, ajax_mode=True): """Specific menu for domain related operations. Corresponds to the menu visible on the left column when you go to *Domains*. :param str selection: menu entry currently selected :param ``User`` user: connected user :rtype: str :return: rendered menu (as HTML) """ nav_classes = "navigation" if ajax_mode: domain_list_url = "list/" quota_list_url = "quotas/" logs_url = "logs/" nav_classes += " ajaxnav" else: domain_list_url = reverse("admin:domain_list") quota_list_url = domain_list_url + "#quotas/" logs_url = domain_list_url + "#logs/" entries = [ {"name": "domains", "label": _("List domains"), "img": "fa fa-user", "class": "ajaxnav navigation", "url": domain_list_url}, {"name": "quotas", "label": _("List quotas"), "img": "fa fa-hdd-o", "class": "ajaxnav navigation", "url": quota_list_url}, {"name": "logs", "label": _("Message logs"), "img": "fa fa-list", "class": "ajaxnav navigation", "url": logs_url}, ] if user.has_perm("admin.add_domain"): extra_entries = signals.extra_domain_menu_entries.send( sender="domains_menu", user=user) for entry in extra_entries: entries += entry[1] entries += [ {"name": "import", "label": _("Import"), "img": "fa fa-folder-open", "url": reverse("admin:domain_import"), "modal": True, "modalcb": "admin.importform_cb"}, {"name": "export", "label": _("Export"), "img": "fa fa-share-alt", "url": reverse("admin:domain_export"), "modal": True, "modalcb": "admin.exportform_cb"} ] return render_to_string("common/menulist.html", { "entries": entries, "selection": selection, "user": user }) @register.simple_tag def identities_menu(user, selection=None, ajax_mode=True): """Menu specific to the Identities page. :param ``User`` user: the connecter user :rtype: str :return: the rendered menu """ nav_classes = "navigation" if ajax_mode: identity_list_url = "list/" quota_list_url = "quotas/" nav_classes += " ajaxnav" else: identity_list_url = reverse("admin:identity_list") quota_list_url = identity_list_url + "#quotas/" entries = [ {"name": "identities", "label": _("List identities"), "img": "fa fa-user", "class": nav_classes, "url": identity_list_url}, {"name": "quotas", "label": _("List quotas"), "img": "fa fa-hdd-o", "class": nav_classes, "url": quota_list_url}, {"name": "import", "label": _("Import"), "img": "fa fa-folder-open", "url": reverse("admin:identity_import"), "modal": True, "modalcb": "admin.importform_cb"}, {"name": "export", "label": _("Export"), "img": "fa fa-share-alt", "url": reverse("admin:identity_export"), "modal": True, "modalcb": "admin.exportform_cb"} ] return render_to_string("common/menulist.html", { "entries": entries, "user": user }) @register.simple_tag def domain_actions(user, domain): actions = [ {"name": "listidentities", "url": u"{0}#list/?searchquery=@{1}".format( reverse("admin:identity_list"), domain.name), "title": _("View the domain's identities"), "img": "fa fa-user"}, ] if domain.alarms.opened().exists(): actions.append({ "name": "listalarms", "url": reverse("admin:domain_alarms", args=[domain.pk]), "title": _("View domain's alarms"), "img": "fa fa-bell" }) if user.has_perm("admin.change_domain"): actions.append({ "name": "editdomain", "title": _("Edit {}").format(domain), "url": reverse("admin:domain_change", args=[domain.pk]), "modal": True, "modalcb": "admin.domainform_cb", "img": "fa fa-edit" }) if user.has_perm("admin.delete_domain"): actions.append({ "name": "deldomain", "url": reverse("admin:domain_delete", args=[domain.id]), "title": _("Delete %s?") % domain.name, "img": "fa fa-trash" }) responses = signals.extra_domain_actions.send( sender=None, user=user, domain=domain) for _receiver, response in responses: if response: actions += response return render_actions(actions) @register.simple_tag def identity_actions(user, ident): name = ident.__class__.__name__ objid = ident.id if name == "User": actions = [] result = core_signals.extra_account_actions.send( sender="identity_actions", account=ident) for action in result: actions += action[1] url = ( reverse("admin:account_change", args=[objid]) + "?active_tab=default" ) actions += [ {"name": "changeaccount", "url": url, "img": "fa fa-edit", "modal": True, "modalcb": "admin.editaccount_cb", "title": _("Edit {}").format(ident.username)}, {"name": "delaccount", "url": reverse("admin:account_delete", args=[objid]), "img": "fa fa-trash", "title": _("Delete %s?") % ident.username}, ] else: actions = [ {"name": "changealias", "url": reverse("admin:alias_change", args=[objid]), "img": "fa fa-edit", "modal": True, "modalcb": "admin.aliasform_cb", "title": _("Edit {}").format(ident)}, {"name": "delalias", "url": "{}?selection={}".format( reverse("admin:alias_delete"), objid), "img": "fa fa-trash", "title": _("Delete %s?") % ident.address}, ] return render_actions(actions) @register.simple_tag def check_identity_status(identity): """Check if identity is enabled or not.""" if identity.__class__.__name__ == "User": if hasattr(identity, "mailbox") \ and not identity.mailbox.domain.enabled: return False elif not identity.is_active: return False elif not identity.enabled or not identity.domain.enabled: return False return True @register.simple_tag def domain_aliases(domain): """Display domain aliases of this domain. :param domain: :rtype: str """ if not domain.aliases.count(): return "---" res = "" for alias in domain.aliases.all(): res += "%s<br/>" % alias.name return mark_safe(res) @register.simple_tag def identity_modify_link(identity, active_tab="default"): """Return the appropriate modification link. According to the identity type, a specific modification link (URL) must be used. :param identity: a ``User`` or ``Alias`` instance :param str active_tab: the tab to display :rtype: str """ linkdef = {"label": identity.identity, "modal": True} if identity.__class__.__name__ == "User": linkdef["url"] = reverse("admin:account_change", args=[identity.id]) linkdef["url"] += "?active_tab=%s" % active_tab linkdef["modalcb"] = "admin.editaccount_cb" else: linkdef["url"] = reverse("admin:alias_change", args=[identity.id]) linkdef["modalcb"] = "admin.aliasform_cb" return render_link(linkdef) @register.simple_tag def domadmin_actions(daid, domid): actions = [{ "name": "removeperm", "url": "{0}?domid={1}&daid={2}".format( reverse("admin:permission_remove"), domid, daid), "img": "fa fa-trash", "title": _("Remove this permission") }] return render_actions(actions) @register.filter def gender(value, target): if value in genders: trans = target == "m" and genders[value][0] or genders[value][1] if trans.find("_") == -1: return trans return value @register.simple_tag def get_extra_admin_content(user, target, currentpage): results = signals.extra_admin_content.send( sender="get_extra_admin_content", user=user, location=target, currentpage=currentpage) if not results: return "" results = reduce(lambda a, b: a + b, [result[1] for result in results]) return mark_safe("".join(results))
{ "repo_name": "modoboa/modoboa", "path": "modoboa/admin/templatetags/admin_tags.py", "copies": "1", "size": "9425", "license": "isc", "hash": -5988359314644047000, "line_mean": 30.3122923588, "line_max": 76, "alpha_frac": 0.5515119363, "autogenerated": false, "ratio": 3.8111605337646584, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9862672470064657, "avg_score": 0, "num_lines": 301 }
""" admin for course catalog """ from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from course_catalog.models import ( Course, Program, UserList, ProgramItem, UserListItem, LearningResourceRun, CoursePrice, CourseInstructor, CourseTopic, Podcast, PodcastEpisode, Enrollment, ) class CourseInstructorAdmin(admin.ModelAdmin): """Instructor Admin""" model = CourseInstructor search_fields = ("full_name", "first_name", "last_name") class CoursePriceAdmin(admin.ModelAdmin): """Price Admin""" model = CoursePrice search_fields = ("price",) list_filter = ("mode",) class CourseTopicAdmin(admin.ModelAdmin): """Topic Admin""" model = CourseTopic search_fields = ("name",) class LearningResourceRunAdmin(admin.ModelAdmin): """LearningResourceRun Admin""" model = LearningResourceRun search_fields = ("run_id", "title", "course__course_id") list_display = ("run_id", "title", "best_start_date", "best_end_date") list_filter = ("semester", "year") exclude = ("course",) autocomplete_fields = ("prices", "instructors", "topics") class LearningResourceRunInline(GenericTabularInline): """Inline list items for course runs""" model = LearningResourceRun extra = 0 show_change_link = True fields = ( "run_id", "best_start_date", "best_end_date", "enrollment_start", "enrollment_end", "start_date", "end_date", "semester", "year", ) def has_delete_permission(self, request, obj=None): return False def has_change_permission(self, request, obj=None): return False def has_add_permission(self, request, obj=None): return False class CourseAdmin(admin.ModelAdmin): """Course Admin""" model = Course search_fields = ("course_id", "title") list_display = ("course_id", "title", "platform") list_filter = ("platform",) inlines = [LearningResourceRunInline] autocomplete_fields = ("topics",) class UserListItemInline(admin.StackedInline): """Inline list items for user lists""" model = UserListItem classes = ["collapse"] def has_delete_permission(self, request, obj=None): return True class ProgramItemInline(admin.StackedInline): """Inline list items for programs""" model = ProgramItem classes = ["collapse"] def has_delete_permission(self, request, obj=None): return True class ProgramAdmin(admin.ModelAdmin): """Program Admin""" model = Program list_display = ("title", "short_description") search_fields = ("title", "short_description") autocomplete_fields = ("topics",) inlines = [ProgramItemInline, LearningResourceRunInline] class UserListAdmin(admin.ModelAdmin): """UserList Admin""" model = UserList list_filter = ("privacy_level", "list_type") list_display = ("title", "short_description", "author", "privacy_level") search_fields = ("title", "short_description", "author__username", "author__email") inlines = [UserListItemInline] class PodcastAdmin(admin.ModelAdmin): """PodcastAdmin""" model = Podcast search_fields = ("full_description",) class PodcastEpisodeAdmin(admin.ModelAdmin): """PodcastEpisodeAdmin""" model = PodcastEpisode search_fields = ("full_description",) class EnrollmentAdmin(admin.ModelAdmin): """Enrollment Admin""" def run_id(self, obj): """run_id as string""" if obj.run: return f"{obj.run.run_id}" else: return "" def course_id(self, obj): """course_id as string""" if obj.course: return f"{obj.course.course_id}" else: return "" model = Enrollment search_fields = ( "course__course_id", "course__title", "enrollments_table_run_id", "run__run_id", "run__slug", "run__title", "user__email", "user__username", ) list_display = ( "enrollments_table_run_id", "user", "enrollment_timestamp", "run_id", "course_id", ) autocomplete_fields = ("run", "user") admin.site.register(CourseTopic, CourseTopicAdmin) admin.site.register(CoursePrice, CoursePriceAdmin) admin.site.register(CourseInstructor, CourseInstructorAdmin) admin.site.register(Course, CourseAdmin) admin.site.register(LearningResourceRun, LearningResourceRunAdmin) admin.site.register(Program, ProgramAdmin) admin.site.register(UserList, UserListAdmin) admin.site.register(Podcast, PodcastAdmin) admin.site.register(PodcastEpisode, PodcastEpisodeAdmin) admin.site.register(Enrollment, EnrollmentAdmin)
{ "repo_name": "mitodl/open-discussions", "path": "course_catalog/admin.py", "copies": "1", "size": "4808", "license": "bsd-3-clause", "hash": 7023131541726172000, "line_mean": 23.5306122449, "line_max": 87, "alpha_frac": 0.6439267887, "autogenerated": false, "ratio": 3.9185004074979624, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5062427196197963, "avg_score": null, "num_lines": null }
"""Admin for event-related models.""" import wtforms from pygotham.admin.utils import model_view from pygotham.events import models __all__ = ('EventModelView',) CATEGORY = 'Events' EventModelView = model_view( models.Event, 'Events', CATEGORY, column_list=('name', 'slug', 'begins', 'ends', 'active'), form_excluded_columns=( 'about_pages', 'announcements', 'calls_to_action', 'days', 'sponsor_levels', 'talks', 'volunteers', ), form_overrides={ 'activity_begins': wtforms.DateTimeField, 'activity_ends': wtforms.DateTimeField, 'proposals_begin': wtforms.DateTimeField, 'proposals_end': wtforms.DateTimeField, 'registration_begins': wtforms.DateTimeField, 'registration_ends': wtforms.DateTimeField, 'talk_list_begins': wtforms.DateTimeField, 'talk_schedule_begins': wtforms.DateTimeField, }, ) VolunteerModelView = model_view( models.Volunteer, 'Volunteers', CATEGORY, column_filters=('event.slug', 'event.name'), column_list=('event', 'user'), )
{ "repo_name": "pathunstrom/pygotham", "path": "pygotham/admin/events.py", "copies": "3", "size": "1128", "license": "bsd-3-clause", "hash": -2482564116813502500, "line_mean": 24.0666666667, "line_max": 61, "alpha_frac": 0.6267730496, "autogenerated": false, "ratio": 3.638709677419355, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 45 }
"""Admin for feedgrabber""" from django.contrib import admin from django.utils.translation import ugettext as _ from feedgrabber.models import Site from feedgrabber.models import Feed from feedgrabber.models import Item from feedgrabber.models import Author from feedgrabber.models import Category class FeedInline(admin.TabularInline): model = Feed extra = 1 class SiteAdmin(admin.ModelAdmin): inlines = [FeedInline,] list_display = ('name', 'url', 'language', 'description') list_filter = ('language',) search_fields = ('url', 'name', 'description', 'language') fieldsets = ((None, {'fields': ('name', 'url')}), (_('Informations'), {'fields': ('language', 'description')})) admin.site.register(Site, SiteAdmin) class FeedAdmin(admin.ModelAdmin): date_hierarchy = 'creation_date' list_display = ('site', 'name', 'url', 'creation_date', 'get_len_items', 'last_access', 'is_update') list_filter = ('site', 'creation_date', 'last_access') search_fields = ('url', 'name', 'description') fieldsets = ((None, {'fields': ('site', 'url')}), (_('Informations'), {'fields': ('name', 'description', 'last_access')})) admin.site.register(Feed, FeedAdmin) class AuthorAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'website', 'slug') search_fields = ('name', 'email', 'website') fields = ('name', 'slug', 'email', 'website') prepopulated_fields = {'slug': ('name',)} admin.site.register(Author, AuthorAdmin) class CategoryAdmin(admin.ModelAdmin): list_display = ('name', 'scheme', 'slug') search_fields = ('name', 'scheme') fields = ('name', 'slug', 'scheme') prepopulated_fields = {'slug': ('name',)} admin.site.register(Category, CategoryAdmin) class ItemAdmin(admin.ModelAdmin): date_hierarchy = 'creation_date' list_display = ('title', 'feed', 'get_author', 'publication_date', 'is_recent') list_filter = ('feed', 'creation_date', 'publication_date') search_fields = ('url', 'title', 'content', 'guid', 'comments') fieldsets = ((None, {'fields': ('feed', 'url')}), (_('Content'), {'fields': ('title', 'content')}), (_('Additional Content'), {'fields': ('guid', 'author', 'categories', 'ressource', 'comments')}), (_('Informations'), {'fields': ('creation_date', 'publication_date')})) admin.site.register(Item, ItemAdmin)
{ "repo_name": "Fantomas42/django-feedgrabber", "path": "feedgrabber/admin.py", "copies": "1", "size": "2568", "license": "bsd-3-clause", "hash": 4669199370199489000, "line_mean": 37.9090909091, "line_max": 88, "alpha_frac": 0.5934579439, "autogenerated": false, "ratio": 3.861654135338346, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4955112079238346, "avg_score": null, "num_lines": null }
"""admin for lifeX LifeXWeek: LifeXWeekAdmin LifeXIdea: LifeXIdeaAdmin LifeXCategory: LifeXCategoryAdmin LifeXPost: LifeXPostAdmin LifeXBlog: LifeXBlogAdmin """ from django.contrib import admin from .models import LifeXWeek, LifeXIdea, LifeXCategory, LifeXPost, LifeXBlog @admin.register(LifeXWeek) class LifeXWeekAdmin(admin.ModelAdmin): """ Admin for LifeX Week List: Week number, Start date, End date, No of posts Form: Nothing (week number is readonly) Search: Week number """ list_display = ( 'number', 'start_date', 'end_date', 'posts' ) ordering = ( '-number', ) search_fields = ( 'number', ) readonly_fields = ( 'number', ) view_on_site = True def start_date(self, obj): """start date of week Args: self(LifeXWeekAdmin) obj(LifeXWeek) Returns: Date: starting date of the week Raises: None """ return obj._start_week() def end_date(self, obj): """end date of week Args: self(LifeXWeekAdmin) obj(LifeXWeek) Returns: Date: ending date of the week Raises: None """ return obj._end_week() def posts(self, obj): """no of posts Total posts associated with a week Args: self(LifeXWeekAdmin) obj(LifeXWeek) Returns: int: total posts associated with week Raises: None """ return obj.lifexpost_set.count() @admin.register(LifeXIdea) class LifeXIdeaAdmin(admin.ModelAdmin): """Admin for LifeX Idea List: Id, Title, Experimented?, Retry?, Category Ordering: Id, Title, Experimented, Retry Filter: Category, Experimented?, Retry? Form: (ID is readonly) title, category, experimented, retry, body Search: ID, title """ list_display = ( 'idea_id', 'title', 'experimented', 'retry', 'category', ) ordering = ( 'idea_id', 'title', 'experimented', 'retry', ) search_fields = ( 'idea_id', 'title', ) list_filter = ( 'category', 'experimented', 'retry', ) readonly_fields = ( 'idea_id', ) view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'title', 'category', 'experimented', 'retry', ) }), ('Contents', { 'classes': ('full-width',), 'description': 'source can be selected', 'fields': ( 'body', ) }), ) @admin.register(LifeXCategory) class LifeXCategoryAdmin(admin.ModelAdmin): """ Admin for LifeX Category List: Name, Count of Ideas Order: Name Search: Name Form: Name, Slug """ list_display = ( 'name', 'ideas' ) ordering = ( 'name', ) search_fields = ( 'name', ) view_on_site = True def ideas(self, obj): """no of ideas count ideas associated with category Args: self(LifeXCategoryAdmin) obj(LifeXCategory) Returns: int: no of ideas Raises: None """ return obj.lifexidea_set.count() @admin.register(LifeXPost) class LifeXPostAdmin(admin.ModelAdmin): """ Admin for LifeX Posts List: ID, Title, Week, Idea, Date Order: Date, Week, ID Search: Title Date: date Filter: Tags, Week, Idea Form: ID(R), Title, Week(H), Idea(H), Date, Body, Tags(H) """ list_display = ( 'post_id', 'title', 'week', 'idea', 'date', ) ordering = ( '-date', '-week', '-post_id', ) search_fields = ( 'title', ) date_hierarchy = 'date' list_filter = ( 'tags', 'week', 'idea', ) filter_horizontal = ( 'tags', ) readonly_fields = ( 'post_id', ) view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'post_id', 'title', 'week', 'idea', 'date', ) }), ('Contents', { 'classes': ('full-width',), 'description': 'source can be selected', 'fields': ( 'body', ) }), ('Extras', { 'classes': ('collapse',), 'fields': ( 'tags', ) }), ) @admin.register(LifeXBlog) class LifeXBlogAdmin(admin.ModelAdmin): """ Admin for LifeX Blog List: ID, Title, Date Order: Date, Title Search: Title Date: date Form: ID(R), Title, Date, Body, Tags(H) """ list_display = ( 'post_id', 'title', 'date', ) ordering = ( '-date', 'title', ) search_fields = ( 'title', ) date_hierarchy = 'date' filter_horizontal = ( 'tags', ) readonly_fields = ( 'post_id', ) view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'post_id', 'title', 'date', ) }), ('Contents', { 'classes': ('full-width',), 'description': 'source can be selected', 'fields': ( 'body', ) }), ('Extras', { 'classes': ('collapse',), 'fields': ( 'tags', ) }), )
{ "repo_name": "efueger/harshp.com", "path": "lifeX/admin.py", "copies": "1", "size": "5889", "license": "mit", "hash": -2169981441393915100, "line_mean": 18.5, "line_max": 77, "alpha_frac": 0.4545763287, "autogenerated": false, "ratio": 3.9417670682730925, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9896343396973093, "avg_score": 0, "num_lines": 302 }
"""Admin for movie_metadata MovieAdmin """ from django.contrib import admin from movie_metadata.models import Movie from movie_metadata.models import Actor from movie_metadata.models import Director from movie_metadata.models import Person class MovieActorInline(admin.TabularInline): """Show movies inline on Actor forms """ model = Movie.actors.through class MovieDirectorInline(admin.TabularInline): """Show movies inline on Director forms """ model = Movie.directors.through @admin.register(Movie) class MovieAdmin(admin.ModelAdmin): """Admin for Movie class """ # display fields in movie index list_display = ( 'title', 'release', 'relpath', 'imdb_score', 'tomatoes_rating', 'metascore' ) # sort columns ordering = ( 'title', 'release', 'imdb_score', 'tomatoes_rating', 'metascore' ) # search based on fields search_fields = ( 'title', 'relpath', ) # sort based on date field date_hierarchy = 'release' # filter results based on fields list_filter = ( 'actors', 'directors', ) # horizontal multi-select columns in movie edit forms filter_horizontal = ( 'actors', 'directors', ) # read-only fields in forms readonly_fields = ('_id',) # inlines = [ActorInline, ] @admin.register(Actor) class ActorAdmin(admin.ModelAdmin): """Admin for Actors """ list_display = ( 'name', 'no_movies', 'is_director', 'directed', ) def name(self, obj): """Actor Name """ return obj.person.name def no_movies(self, obj): """No of movies acted in """ return obj.movie_set.count() no_movies.short_description = 'Movies acted in' def is_director(self, obj): """Is also a director? """ try: if obj.person.director: return True except Exception: pass return False is_director.short_description = 'Director?' is_director.boolean = True def directed(self, obj): """No of Movies directed """ try: if obj.person.director is not None: return obj.person.director.movie_set.count() except Exception: pass return 0 directed.short_description = 'Movies Directed' search_fields = ('person__name',) readonly_fields = ('person',) fieldsets = ( ('Person', { 'fields': ( 'person', ) }), ) inlines = [MovieActorInline, ] @admin.register(Director) class DirectorAdmin(admin.ModelAdmin): """Admin for Directors """ list_display = ( 'name', 'no_movies', 'is_actor', 'acted', ) def name(self, obj): """Director Name """ return obj.person.name def no_movies(self, obj): """No of movies directed """ return obj.movie_set.count() no_movies.short_description = 'Movies directed' def is_actor(self, obj): """Is also an actor? """ try: if obj.person.actor: return True except Exception: pass return False is_actor.short_description = 'Actor?' is_actor.boolean = True def acted(self, obj): """No of Movies acted in """ try: if obj.person.actor is not None: return obj.person.actor.movie_set.count() except Exception: pass return 0 acted.short_description = 'Movies acted in' search_fields = ('person__name',) readonly_fields = ('person',) fieldsets = ( ('Person', { 'fields': ( 'person', ) }), ) inlines = [MovieDirectorInline, ] @admin.register(Person) class PersonAdmin(admin.ModelAdmin): """Admin for Actors """ list_display = ( 'name', 'no_movies', 'is_actor', 'acted', 'is_director', 'directed', ) def no_movies(self, obj): """No of movies acted in """ # return obj.movie_set.count() return 0 def is_actor(self, obj): """Is also an actor? """ try: if obj.actor: return True except Exception: pass return False is_actor.short_description = 'Actor?' is_actor.boolean = True def acted(self, obj): """No of Movies acted in """ try: if obj.actor is not None: return obj.actor.movie_set.count() except Exception: pass return 0 acted.short_description = 'Movies acted in' def is_director(self, obj): """Is also a director? """ try: if obj.director: return True except Exception: pass return False is_director.short_description = 'Director?' is_director.boolean = True def directed(self, obj): """No of Movies directed """ try: if obj.director is not None: return obj.director.movie_set.count() except Exception: pass return 0 directed.short_description = 'Movies Directed' search_fields = ('name',) fieldsets = ( ('Person', { 'fields': ( 'name', ) }), )
{ "repo_name": "coolharsh55/hdd-indexer", "path": "movie_metadata/admin.py", "copies": "1", "size": "5648", "license": "mit", "hash": -4604653232358931500, "line_mean": 20.7230769231, "line_max": 60, "alpha_frac": 0.5207152975, "autogenerated": false, "ratio": 4.18060695780903, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 260 }
"""Admin forms.""" from django import forms from happening import forms as happening_forms from payments.models import PaymentHandler from allauth.socialaccount.models import SocialApp from happening.models import NavigationItemConfiguration from happening.forms import BooleanField, MarkdownField from happening.forms import EmailToField, DateTimeRangeField from emails.models import Email from django.contrib.auth.models import Group class ConfigurationForm(forms.Form): """A form to attach custom configuration variables to.""" pass class PaymentHandlerForm(forms.ModelForm): """Form for creating/modifying payment handlers.""" class Meta: model = PaymentHandler fields = ['description', 'public_key', 'secret_key'] class ThemeForm(forms.Form): """Form for changing theme options.""" logo = happening_forms.ImageField() class SocialAppForm(forms.ModelForm): """Form for creating/modifying social apps.""" class Meta: model = SocialApp fields = ['provider', 'name', 'client_id', 'secret'] class AddMenuForm(forms.ModelForm): """Form for adding a menu.""" class Meta: model = NavigationItemConfiguration fields = ['name'] def __init__(self, *args, **kwargs): """Initialise menu form.""" menus = kwargs.pop("menus") super(AddMenuForm, self).__init__(*args, **kwargs) self.fields["name"] = forms.ChoiceField(choices=menus) class EmailForm(forms.ModelForm): """Form for sending emails.""" class Meta: model = Email fields = ['to', 'subject', 'content'] to = EmailToField() content = MarkdownField() sending_range = DateTimeRangeField(allow_instant=True) def save(self, commit=True): """Save email.""" instance = super(EmailForm, self).save(commit=commit) if not self.cleaned_data['sending_range'] == '': parts = self.cleaned_data['sending_range'].split("---") instance.start_sending = parts[0] instance.stop_sending = parts[1] if commit: instance.save() return instance class WaitingListForm(forms.Form): """Form for setting up waiting lists.""" automatic = BooleanField(label="Automatically manage waiting list", required=False) class PageForm(forms.Form): """Form for creating a page.""" url = forms.CharField() title = forms.CharField() class GroupForm(forms.ModelForm): """Form for creating groups.""" class Meta: model = Group fields = ['name']
{ "repo_name": "happeninghq/happening", "path": "src/admin/forms.py", "copies": "2", "size": "2615", "license": "mit", "hash": -5119631245960311000, "line_mean": 22.9908256881, "line_max": 71, "alpha_frac": 0.6500956023, "autogenerated": false, "ratio": 4.308072487644152, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 109 }
# admin/forms.py # Jake Malley # 19/02/15 """ Defines the forms to be used in the admin blueprint. """ # Imports from flask_wtf import Form from wtforms import TextField, PasswordField, BooleanField from wtforms.validators import DataRequired, Length, EqualTo, Email # DataRequired validator makes sure the data is present in the field. # Length validator makes sure the field is between a specific length # EqualTo validator makes sure the field is equal to another field. # Email validator makes sure the field is a valid email. class AdminEditDetailsForm(Form): """ Form for administrators to edit personal details. """ # Hidden field for the exercise id. member_id = TextField('member_id') # Text field for the users firstname. firstname = TextField( 'firstname', validators=[DataRequired(),Length(min=2,max=20)] ) # Text field for the users surname. surname = TextField( 'surname', validators=[DataRequired(), Length(min=2,max=20)] ) # Text field for the users email. email = TextField( 'email', validators=[DataRequired(),Email(message=None)] ) # Password field for the password. password = PasswordField( 'password', validators=[Length(max=32)] ) # Password field for the password confirm. confirm_password = PasswordField( 'confirm_password', validators=[EqualTo('password',message='Passwords must match.')] ) # Boolean Field for setting admin. set_admin = BooleanField('admin') # Boolean Field for setting active set_active = BooleanField('admin') # Boolean Field for deleting the user. delete_user = BooleanField('delete_user')
{ "repo_name": "jakemalley/training-log", "path": "traininglog/admin/forms.py", "copies": "1", "size": "1730", "license": "mit", "hash": -867904260281487400, "line_mean": 29.3684210526, "line_max": 72, "alpha_frac": 0.6786127168, "autogenerated": false, "ratio": 4.109263657957245, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0056470613139379035, "num_lines": 57 }
# Admin form vaildation from django import forms from itxland.catalog.models import Product class ProductAdminForm(forms.ModelForm): """ ModelForm class to validate product instance data before saving from admin interface """ class Meta: model = Product def clean_price(self): if self.cleaned_data['price'] <= 0: raise forms.ValidationError('Price supplied must be greater than zero.') return self.cleaned_data['price'] class ProductAddToCartForm(forms.Form): quantity = forms.IntegerField(widget=forms.TextInput(attrs={'size':'2', 'value':'1', 'class':'quantity', 'maxlength':'5'}), error_messages={'invalid':'Please enter a valid quantity.'}, min_value=1) product_slug = forms.CharField(widget=forms.HiddenInput()) # override the default __init__ so we can set the request def __init__(self, request=None, *args, **kwargs): self.request = request super(ProductAddToCartForm, self).__init__(*args, **kwargs) # custom validation to check for cookies def clean(self): if self.request: if not self.request.session.test_cookie_worked(): raise forms.ValidationError("Cookies must be enabled.") return self.cleaned_data
{ "repo_name": "davidhenry/ITX-Land", "path": "catalog/forms.py", "copies": "1", "size": "1206", "license": "mit", "hash": 8304155549326911000, "line_mean": 35.5454545455, "line_max": 96, "alpha_frac": 0.7031509121, "autogenerated": false, "ratio": 3.853035143769968, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5056186055869968, "avg_score": null, "num_lines": null }
"""Admin for news-related models.""" import wtforms from pygotham.admin.utils import model_view from pygotham.news import models __all__ = ('AnnouncementModelView', 'CallToActionModelView') CATEGORY = 'News' AnnouncementModelView = model_view( models.Announcement, 'Announcements', CATEGORY, column_default_sort='published', column_filters=('event.slug', 'event.name'), column_list=('title', 'published', 'active'), form_columns=('title', 'content', 'active', 'published'), form_overrides={ 'published': wtforms.DateTimeField, }, ) CallToActionModelView = model_view( models.CallToAction, 'Calls to Action', CATEGORY, column_default_sort='begins', column_filters=('event.slug', 'event.name'), column_list=('title', 'event', 'begins', 'ends', 'active'), form_columns=('title', 'url', 'event', 'begins', 'ends', 'active'), form_overrides={ 'url': wtforms.TextField, 'begins': wtforms.DateTimeField, 'ends': wtforms.DateTimeField, }, )
{ "repo_name": "djds23/pygotham-1", "path": "pygotham/admin/news.py", "copies": "3", "size": "1044", "license": "bsd-3-clause", "hash": -4524167822095535000, "line_mean": 25.7692307692, "line_max": 71, "alpha_frac": 0.648467433, "autogenerated": false, "ratio": 3.527027027027027, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 39 }
"""Admin for schedule-related models.""" from pygotham.admin.utils import model_view from pygotham.schedule import models # This line is really long because pep257 needs it to be on one line. __all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView') CATEGORY = 'Schedule' DayModelView = model_view( models.Day, 'Days', CATEGORY, column_default_sort='date', column_filters=('event.slug', 'event.name'), column_list=('date', 'event'), form_columns=('event', 'date'), ) RoomModelView = model_view( models.Room, 'Rooms', CATEGORY, column_default_sort='order', form_columns=('name', 'order'), ) SlotModelView = model_view( models.Slot, 'Slots', CATEGORY, column_default_sort='start', column_filters=('day', 'day.event.slug', 'day.event.name'), column_list=( 'day', 'rooms', 'kind', 'start', 'end', 'presentation', 'content_override', ), form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'), ) PresentationModelView = model_view( models.Presentation, 'Presentations', CATEGORY, )
{ "repo_name": "djds23/pygotham-1", "path": "pygotham/admin/schedule.py", "copies": "1", "size": "1142", "license": "bsd-3-clause", "hash": 1690834934835651300, "line_mean": 21.84, "line_max": 85, "alpha_frac": 0.6374781086, "autogenerated": false, "ratio": 3.4191616766467066, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45566397852467067, "avg_score": null, "num_lines": null }
"""admin for sitedata Tag: TagAdmin Book: BookAdmin Movie: MovieAdmin TVShow: TVShowAdmin Game: GameAdmin """ from django.contrib import admin from .models import Tag @admin.register(Tag) class TagAdmin(admin.ModelAdmin): """Admin for Tags List: tagname, count of linked objects Order: tagname, tag id Search: tagname Tag ID is a readonly field """ list_display = ( 'tagname', 'linked_objects', ) ordering = ( 'tagname', 'tagid', ) search_fields = ( 'tagname', ) readonly_fields = ( 'tagid', ) view_on_site = True def linked_objects(self, obj): """linked objects using the tag count number of objects using this tag Args: self(TagAdmin) obj(Tag) Returns: int: no of objects Raises: None """ linked_objects = \ obj.blogpost_set.count() + \ obj.storypost_set.count() + \ obj.poem_set.count() + \ obj.article_set.count() + \ obj.brainbankpost_set.count() + \ obj.lifexpost_set.count() + obj.lifexblog_set.count() + \ obj.book_set.count() + obj.movie_set.count() + \ obj.tvshow_set.count() + obj.game_set.count() return linked_objects from .models import Book @admin.register(Book) class BookAdmin(admin.ModelAdmin): """Admin for Books List: title, read, start date, end date Order: title, read, start date, end date Search: title Filter: Read, start date, end date Form: (ID is readonly) title, read, start/end date, slug, tags """ list_display = ( 'title', 'read', 'date_start', 'date_end', ) ordering = ( 'title', 'read', 'date_start', 'date_end', ) search_fields = ( 'title', ) list_filter = ( 'read', 'date_start', 'date_end', ) readonly_fields = ( '_id', ) filter_horizontal = ( 'tags', ) view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'title', '_id', 'read', 'date_start', 'date_end', 'slug', ), }), ('Tags', { 'fields': ( 'tags', ), }), ) from .models import Movie @admin.register(Movie) class MovieAdmin(admin.ModelAdmin): """Admin for Movies List: title, read, seen date Order: title, read, seen date Search: title Date: seen date Form: (ID is readonly) title, seen date, slug, tags """ list_display = ( 'title', 'date_seen', ) ordering = ( 'title', 'date_seen', ) search_fields = ( 'title', ) date_hierarchy = 'date_seen' readonly_fields = ( '_id', ) filter_horizontal = ( 'tags', ) view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'title', '_id', 'date_seen', 'slug', ), }), ('Tags', { 'fields': ( 'tags', ), }), ) from .models import TVShow @admin.register(TVShow) class TVShowAdmin(admin.ModelAdmin): """Admin for TV Shows List: title, watched, start date, end date Order: title, watched, start date, end date Search: title Filter: watched, start date, end date Form: (ID is readonly) title, watched, start/end date, slug, tags """ list_display = ( 'title', 'watched', 'date_start', 'date_end', ) ordering = ( 'title', 'watched', 'date_start', 'date_end', ) search_fields = ( 'title', ) list_filter = ( 'watched', 'date_start', 'date_end', ) readonly_fields = ( '_id', ) filter_horizontal = ( 'tags', ) view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'title', '_id', 'watched', 'date_start', 'date_end', ), }), ('Tags', { 'fields': ( 'tags', ), }), ) from .models import Game @admin.register(Game) class GameAdmin(admin.ModelAdmin): """Admin for Games List: title, finished, start date, end date Order: title, finished, start date, end date Search: title Filter: finished, start date, end date Form: (ID is finishedonly) title, finished, start/end date, slug, tags """ list_display = ( 'title', 'finished', 'date_start', 'date_end', ) ordering = ( 'title', 'finished', 'date_start', 'date_end', ) search_fields = ( 'title', ) list_filter = ( 'finished', 'date_start', 'date_end', ) finishedonly_fields = ( '_id', ) filter_horizontal = ( 'tags', ) view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'title', '_id', 'finished', 'date_start', 'date_end', ), }), ('Tags', { 'fields': ( 'tags', ), }), )
{ "repo_name": "efueger/harshp.com", "path": "sitedata/admin.py", "copies": "1", "size": "5663", "license": "mit", "hash": 1273312408912490800, "line_mean": 19.0815602837, "line_max": 74, "alpha_frac": 0.4472894226, "autogenerated": false, "ratio": 3.9740350877192983, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9915810376436369, "avg_score": 0.001102826776585642, "num_lines": 282 }
"""admin for stories StoryPost: StoryPostAdmin """ from django.contrib import admin from .models import StoryPost @admin.register(StoryPost) class StoryPostAdmin(admin.ModelAdmin): """Admin for story """ list_display = ( 'title', 'published', 'post_id', 'tags_count', ) ordering = ( '-post_id', 'published', 'title' ) search_fields = ( 'title', ) date_hierarchy = 'published' list_filter = ( 'published', 'tags', 'modified', ) filter_horizontal = ( 'tags', ) # exclude = ('') readonly_fields = ( 'post_id', ) prepopulated_fields = { "slug": ( "title", ) } view_on_site = True fieldsets = ( ('Details', { 'fields': ( 'post_id', 'title', 'published', 'modified', ) }), ('Contents', { 'classes': ('full-width',), 'description': 'source can be selected', 'fields': ( 'body', ) }), ('Extras', { 'classes': ('collapse',), 'fields': ( 'headerimage', 'tags', 'slug', ) }), ) # future: status/draft or published/NO or publish/future # def suit_row_attributes(self, obj, request): # return {'class': 'error'} def tags_count(self, obj): """tag count count the tags associated with a story """ return obj.tags.count()
{ "repo_name": "efueger/harshp.com", "path": "stories/admin.py", "copies": "1", "size": "1670", "license": "mit", "hash": -6684481618113385000, "line_mean": 19.1204819277, "line_max": 60, "alpha_frac": 0.4299401198, "autogenerated": false, "ratio": 4.227848101265823, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 83 }
"""Admin for talk-related models.""" from flask_admin import actions from flask.ext.admin.contrib.sqla import ModelView from pygotham.admin.utils import model_view from pygotham.core import db from pygotham.talks import models __all__ = ('CategoryModelView', 'talk_model_view', 'TalkReviewModelView') CATEGORY = 'Talks' class TalkModelView(ModelView, actions.ActionsMixin): """Admin view for :class:`~pygotham.models.Talk`.""" column_default_sort = 'id' column_filters = ( 'status', 'duration', 'level', 'event.slug', 'event.name') column_list = ('name', 'status', 'duration', 'level', 'type', 'user') column_searchable_list = ('name',) form_excluded_columns = ('presentation',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.init_actions() @actions.action( 'accept', 'Accept', 'Are you sure you want to accept selected models?') def approve(self, talks): for pk in talks: talk = models.Talk.query.get(pk) talk.status = 'accepted' self.session.commit() @actions.action( 'reject', 'Reject', 'Are you sure you want to reject selected models?') def reject(self, talks): for pk in talks: talk = models.Talk.query.get(pk) talk.status = 'rejected' self.session.commit() CategoryModelView = model_view( models.Category, 'Categories', CATEGORY, form_columns=('name', 'slug'), ) DurationModelView = model_view( models.Duration, 'Durations', CATEGORY, ) talk_model_view = TalkModelView( models.Talk, db.session, 'Talks', CATEGORY, 'talks') TalkReviewModelView = model_view( models.Talk, 'Review', CATEGORY, acceptable_roles=('reviewer',), can_create=False, can_delete=False, column_default_sort='id', column_filters=('event.slug', 'event.name'), column_list=('name', 'status', 'level', 'type', 'user'), column_searchable_list=('name',), edit_template='talks/review.html', )
{ "repo_name": "PyGotham/pygotham", "path": "pygotham/admin/talks.py", "copies": "2", "size": "2050", "license": "bsd-3-clause", "hash": 433286090152853600, "line_mean": 25.9736842105, "line_max": 79, "alpha_frac": 0.6302439024, "autogenerated": false, "ratio": 3.4686971235194584, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 76 }
""" Admin for techtv2ovs """ from django.contrib import admin from techtv2ovs.models import TechTVCollection, TechTVVideo class TechTVCollectionAdmin(admin.ModelAdmin): """Customized collection admin model""" model = TechTVCollection list_display = ("id", "name", "description") readonly_fields = ("id", "name", "description") search_fields = ( "name", "description", "collection__title", ) class TechTVVideoAdmin(admin.ModelAdmin): """Customized Video admin model""" model = TechTVVideo list_display = ( "id", "title", "description", "status", ) readonly_fields = ( "id", "ttv_id", "title", "description", "errors", "private", "private_token", "external_id", ) list_filter = ("status", "thumbnail_status", "videofile_status", "subtitle_status") search_fields = ( "ttv_id", "title", "ttv_collection__name", ) admin.site.register(TechTVCollection, TechTVCollectionAdmin) admin.site.register(TechTVVideo, TechTVVideoAdmin)
{ "repo_name": "mitodl/odl-video-service", "path": "techtv2ovs/admin.py", "copies": "1", "size": "1135", "license": "bsd-3-clause", "hash": 4790093024867242000, "line_mean": 21.7, "line_max": 87, "alpha_frac": 0.5929515419, "autogenerated": false, "ratio": 3.7582781456953644, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4851229687595364, "avg_score": null, "num_lines": null }
# Admin for top-level ICEKit models from django.conf import settings from django.conf.urls import url, patterns from django.contrib import admin from django.contrib.contenttypes.models import ContentType from django.http import JsonResponse from icekit import models from icekit.admin_tools.mixins import RawIdPreviewAdminMixin, \ BetterDateTimeAdmin from django.db.models import DateTimeField, DateField, TimeField class LayoutAdmin(admin.ModelAdmin): filter_horizontal = ('content_types',) list_display = ('title', 'display_template_name', 'display_content_types' ) def _get_ctypes(self): """ Returns all related objects for this model. """ ctypes = [] for related_object in self.model._meta.get_all_related_objects(): model = getattr(related_object, 'related_model', related_object.model) ctypes.append(ContentType.objects.get_for_model(model).pk) if model.__subclasses__(): for child in model.__subclasses__(): ctypes.append(ContentType.objects.get_for_model(child).pk) return ctypes def display_content_types(self, obj): return ", ".join([unicode(x) for x in obj.content_types.all()]) def display_template_name(self, obj): return obj.template_name def placeholder_data_view(self, request, id): """ Return placeholder data for the given layout's template. """ # See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`. try: layout = models.Layout.objects.get(pk=id) except models.Layout.DoesNotExist: json = {'success': False, 'error': 'Layout not found'} status = 404 else: placeholders = layout.get_placeholder_data() status = 200 placeholders = [p.as_dict() for p in placeholders] # inject placeholder help text, if any is set for p in placeholders: try: p['help_text'] = settings.FLUENT_CONTENTS_PLACEHOLDER_CONFIG.get(p['slot']).get('help_text') except AttributeError: p['help_text'] = None json = { 'id': layout.id, 'title': layout.title, 'placeholders': placeholders, } return JsonResponse(json, status=status) def get_urls(self): """ Add ``layout_placeholder_data`` URL. """ # See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`. urls = super(LayoutAdmin, self).get_urls() my_urls = patterns( '', url( r'^placeholder_data/(?P<id>\d+)/$', self.admin_site.admin_view(self.placeholder_data_view), name='layout_placeholder_data', ) ) return my_urls + urls def formfield_for_manytomany(self, db_field, request=None, **kwargs): if db_field.name == "content_types": kwargs["queryset"] = ContentType.objects.filter(pk__in=self._get_ctypes()) return super(LayoutAdmin, self)\ .formfield_for_manytomany(db_field, request, **kwargs) class MediaCategoryAdmin(admin.ModelAdmin): pass # import has to happen here to avoid circular import errors from icekit.publishing.admin import PublishingAdmin, \ PublishableFluentContentsAdmin from icekit.workflow.admin import WorkflowMixinAdmin, WorkflowStateTabularInline class ICEkitContentsAdmin( BetterDateTimeAdmin, PublishingAdmin, WorkflowMixinAdmin, RawIdPreviewAdminMixin, ): """ A base for generic admins that will include ICEkit features: - publishing - workflow - Better date controls """ list_display = PublishingAdmin.list_display + \ WorkflowMixinAdmin.list_display list_filter = PublishingAdmin.list_filter + \ WorkflowMixinAdmin.list_filter inlines = [WorkflowStateTabularInline] class ICEkitFluentContentsAdmin( BetterDateTimeAdmin, PublishableFluentContentsAdmin, WorkflowMixinAdmin, RawIdPreviewAdminMixin, ): """ A base for Fluent Contents admins that will include ICEkit features: - publishing - workflow - Better date controls """ list_display = ICEkitContentsAdmin.list_display list_filter = ICEkitContentsAdmin.list_filter inlines = ICEkitContentsAdmin.inlines class ICEkitInlineAdmin(BetterDateTimeAdmin): """ A base for Inlines that will include ICEkit features: - Better date controls (we don't need RawIdPreview as the behaviour is injected into Inlines from the parent) """ pass admin.site.register(models.Layout, LayoutAdmin) admin.site.register(models.MediaCategory, MediaCategoryAdmin) # Classes that used to be here from icekit.admin_tools.filters import \ ChildModelFilter as new_ChildModelFilter from icekit.admin_tools.polymorphic import \ PolymorphicAdminUtilsMixin as new_PolymorphicAdminUtilsMixin, \ ChildModelPluginPolymorphicParentModelAdmin as new_ChildModelPluginPolymorphicParentModelAdmin from icekit.utils.deprecation import deprecated @deprecated class ChildModelFilter(new_ChildModelFilter): """ .. deprecated:: Use :class:`icekit.admin_tools.filters.ChildModelFilter` instead. """ pass @deprecated class PolymorphicAdminUtilsMixin(new_PolymorphicAdminUtilsMixin): """ .. deprecated:: Use :class:`icekit.admin_tools.polymorphic.PolymorphicAdminUtilsMixin` instead. """ pass @deprecated class ChildModelPluginPolymorphicParentModelAdmin(new_ChildModelPluginPolymorphicParentModelAdmin): """ .. deprecated:: Use :class:`icekit.admin_tools.polymorphic.ChildModelPluginPolymorphicParentModelAdmin` instead. """ pass
{ "repo_name": "ic-labs/django-icekit", "path": "icekit/admin.py", "copies": "1", "size": "5857", "license": "mit", "hash": -3102546891658022400, "line_mean": 29.3471502591, "line_max": 112, "alpha_frac": 0.6655284275, "autogenerated": false, "ratio": 4.130465444287729, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5295993871787729, "avg_score": null, "num_lines": null }
"""Admin forward Kerberos tickets to the cell ticket locker. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import sys import click from treadmill import cli from treadmill import context from treadmill import discovery from treadmill import krb from treadmill import exc _LOGGER = logging.getLogger(__name__) _ON_EXCEPTIONS = cli.handle_exceptions([ (exc.InvalidInputError, None), ]) def _iterate(discovery_iter): """Iterate discovered endpoints.""" hostports = [] for (_, hostport) in discovery_iter: if not hostport: continue host, port = hostport.split(':') hostports.append((host, int(port))) return hostports def init(): """Return top level command handler""" @click.command() @click.option('--cell', required=True, envvar='TREADMILL_CELL', callback=cli.handle_context_opt) @click.option('--proid', required=True, help='Proid.') @click.option('--spn', default=None, help='Service Principal Name used in the Kerberos protocol.') @click.option('--acceptors', required=False, type=cli.LIST, help='List of ticket acceptors (host:port).') @click.argument('endpoint', required=False) @_ON_EXCEPTIONS def forward(endpoint, spn, proid, cell, acceptors): """Forward Kerberos tickets to the cell ticket locker.""" _LOGGER.setLevel(logging.INFO) if not endpoint: endpoint = '*' if not acceptors: pattern = "{0}.tickets-v2".format(proid) discovery_iter = discovery.iterator( context.GLOBAL.zk.conn, pattern, endpoint, False ) hostports = _iterate(discovery_iter) else: hostports = [] for hostport in acceptors: host, port = hostport.split(':') hostports.append((host, int(port))) failure = krb.forward(cell, hostports, tktfwd_spn=spn) sys.exit(failure) return forward
{ "repo_name": "Morgan-Stanley/treadmill", "path": "lib/python/treadmill/cli/admin/krb/forward.py", "copies": "1", "size": "2154", "license": "apache-2.0", "hash": 8142667999282794000, "line_mean": 28.1081081081, "line_max": 79, "alpha_frac": 0.6202414113, "autogenerated": false, "ratio": 4.003717472118959, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5123958883418959, "avg_score": null, "num_lines": null }
""" Admin functions """ from hxl_proxy import app from flask import flash, session from hxl_proxy import dao, exceptions, util import hashlib, json ######################################################################## # Authentication and authorisation ######################################################################## def admin_auth (): """ Check authorisation for admin tasks Will redirect to a login page if not authorised. ADMIN_PASSWORD_MD5 must be set in the config file """ if not session.get('is_admin'): flash("Password required for admin functions") raise exceptions.RedirectException('/admin/login') def do_admin_login (password): """ POST action: log into admin functions @param password: the text of the admin password """ expected_passhash = app.config.get('ADMIN_PASSWORD_MD5') actual_passhash = hashlib.md5(password.encode("utf-8")).hexdigest() if expected_passhash == actual_passhash: session['is_admin'] = True else: flash("Wrong password") raise exceptions.Redirect('/admin/login') def do_admin_logout (): """ POST action: log out of admin functions """ admin_auth() session['is_admin'] = False ######################################################################## # Admin functions for recipes ######################################################################## def admin_get_recipes (): """ Get a list of saved recipes for the admin page @returns: a list of recipes (just dicts, not Recipe objects) """ admin_auth() recipes = dao.recipes.list() return recipes def admin_get_recipe (recipe_id): """ Look up and return a single recipe for the admin page @param recipe_id: the hash id for the saved recipe @returns: a Recipe object """ admin_auth() recipe = dao.recipes.read(recipe_id) return recipe def do_admin_update_recipe (fields): """ POST action: force-update a saved recipe """ admin_auth() # original data fields data_fields = dao.recipes.read(fields['recipe_id']) # try parsing the JSON args string try: fields['args'] = json.loads(fields['args']) except: flash("Parsing error in JSON arguments; restoring old values") raise exceptions.RedirectException("/admin/recipes/{}/edit.html".format(fields['recipe_id'])) # munge the checkbox value if fields.get('cloneable') == 'on': if 'authorization_token' in fields['args']: flash("Cannot make recipe cloneable (contains authorisation token)") fields['cloneable'] = False else: fields['cloneable'] = True else: fields['cloneable'] = False # see if there's a new password if fields.get('password'): flash("Updated recipe password") fields['passhash'] = util.make_md5(fields['password']) del fields['password'] # copy over the new fields for key in fields: data_fields[key] = fields[key] # save to the database dao.recipes.update(data_fields) def do_admin_delete_recipe (recipe_id): admin_auth() dao.recipes.delete(recipe_id)
{ "repo_name": "HXLStandard/hxl-proxy", "path": "hxl_proxy/admin.py", "copies": "1", "size": "3194", "license": "unlicense", "hash": 2220012253229548300, "line_mean": 27.5178571429, "line_max": 101, "alpha_frac": 0.5876643707, "autogenerated": false, "ratio": 4.369357045143639, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.008539323593504785, "num_lines": 110 }
# /admin/__init__.py from portfolio.application import application from portfolio.application.base import root_dir from os.path import join, split from functools import wraps from flask import abort, jsonify, request, session from bcrypt import hashpw def needs_logged_in(function): """ A function wrapper that ensures the user is logged in before their request is processed. """ @wraps(function) def wrapper(*args, **kwargs): if "admin" not in session: abort(403) return function(*args, **kwargs) return wrapper @application.route("/admin/api/login", methods=["POST"]) def login(): data = request.get_json() if data is None: abort(400) if "password" not in data: abort(400) # open the password file fname = join(split(root_dir)[0], "passwd") with open(fname, "rb") as f: password = f.readline() if hashpw(data["password"].encode("utf-8"), password) == password: session["admin"] = True return jsonify(**{ "auth": True }) return jsonify(**{ "auth": False }) @application.route("/admin/api/logout") def logout(): if "admin" not in session: return jsonify(**{ "error": "Not logged in" }) session.pop("admin", None) return ("", 204) @application.route("/admin/api/logged_in") def logged_in(): if "admin" in session: return jsonify(**{ "auth": True }) return jsonify(**{ "auth": False })
{ "repo_name": "TumblrCommunity/PowerPortfolio", "path": "portfolio/admin/__init__.py", "copies": "1", "size": "1558", "license": "mit", "hash": -8056974871876427000, "line_mean": 24.9666666667, "line_max": 78, "alpha_frac": 0.5879332478, "autogenerated": false, "ratio": 4.036269430051814, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5124202677851813, "avg_score": null, "num_lines": null }
"""Admin integration for django-watson.""" from __future__ import unicode_literals from django.contrib import admin from django.contrib.admin.views.main import ChangeList from watson.registration import SearchEngine, SearchAdapter admin_search_engine = SearchEngine("admin") class WatsonSearchChangeList(ChangeList): """A change list that takes advantage of django-watson full text search.""" def get_queryset(self, *args, **kwargs): """Creates the query set.""" # Do the basic searching. search_fields = self.search_fields self.search_fields = () try: qs = super(WatsonSearchChangeList, self).get_queryset(*args, **kwargs) finally: self.search_fields = search_fields # Do the full text searching. if self.query.strip(): qs = self.model_admin.search_engine.filter(qs, self.query, ranking=False) return qs class SearchAdmin(admin.ModelAdmin): """ A ModelAdmin subclass that provides full-text search integration. Subclass this admin class and specify a tuple of search_fields for instant integration! """ search_engine = admin_search_engine search_adapter_cls = SearchAdapter @property def search_context_manager(self): """The search context manager used by this SearchAdmin.""" return self.search_engine._search_context_manager def __init__(self, *args, **kwargs): """Initializes the search admin.""" super(SearchAdmin, self).__init__(*args, **kwargs) # Check that the search fields are valid. for search_field in self.search_fields or (): if search_field[0] in ("^", "@", "="): raise ValueError("SearchAdmin does not support search fields prefixed with '^', '=' or '@'") # Register with the search engine. self.register_model_with_watson() # Set up revision contexts on key methods, just in case. self.add_view = self.search_context_manager.update_index()(self.add_view) self.change_view = self.search_context_manager.update_index()(self.change_view) self.delete_view = self.search_context_manager.update_index()(self.delete_view) self.changelist_view = self.search_context_manager.update_index()(self.changelist_view) def register_model_with_watson(self): """Registers this admin class' model with django-watson.""" if not self.search_engine.is_registered(self.model) and self.search_fields: self.search_engine.register( self.model, fields = self.search_fields, adapter_cls = self.search_adapter_cls, get_live_queryset = lambda self_: None, # Ensure complete queryset is used in admin. ) def get_changelist(self, request, **kwargs): """Returns the ChangeList class for use on the changelist page.""" return WatsonSearchChangeList
{ "repo_name": "philippeowagner/django-watson", "path": "src/watson/admin.py", "copies": "5", "size": "2968", "license": "bsd-3-clause", "hash": 5808356286298622000, "line_mean": 37.0512820513, "line_max": 108, "alpha_frac": 0.6519541779, "autogenerated": false, "ratio": 4.186177715091678, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7338131892991678, "avg_score": null, "num_lines": null }
"""Admin integration for django-watson.""" from __future__ import unicode_literals from django.contrib import admin from django.contrib.admin.views.main import ChangeList from watson.search import SearchEngine, SearchAdapter admin_search_engine = SearchEngine("admin") class WatsonSearchChangeList(ChangeList): """A change list that takes advantage of django-watson full text search.""" def get_queryset(self, *args, **kwargs): """Creates the query set.""" # Do the basic searching. search_fields = self.search_fields self.search_fields = () try: qs = super(WatsonSearchChangeList, self).get_queryset(*args, **kwargs) finally: self.search_fields = search_fields # Do the full text searching. if self.query.strip(): qs = self.model_admin.search_engine.filter(qs, self.query, ranking=False) return qs class SearchAdmin(admin.ModelAdmin): """ A ModelAdmin subclass that provides full-text search integration. Subclass this admin class and specify a tuple of search_fields for instant integration! """ search_engine = admin_search_engine search_adapter_cls = SearchAdapter @property def search_context_manager(self): """The search context manager used by this SearchAdmin.""" return self.search_engine._search_context_manager def __init__(self, *args, **kwargs): """Initializes the search admin.""" super(SearchAdmin, self).__init__(*args, **kwargs) # Check that the search fields are valid. for search_field in self.search_fields or (): if search_field[0] in ("^", "@", "="): raise ValueError("SearchAdmin does not support search fields prefixed with '^', '=' or '@'") # Register with the search engine. self.register_model_with_watson() # Set up revision contexts on key methods, just in case. self.add_view = self.search_context_manager.update_index()(self.add_view) self.change_view = self.search_context_manager.update_index()(self.change_view) self.delete_view = self.search_context_manager.update_index()(self.delete_view) self.changelist_view = self.search_context_manager.update_index()(self.changelist_view) def register_model_with_watson(self): """Registers this admin class' model with django-watson.""" if not self.search_engine.is_registered(self.model) and self.search_fields: self.search_engine.register( self.model, fields = self.search_fields, adapter_cls = self.search_adapter_cls, get_live_queryset = lambda self_: None, # Ensure complete queryset is used in admin. ) def get_changelist(self, request, **kwargs): """Returns the ChangeList class for use on the changelist page.""" return WatsonSearchChangeList
{ "repo_name": "erikng/sal", "path": "watson/admin.py", "copies": "3", "size": "2962", "license": "apache-2.0", "hash": -4875847890716812000, "line_mean": 36.9743589744, "line_max": 108, "alpha_frac": 0.651249156, "autogenerated": false, "ratio": 4.1777150916784205, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.632896424767842, "avg_score": null, "num_lines": null }