def save(self, *args, **kwargs): if self.order is None: self.order = self.form.fields.count() if not self.slug: slug = slugify(self).replace('-', '_') self.slug = unique_slug(self.form.fields, "slug", slug) super(Field, self).save(*args, **kwargs)
def callback_field(sender, instance, *args, **kwargs): if not instance.slug or len(instance.slug) == len(instance.label): slug = slugify(get_translation(instance.label)) instance.slug = unique_slug(instance.__class__.objects, "slug", slug) if not instance.order: max_order = max(instance.form.fields.aggregate(Max('order')).values() + instance.form.labels.aggregate(Max('order')).values()) instance.order = max_order or 0 + 1
def save(self, *args, **kwargs): """ Create a unique slug from title - append an index and increment if it already exists. """ if not self.slug: slug = slugify(self) self.slug = unique_slug(self.__class__.objects, "slug", slug) super(AbstractForm, self).save(*args, **kwargs)
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 save(self, *args, **kwargs): """ Create a unique slug from title - append an index and increment if it already exists. """ if not self.slug: self.slug = slugify(self.title) i = 0 while True: if i > 0: if i > 1: self.slug = self.slug.rsplit("-", 1)[0] self.slug = "%s-%s" % (self.slug, i) if not self.__class__.objects.filter(slug=self.slug): break i += 1 super(AbstractForm, self).save(*args, **kwargs)
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 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 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: filename = join( "forms", "%s_%s" % (self.form.id, self.form.slug), "%s_%s" % (entry.id, slugify(os.path.splitext(value.name)[0]) + os.path.splitext(value.name)[1])) value = fs.save(filename, 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 save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.label).replace('-', '_') return super(AbstractField, self).save(*args, **kwargs)
def save(self, *args, **kwargs): if not self.slug: slug = slugify(self).replace('-', '_') self.slug = unique_slug(self.form.fields, "slug", slug) return super(AbstractField, self).save(*args, **kwargs)
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 callback_form(sender, instance, *args, **kwargs): if not instance.slug or len(instance.slug) == len(instance.title): slug = slugify(get_translation(instance.title)) instance.slug = unique_slug(instance.__class__.objects, "slug", slug)
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)