def published(self, for_user=None): if for_user is not None and for_user.is_staff: return self.all() filters = [ Q(publish_date__lte=now()) | Q(publish_date__isnull=True), Q(expiry_date__gte=now()) | Q(expiry_date__isnull=True), Q(status=STATUS_PUBLISHED), ] if settings.USE_SITES: filters.append(Q(sites=Site.objects.get_current())) return self.filter(*filters)
def published(self, for_user=None): """ Mimics the queryset logic in ``FormManager.published``, so we can check a form is published when it wasn't loaded via the queryset's ``published`` method, and is passed to the ``render_built_form`` template tag. """ if for_user is not None and for_user.is_staff: return True status = self.status == STATUS_PUBLISHED publish_date = self.publish_date is None or self.publish_date <= now() expiry_date = self.expiry_date is None or self.expiry_date >= now() return status and publish_date and expiry_date
def published(self, for_user=None, for_object=None, editor_check=None): if for_user is not None and for_object is not None and editor_check is not None\ and editor_check(for_user, for_object): # User has permissions to edit forms return self.filter(content_type=ContentType.objects.get_for_model(for_object.__class__), object_id=for_object.id) # Return all forms related to the passed object filters = [ Q(publish_date__lte=now()) | Q(publish_date__isnull=True), Q(expiry_date__gte=now()) | Q(expiry_date__isnull=True), Q(status=STATUS_PUBLISHED), # Q(content_type="", object_id=""), # TODO ] if settings.USE_SITES: filters.append(Q(sites=Site.objects.get_current())) return self.filter(*filters)
def save(self, **kwargs): """ Get/create a FormEntry instance and assign submitted values to related FieldEntry instances for each form field. """ entry = super(FormForForm, self).save(commit=False) entry.form = self.form entry.entry_time = now() entry.save() entry_fields = entry.fields.values_list("field_id", flat=True) new_entry_fields = [] for field in self.form_fields: field_key = field.slug value = self.cleaned_data[field_key] if value and self.fields[field_key].widget.needs_multipart_form: value = fs.save(join("forms", str(uuid4()), value.name), value) if isinstance(value, list): value = ", ".join([v.strip() for v in value]) if field.id in entry_fields: field_entry = entry.fields.get(field_id=field.id) field_entry.value = value field_entry.save() else: new = {"entry": entry, "field_id": field.id, "value": value} new_entry_fields.append(self.field_entry_model(**new)) if new_entry_fields: if django.VERSION >= (1, 4, 0): self.field_entry_model.objects.bulk_create(new_entry_fields) else: for field_entry in new_entry_fields: field_entry.save() return entry
def published(self, for_user=None): """ Mimics the queryset logic in ``FormManager.published``, so we can check a form is published when it wasn't loaded via the queryset's ``published`` method, and is passed to the ``render_built_form`` template tag. """ if for_user is not None and for_user.is_staff: return True status = self.status == STATUS_PUBLISHED publish_date = self.publish_date is None or self.publish_date <= now() expiry_date = self.expiry_date is None or self.expiry_date >= now() authenticated = for_user is not None and for_user.is_authenticated if DJANGO_VERSION <= (1, 9): # Django 1.8 compatibility, is_authenticated has to be called as a method. authenticated = for_user is not None and for_user.is_authenticated() login_required = (not self.login_required or authenticated) return status and publish_date and expiry_date and login_required
def entries_view(self, request, form_id, show=False, export=False): """ Displays the form entries in a HTML table with option to export as CSV file. """ if request.POST.get("back"): change_url = reverse("admin:%s_%s_change" % (Form._meta.app_label, Form.__name__.lower()), args=(form_id,)) return HttpResponseRedirect(change_url) form = get_object_or_404(Form, id=form_id) entries_form = EntriesForm(form, request, request.POST or None) delete_entries_perm = "%s.delete_formentry" % FormEntry._meta.app_label can_delete_entries = request.user.has_perm(delete_entries_perm) submitted = entries_form.is_valid() or show or export export = export or request.POST.get("export") if submitted: if export: response = HttpResponse(mimetype="text/csv") fname = "%s-%s.csv" % (form.slug, slugify(now().ctime())) response["Content-Disposition"] = "attachment; filename=%s" % fname queue = StringIO() csv = writer(queue, delimiter=CSV_DELIMITER) csv.writerow(entries_form.columns()) for row in entries_form.rows(csv=True): csv.writerow(row) # Decode and reencode entire queued response into utf-16 to be Excel compatible data = queue.getvalue().decode("utf-8").encode("utf-16") response.write(data) return response elif request.POST.get("delete") and can_delete_entries: selected = request.POST.getlist("selected") if selected: try: from django.contrib.messages import info except ImportError: def info(request, message, fail_silently=True): request.user.message_set.create(message=message) entries = FormEntry.objects.filter(id__in=selected) count = entries.count() if count > 0: entries.delete() message = ungettext("1 entry deleted", "%(count)s entries deleted", count) info(request, message % {"count": count}) template = "admin/forms/entries.html" context = {"title": _("View Entries"), "entries_form": entries_form, "opts": self.model._meta, "original": form, "can_delete_entries": can_delete_entries, "submitted": submitted} return render_to_response(template, context, RequestContext(request))
def form_valid(self, form): try: show_hidden_fields = form.cleaned_data['show_hidden'] except Exception as e: show_hidden = False try: indicator = form.cleaned_data['indicator'] columns = indicator.get_column_headers(show_hidden=show_hidden) except Exception as e: indicator = None if form.cleaned_data['export'] == True: response = HttpResponse(mimetype="application/vnd.ms-excel") fname = "%s-%s.xls" % ("QI Data Export", slugify(now().ctime())) attachment = "attachment; filename=%s" % fname response["Content-Disposition"] = attachment queue = BytesIO() workbook = xlwt.Workbook(encoding='utf8') if indicator == None: for i in cm.Indicator.objects.all().order_by("form_number"): columns = i.get_column_headers(show_hidden=show_hidden) workbook = self.add_indicator_to_workbook( i, workbook, columns, form.cleaned_data) else: workbook = self.add_indicator_to_workbook( indicator, workbook, columns, form.cleaned_data) workbook.save(queue) data = queue.getvalue() response.write(data) return response else: context = { "columns": columns, "entries": indicator.get_filtered_entries(form.cleaned_data, csv=False, show_hidden=show_hidden), "available_verbs": self.noun.get_available_verbs(self.request.user), "filter": form.cleaned_data } return render_to_response('indicator/entries.html', context, context_instance=RequestContext( self.request))
def form_valid(self, form): try: show_hidden_fields = form.cleaned_data['show_hidden'] except Exception as e: show_hidden = False try: indicator = form.cleaned_data['indicator'] columns = indicator.get_column_headers(show_hidden=show_hidden) except Exception as e: indicator = None if form.cleaned_data['export']==True: response = HttpResponse(mimetype="application/vnd.ms-excel") fname = "%s-%s.xls" % ("QI Data Export", slugify(now().ctime())) attachment = "attachment; filename=%s" % fname response["Content-Disposition"] = attachment queue = BytesIO() workbook = xlwt.Workbook(encoding='utf8') if indicator == None: for i in cm.Indicator.objects.all().order_by("form_number"): columns = i.get_column_headers(show_hidden=show_hidden) workbook = self.add_indicator_to_workbook(i, workbook, columns, form.cleaned_data) else: workbook = self.add_indicator_to_workbook(indicator, workbook, columns, form.cleaned_data) workbook.save(queue) data = queue.getvalue() response.write(data) return response else: context = { "columns":columns, "entries":indicator.get_filtered_entries(form.cleaned_data,csv=False, show_hidden=show_hidden), "available_verbs": self.noun.get_available_verbs(self.request.user), "filter":form.cleaned_data } return render_to_response('indicator/entries.html', context, context_instance=RequestContext(self.request))
def save(self, **kwargs): """ Get/create a FormEntry instance and assign submitted values to related FieldEntry instances for each form field. """ entry = super(FormForForm, self).save(commit=False) entry.form = self.form entry.entry_time = now() entry.user = self.user entry.track = self.track entry.save() entry_fields = entry.fields.values_list("field_id", flat=True) new_entry_fields = [] for field in self.form_fields: field_key = field.slug value = self.cleaned_data[field_key] if value and self.fields[field_key].widget.needs_multipart_form: value = fs.save(join("forms", str(uuid4()), value.name), value) #matrix_rows and matrix_cols will be non-zero if user created a form which contained the Matrix as one of its fields. elif isinstance(value, list) and not ( field.matrix_rows and field.matrix_cols and field.matrix_rows > 0 and field.matrix_cols > 0): value = ", ".join([v.strip() for v in value]) if field.id in entry_fields: field_entry = entry.fields.get(field_id=field.id) field_entry.value = value field_entry.save() else: new = {"entry": entry, "field_id": field.id, "value": value} new_entry_fields.append(self.field_entry_model(**new)) if new_entry_fields: if django.VERSION >= (1, 4, 0): self.field_entry_model.objects.bulk_create(new_entry_fields) else: for field_entry in new_entry_fields: field_entry.save() self.update_application_status() return entry
def get(self, request, formid): export = True if request.user.is_authenticated(): form = get_object_or_404(Form, id=formid) if form.user.id == request.user.id: post = request.POST or None args = form, request, FormEntry, FieldEntry, post entries_form = EntriesForm(*args) submitted = entries_form.is_valid() or export if submitted: response = HttpResponse(content_type="text/csv") fname = "%s-%s.csv" % (form.slug, slugify(now().ctime())) attachment = "attachment; filename=%s" % fname response["Content-Disposition"] = attachment queue = StringIO() try: csv = writer(queue, delimiter=CSV_DELIMITER) writerow = csv.writerow except TypeError: queue = BytesIO() delimiter = bytes(CSV_DELIMITER, encoding="utf-8") csv = writer(queue, delimiter=delimiter) writerow = lambda row: csv.writerow([c.encode("utf-8") if hasattr(c, "encode") else c for c in row]) writerow(entries_form.columns()) for row in entries_form.rows(csv=True): writerow(row) data = queue.getvalue() response.write(data) return response else: return HttpResponse(status=204) else: return HttpResponse(status=204) else: return HttpResponse(status=204)
def entries_view(request, form_id, show=False, export=False, export_xls=False, content_type=None, object_id=None, entries_perm_check=lambda user, object: True, submitter_fields=('user.username', ), entries_template="forms/form_entries.html", **kwargs): """ Displays the form entries. """ model = Form template = entries_template formentry_model = FormEntry fieldentry_model = FieldEntry if request.POST.get("back"): #bits = (model._meta.app_label, model.__name__.lower()) change_url = reverse("forms:edit_form", current_app=request.resolver_match.namespace, kwargs={ "object_id": object_id, "form_id": form_id }) return HttpResponseRedirect(change_url) object = get_object_or_404( content_type.model_class(), id=object_id) if content_type is not None else None perm_check = entries_perm_check if perm_check(request.user, object) is False: raise PermissionDenied form = get_object_or_404(Form, content_type=content_type, object_id=object_id, id=form_id) post = request.POST or None args = form, request, formentry_model, fieldentry_model, post kw = {"submitter_fields": submitter_fields} entries_form = EntriesForm(*args, **kw) delete = "%s.delete_formentry" % formentry_model._meta.app_label can_delete_entries = request.user.has_perm(delete) or perm_check( request.user, object) submitted = entries_form.is_valid() or show or export or export_xls export = export or request.POST.get("export") export_xls = export_xls or request.POST.get("export_xls") if submitted: if export: response = HttpResponse(content_type="text/csv; charset=utf-8") fname = "%s-%s.csv" % (form.slug, slugify(now().ctime())) attachment = "attachment; filename=%s" % fname response["Content-Disposition"] = attachment queue = StringIO() try: csv = writer(queue, delimiter=CSV_DELIMITER) writerow = csv.writerow except TypeError: queue = BytesIO() delimiter = bytes(CSV_DELIMITER, encoding="utf-8") csv = writer(queue, delimiter=delimiter) writerow = lambda row: csv.writerow([ c.encode("utf-8") if hasattr(c, "encode") else c for c in row ]) writerow(entries_form.columns()) for row in entries_form.rows(csv=True): writerow(row) data = queue.getvalue() response.write(data) return response elif XLWT_INSTALLED and export_xls: response = HttpResponse( content_type="application/vnd.ms-excel; charset=utf-8") fname = "%s-%s.xls" % (form.slug, slugify(now().ctime())) attachment = "attachment; filename=%s" % fname response["Content-Disposition"] = attachment queue = BytesIO() workbook = xlwt.Workbook(encoding='utf8') sheet = workbook.add_sheet(form.title[:31]) for c, col in enumerate(entries_form.columns()): sheet.write(0, c, col) for r, row in enumerate(entries_form.rows(csv=True)): for c, item in enumerate(row): if isinstance(item, datetime): item = item.replace(tzinfo=None) sheet.write(r + 2, c, item, XLWT_DATETIME_STYLE) else: sheet.write(r + 2, c, item) workbook.save(queue) data = queue.getvalue() response.write(data) return response elif request.POST.get("delete") and can_delete_entries: selected = request.POST.getlist("selected") if selected: try: from django.contrib.messages import info except ImportError: def info(request, message, fail_silently=True): request.user.message_set.create(message=message) entries = formentry_model.objects.filter(id__in=selected) count = entries.count() if count > 0: entries.delete() message = ungettext("1 entry deleted", "%(count)s entries deleted", count) info(request, message % {"count": count}) context = { "title": _("View Entries"), "entries_form": entries_form, "opts": model._meta, "original": form, "can_delete_entries": can_delete_entries, "submitted": submitted, "xlwt_installed": XLWT_INSTALLED, "object_id": object_id } context[kwargs.pop("object_context_name", "object")] = object context.update(kwargs.pop("custom_context", {})) return render_to_response( template, context, RequestContext(request, current_app=request.resolver_match.namespace))
def entries_view(self, request, form_id, show=False, export=False, export_xls=False): """ Displays the form entries in a HTML table with option to export as CSV file. """ if request.POST.get("back"): bits = (self.model._meta.app_label, self.model.__name__.lower()) change_url = reverse("admin:%s_%s_change" % bits, args=(form_id,)) return HttpResponseRedirect(change_url) form = get_object_or_404(self.model, id=form_id) post = request.POST or None args = form, request, self.formentry_model, self.fieldentry_model, post entries_form = EntriesForm(*args) delete = "%s.delete_formentry" % self.formentry_model._meta.app_label can_delete_entries = request.user.has_perm(delete) submitted = entries_form.is_valid() or show or export or export_xls export = export or request.POST.get("export") export_xls = export_xls or request.POST.get("export_xls") if submitted: if export: response = HttpResponse(mimetype="text/csv") fname = "%s-%s.csv" % (form.slug, slugify(now().ctime())) attachment = "attachment; filename=%s" % fname response["Content-Disposition"] = attachment queue = StringIO() csv = unicodecsv.writer(queue, delimiter=CSV_DELIMITER, encoding='utf-8') csv.writerow(entries_form.columns()) for row in entries_form.rows(csv=True): csv.writerow(row) # Decode and reencode entire queued response # into utf-16 to be Excel compatible data = queue.getvalue().decode("utf-8").encode("utf-16") response.write(data) return response elif XLWT_INSTALLED and export_xls: response = HttpResponse(mimetype="application/vnd.ms-excel") fname = "%s-%s.xls" % (form.slug, slugify(now().ctime())) attachment = "attachment; filename=%s" % fname response["Content-Disposition"] = attachment queue = StringIO() workbook = xlwt.Workbook(encoding='utf8') sheet = workbook.add_sheet(form.title[:31]) for c, col in enumerate(entries_form.columns()): sheet.write(0, c, col) for r, row in enumerate(entries_form.rows(csv=True)): for c, item in enumerate(row): if isinstance(item, datetime): item = item.replace(tzinfo=None) sheet.write(r + 2, c, item, XLWT_DATETIME_STYLE) else: sheet.write(r + 2, c, item) workbook.save(queue) data = queue.getvalue() response.write(data) return response elif request.POST.get("delete") and can_delete_entries: selected = request.POST.getlist("selected") if selected: try: from django.contrib.messages import info except ImportError: def info(request, message, fail_silently=True): request.user.message_set.create(message=message) entries = FormEntry.objects.filter(id__in=selected) count = entries.count() if count > 0: entries.delete() message = ungettext("1 entry deleted", "%(count)s entries deleted", count) info(request, message % {"count": count}) template = "admin/forms/entries.html" context = {"title": _("View Entries"), "entries_form": entries_form, "opts": self.model._meta, "original": form, "can_delete_entries": can_delete_entries, "submitted": submitted, "xlwt_installed": XLWT_INSTALLED} return render_to_response(template, context, RequestContext(request))
def entries_view(self, request, form_id, show=False, export=False, export_xls=False): """ Displays the form entries in a HTML table with option to export as CSV file. """ if request.POST.get("back"): bits = (self.model._meta.app_label, self.model.__name__.lower()) change_url = reverse("admin:%s_%s_change" % bits, args=(form_id, )) return HttpResponseRedirect(change_url) form = get_object_or_404(self.model, id=form_id) post = request.POST or None args = form, request, self.formentry_model, self.fieldentry_model, post entries_form = EntriesForm(*args) delete = "%s.delete_formentry" % self.formentry_model._meta.app_label can_delete_entries = request.user.has_perm(delete) submitted = entries_form.is_valid() or show or export or export_xls export = export or request.POST.get("export") export_xls = export_xls or request.POST.get("export_xls") if submitted: if export: response = HttpResponse(content_type="text/csv") fname = "%s-%s.csv" % (form.slug, slugify(now().ctime())) attachment = "attachment; filename=%s" % fname response["Content-Disposition"] = attachment queue = StringIO() try: csv = writer(queue, delimiter=CSV_DELIMITER) writerow = csv.writerow except TypeError: queue = BytesIO() delimiter = bytes(CSV_DELIMITER, encoding="utf-8") csv = writer(queue, delimiter=delimiter) writerow = lambda row: csv.writerow([ c.encode("utf-8") if hasattr(c, "encode") else c for c in row ]) writerow(entries_form.columns()) for row in entries_form.rows(csv=True): writerow(row) data = queue.getvalue() response.write(data) return response elif XLWT_INSTALLED and export_xls: response = HttpResponse( content_type="application/vnd.ms-excel") fname = "%s-%s.xls" % (form.slug, slugify(now().ctime())) attachment = "attachment; filename=%s" % fname response["Content-Disposition"] = attachment queue = BytesIO() workbook = xlwt.Workbook(encoding='utf8') sheet = workbook.add_sheet(form.title[:31]) for c, col in enumerate(entries_form.columns()): sheet.write(0, c, col) for r, row in enumerate(entries_form.rows(csv=True)): for c, item in enumerate(row): if isinstance(item, datetime): item = item.replace(tzinfo=None) sheet.write(r + 2, c, item, XLWT_DATETIME_STYLE) else: sheet.write(r + 2, c, item) workbook.save(queue) data = queue.getvalue() response.write(data) return response elif request.POST.get("delete") and can_delete_entries: selected = request.POST.getlist("selected") if selected: try: from django.contrib.messages import info except ImportError: def info(request, message, fail_silently=True): request.user.message_set.create(message=message) entries = self.formentry_model.objects.filter( id__in=selected) count = entries.count() if count > 0: entries.delete() message = ungettext("1 entry deleted", "%(count)s entries deleted", count) info(request, message % {"count": count}) template = "admin/forms/entries.html" context = { "title": _("View Entries"), "entries_form": entries_form, "opts": self.model._meta, "original": form, "can_delete_entries": can_delete_entries, "submitted": submitted, "xlwt_installed": XLWT_INSTALLED } return render(request, template, context)