Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
class List(SmartListView):
fields = ('title', 'tags', 'created_on', 'created_by')
search_fields = ('title__icontains', 'body__icontains')
default_order = 'title'
def as_json(self, context):
items = []
for obj in self.object_list:
items.append(dict(title=obj.title,
body=obj.body,
tags=obj.tags))
return items
class ListNoPagination(SmartListView):
fields = ('title', 'tags', 'created_on', 'created_by')
search_fields = ('title__icontains', 'body__icontains')
default_order = 'title'
paginate_by = None
def as_json(self, context):
items = []
for obj in self.object_list:
items.append(dict(title=obj.title,
body=obj.body,
tags=obj.tags))
return items
class Author(SmartListView):
class Exclude(SmartUpdateView):
exclude = ('tags',)
class Exclude2(SmartUpdateView):
form_class = ExcludeForm
exclude = ('tags',)
class Readonly(SmartUpdateView):
readonly = ('tags',)
class Readonly2(SmartUpdateView):
form_class = ExcludeForm
readonly = ('tags',)
class Messages(SmartListView):
def pre_process(self, request, *args, **kwargs):
messages.error(request, "Error Messages")
messages.success(request, "Success Messages")
messages.info(request, "Info Messages")
messages.warning(request, "Warning Messages")
messages.debug(request, "Debug Messages")
class ByUuid(SmartReadView):
slug_url_kwarg = 'uuid'
class Refresh(SmartReadView):
permission = None
def derive_refresh(self):
return 123
cancel_url = "@profiles.user_list"
def has_permission(self, request, *args, **kwargs):
user = self.get_object()
return request.user.can_edit(request.org, user) and request.user != user
def get_queryset(self):
return self.request.org.get_users()
def post(self, request, *args, **kwargs):
user = self.get_object()
user.remove_from_org(request.org)
return HttpResponse(status=204)
class List(OrgPermsMixin, SmartListView):
"""
JSON endpoint to fetch users with their activity information
"""
permission = "profiles.profile_user_list"
def get(self, request, *args, **kwargs):
org = request.org
partner_id = request.GET.get("partner")
non_partner = str_to_bool(self.request.GET.get("non_partner", ""))
with_activity = str_to_bool(self.request.GET.get("with_activity", ""))
if non_partner:
users = org.administrators.all()
elif partner_id:
users = Partner.objects.get(org=org, pk=partner_id).get_users()
class CommentCRUDL(SmartCRUDL):
title = "Comments"
actions = ("list", "pinned", "pin", "unpin")
model = MessageBoardComment
class List(OrgPermsMixin, SmartListView):
permission = "msg_board.messageboardcomment_list"
def get_queryset(self):
return MessageBoardComment.get_all(self.request.org).order_by("-submit_date")
def get(self, request, *args, **kwargs):
return JsonResponse({"results": [c.as_json() for c in self.get_queryset()]}, encoder=JSONEncoder)
class Pinned(OrgPermsMixin, SmartListView):
permission = "msg_board.messageboardcomment_pinned"
def get_queryset(self):
return MessageBoardComment.get_all(self.request.org, pinned=True).order_by("-pinned_on")
def get(self, request, *args, **kwargs):
return JsonResponse({"results": [c.as_json() for c in self.get_queryset()]}, encoder=JSONEncoder)
class Pin(OrgObjPermsMixin, SmartReadView):
"""
Endpoint for creating a Pinned Comment
"""
permission = "msg_board.messageboardcomment_pin"
fields = ["comment", "pinned_on"]
http_method_names = ["post"]
header = []
for field in fields:
header.append(str(self.lookup_field_label(dict(), field)))
writer.writerow([s.encode("utf-8") for s in header])
# then our actual values
for obj in self.object_list:
row = []
for field in fields:
row.append(str(self.lookup_field_value(dict(), obj, field)))
writer.writerow([s.encode("utf-8") for s in row])
return response
class SmartXlsView(SmartListView):
def derive_filename(self):
filename = getattr(self, 'filename', None)
if not filename:
filename = "%s.xls" % self.model._meta.verbose_name.lower()
return filename
def render_to_response(self, context, **response_kwargs):
from xlwt import Workbook
book = Workbook()
sheet1 = book.add_sheet(self.derive_title())
fields = self.derive_fields()
# build up our header row
for col in range(len(fields)):
def derive_search(self):
"""
Collects and prepares FAQ search parameters into JSON serializable dict
"""
label = self.request.GET.get("label", None)
text = self.request.GET.get("text", None)
language = self.request.GET.get("language", None)
return {"label": label, "text": text, "language": language}
class FaqCRUDL(SmartCRUDL):
model = FAQ
actions = ("list", "create", "read", "update", "delete", "search", "import", "languages")
class List(OrgPermsMixin, SmartListView):
fields = ("question", "answer", "language", "parent")
default_order = ("-parent", "question")
def derive_queryset(self, **kwargs):
return FAQ.get_all(self.request.org)
class Create(OrgPermsMixin, SmartCreateView):
form_class = FaqForm
def get_form_kwargs(self):
kwargs = super(FaqCRUDL.Create, self).get_form_kwargs()
# Get the data for post requests that didn't come through a form
if self.request.method == "POST" and not self.request.POST and hasattr(self.request, "json"):
kwargs["data"] = self.request.json
kwargs["org"] = self.request.org
return kwargs
def get_summary(self, partner):
return {
"total_replies": DailyCount.get_by_partner([partner], DailyCount.TYPE_REPLIES).total(),
"cases_open": Case.objects.filter(org=partner.org, assignee=partner, closed_on=None).count(),
"cases_closed": Case.objects.filter(org=partner.org, assignee=partner).exclude(closed_on=None).count(),
}
class Delete(OrgObjPermsMixin, SmartDeleteView):
cancel_url = "@cases.partner_list"
def post(self, request, *args, **kwargs):
partner = self.get_object()
partner.release()
return HttpResponse(status=204)
class List(OrgPermsMixin, SmartListView):
paginate_by = None
def get_queryset(self, **kwargs):
return Partner.get_all(self.request.org).order_by("name")
def render_to_response(self, context, **response_kwargs):
if self.request.is_ajax():
with_activity = str_to_bool(self.request.GET.get("with_activity", ""))
return self.render_as_json(context["object_list"], with_activity)
else:
return super(PartnerCRUDL.List, self).render_to_response(context, **response_kwargs)
def render_as_json(self, partners, with_activity):
if with_activity:
# get reply statistics
replies_total = DailyCount.get_by_partner(partners, DailyCount.TYPE_REPLIES, None, None).scope_totals()
def form_valid(self, form):
selected_ids = form.cleaned_data["groups"]
org_groups = Group.objects.filter(org=self.request.org)
org_groups.filter(pk__in=selected_ids).update(is_visible=True)
org_groups.exclude(pk__in=selected_ids).update(is_visible=False)
return HttpResponseRedirect(self.get_success_url())
class FieldCRUDL(SmartCRUDL):
model = Field
actions = ("list",)
class List(OrgPermsMixin, SmartListView):
"""
Basic list view mostly for debugging
"""
fields = ("key", "label", "value_type", "is_visible")
default_order = "key"
def get_queryset(self, **kwargs):
queryset = super(FieldCRUDL.List, self).get_queryset(**kwargs)
return queryset.filter(org=self.request.org)
# angular app requires context data in JSON format
context["context_data_json"] = {"label": label_json}
context["rule_tests"] = self.object.rule.get_tests_description() if self.object.rule else ""
return context
class Delete(OrgObjPermsMixin, SmartDeleteView):
cancel_url = "@msgs.label_list"
def post(self, request, *args, **kwargs):
label = self.get_object()
label.release()
return HttpResponse(status=204)
class List(OrgPermsMixin, SmartListView):
def get(self, request, *args, **kwargs):
with_activity = str_to_bool(self.request.GET.get("with_activity", ""))
labels = list(Label.get_all(self.request.org, self.request.user).order_by("name"))
Label.bulk_cache_initialize(labels)
if with_activity:
# get message statistics
this_month = DailyCount.get_by_label(labels, DailyCount.TYPE_INCOMING, *month_range(0)).scope_totals()
last_month = DailyCount.get_by_label(labels, DailyCount.TYPE_INCOMING, *month_range(-1)).scope_totals()
def as_json(label):
obj = label.as_json()
if with_activity:
obj["activity"] = {"this_month": this_month.get(label, 0), "last_month": last_month.get(label, 0)}
return obj
if not result:
result = dict(id=obj.pk, text="%s" % obj)
results.append(result)
has_more = context['page_obj'].has_next() if context['page_obj'] else False
json_data = dict(results=results, err='nil', more=has_more)
return JsonResponse(json_data)
# otherwise, return normally
else:
return super(SmartListView, self).render_to_response(context)
class SmartCsvView(SmartListView):
def derive_filename(self):
filename = getattr(self, 'filename', None)
if not filename:
filename = "%s.csv" % self.model._meta.verbose_name.lower()
return filename
def render_to_response(self, context, **response_kwargs):
import csv
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv; charset=utf-8')
response['Content-Disposition'] = 'attachment; filename=%s' % self.derive_filename()
writer = csv.writer(response, quoting=csv.QUOTE_ALL)