Ejemplo n.º 1
0
 def post(self, request, *args, **kwargs):
     published = Form.objects.published(for_user=request.user)
     form = get_object_or_404(published, slug=kwargs["slug"])
     form_for_form = FormForForm(
         form,
         RequestContext(request),
         request.POST or None,
         request.FILES or None,
         user=request.user or None,
         track=Track.objects.get(id=request.GET.get("track_id")) or None)
     form_contains_errors = None
     if not form_for_form.is_valid():
         form_contains_errors = True
         form_invalid.send(sender=request, form=form_for_form)
     else:
         # Attachments read must occur before model save,
         # or seek() will fail on large uploads.
         attachments = []
         for f in form_for_form.files.values():
             f.seek(0)
             attachments.append((f.name, f.read()))
         entry = form_for_form.save()
         form_valid.send(sender=request, form=form_for_form, entry=entry)
         self.send_emails(request, form_for_form, form, entry, attachments)
         if not self.request.is_ajax():
             return redirect("form_sent", slug=form.slug)
     context = {
         "form": form,
         "form_for_form": form_for_form,
         "form_contains_errors": form_contains_errors
     }
     return self.render_to_response(context)
Ejemplo n.º 2
0
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)
    if form.login_required and not request.user.is_authenticated():
        return redirect("%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                                      urlquote(request.get_full_path())))
    request_context = RequestContext(request)
    args = (form, request_context, request.POST or None, request.FILES or None)
    form_for_form = FormForForm(*args)
    if request.method == "POST":
        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
        else:
            entry = form_for_form.save()
            subject = form.email_subject
            if not subject:
                subject = "%s - %s" % (form.title, entry.entry_time)
            fields = []
            for (k, v) in form_for_form.fields.items():
                value = form_for_form.cleaned_data[k]
                if isinstance(value, list):
                    value = ", ".join([i.strip() for i in value])
                fields.append((v.label, value))
            context = {
                "fields": fields,
                "message": form.email_message,
                "request": request,
            }
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            if email_to and form.send_email:
                send_mail_template(subject,
                                   "form_response",
                                   email_from,
                                   email_to,
                                   context=context,
                                   fail_silently=settings.DEBUG)
            email_copies = split_choices(form.email_copies)
            if email_copies:
                if email_to and SEND_FROM_SUBMITTER:
                    # Send from the email entered.
                    email_from = email_to
                attachments = []
                for f in form_for_form.files.values():
                    f.seek(0)
                    attachments.append((f.name, f.read()))
                send_mail_template(subject,
                                   "form_response",
                                   email_from,
                                   email_copies,
                                   context=context,
                                   attachments=attachments,
                                   fail_silently=settings.DEBUG)
            form_valid.send(sender=request, form=form_for_form, entry=entry)
            return redirect(reverse("form_sent", kwargs={"slug": form.slug}))
    context = {"form": form}
    return render_to_response(template, context, request_context)
Ejemplo n.º 3
0
    def post(self, request, slug):
        published = Form.objects.published(for_user=request.user)
        form = get_object_or_404(published, slug=slug)

        if not form.is_user_permitted(request.user, 'submit'):
            raise Http404

        request_context = RequestContext(request)
        args = (form, request_context, request.POST or None, request.FILES or None)
        form_for_form = FormForForm(*args)

        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
        else:
            try:
                entry = form_for_form.save(user=request.user)
            except IntegrityError:
                err = "You have already voted for this"
                request.session['form_submitted'] = True
                request.session['form_error'] = err
                return redirect(reverse("form_error", kwargs={"slug": form.slug}))
            except:
                raise

            form_valid.send(sender=request, form=form_for_form, entry=entry)
            request.session['form_submitted'] = True;
            return redirect(reverse("form_success", kwargs={"slug": form.slug}))

        context = self.get_context_data(form=form, can_submit=form.is_user_permitted(request.user, 'submit'))
        return self.render_to_response(context)
Ejemplo n.º 4
0
 def post(self, request, *args, **kwargs):
     published = Form.objects.published(for_user=request.user)
     form = get_object_or_404(published, slug=kwargs["slug"])
     form_for_form = FormForForm(form, RequestContext(request),
                                 request.POST or None,
                                 request.FILES or None,
                                 user=request.user or None,
                                 track=Track.objects.get(id=request.GET.get("track_id")) or None)
     form_contains_errors = None
     if not form_for_form.is_valid():
         form_contains_errors = True
         form_invalid.send(sender=request, form=form_for_form)
     else:
         # Attachments read must occur before model save,
         # or seek() will fail on large uploads.
         attachments = []
         for f in form_for_form.files.values():
             f.seek(0)
             attachments.append((f.name, f.read()))
         entry = form_for_form.save()
         form_valid.send(sender=request, form=form_for_form, entry=entry)
         self.send_emails(request, form_for_form, form, entry, attachments)
         if not self.request.is_ajax():
             return redirect("form_sent", slug=form.slug)
     context = {"form": form, "form_for_form": form_for_form, "form_contains_errors": form_contains_errors}
     return self.render_to_response(context)
Ejemplo n.º 5
0
 def __call__(self, request, slug, template="forms/form_detail.html"):
     """
     Display a built form and handle submission.
     """
     published = Form.objects.published(for_user=request.user)
     form = get_object_or_404(published, slug=slug)
     if form.login_required and not request.user.is_authenticated():
         return redirect("%s?%s=%s" % (
             settings.LOGIN_URL,
             REDIRECT_FIELD_NAME,
             urlquote(request.get_full_path())
         ))
     request_context = RequestContext(request)
     args = (
         form, request_context,
         request.POST or None,
         request.FILES or None
     )
     form_for_form = FormForForm(*args)
     if request.method == "POST":
         if not form_for_form.is_valid():
             form_invalid.send(sender=request, form=form_for_form)
         else:
             entry = form_for_form.save()
             self.email(request, form, form_for_form, entry)
             form_valid.send(
                 sender=request,
                 form=form_for_form,
                 entry=entry
             )
             return redirect(reverse("form_sent", kwargs={
                 "slug": form.slug
             }))
     context = {"form": form}
     return render_to_response(template, context, request_context)
Ejemplo n.º 6
0
 def process_form(self, request):
     if self.bound_form:
         return self.entry
     from .forms import FormForForm
     self.bound_form = FormForForm(self, request.POST, request.FILES)
     if not self.bound_form.is_valid():
         form_invalid.send(sender=request, form=self.bound_form)
         return None
     self.entry = self.bound_form.save()
     fields = ["%s: %s" % (v.label, self.bound_form.cleaned_data[k])
         for (k, v) in self.bound_form.fields.items()]
     subject = self.email_subject
     if not subject:
         subject = "%s - %s" % (self.title, self.entry.entry_time)
     body = "\n".join(fields)
     if self.email_message:
         body = "%s\n\n%s" % (self.email_message, body)
     email_from = self.email_from or settings.DEFAULT_FROM_EMAIL
     email_to = self.bound_form.email_to()
     if email_to and self.send_email:
         msg = EmailMessage(subject, body, email_from, [email_to])
         msg.send()
     email_from = email_to or email_from # Send from the email entered.
     email_copies = [e.strip() for e in self.email_copies.split(",")
         if e.strip()]
     if email_copies:
         msg = EmailMessage(subject, body, email_from, email_copies)
         for f in self.bound_form.files.values():
             f.seek(0)
             msg.attach(f.name, f.read())
         msg.send()
     form_valid.send(sender=request, form=self.bound_form, entry=self.entry)
     return self.entry
Ejemplo n.º 7
0
    def render(self, request, instance, **kwargs):
        context = self.get_context(request, instance, **kwargs)

        form = instance.form
        if request.method == 'POST':
            form_for_form = FormForForm(form, Context(context), request.POST,
                                        request.FILES or None)

            if not form_for_form.is_valid():
                form_invalid.send(sender=request, form=form_for_form)
            else:
                attachments = []
                for f in form_for_form.files.values():
                    f.seek(0)
                    attachments.append((f.name, f.read()))

                entry = form_for_form.save()
                form_valid.send(sender=request,
                                form=form_for_form,
                                entry=entry)

                FormDetail().send_emails(request, form_for_form, form, entry,
                                         attachments)

                if not request.is_ajax() and form.redirect_url:
                    return redirect(str(form.redirect_url))

                return self.render_to_string(
                    request, "fluentcms_forms_builder/form_sent.html", context)
        else:
            form_for_form = FormForForm(form, Context(context))

        context.update(form_for_form=form_for_form)

        return self.render_to_string(request, self.render_template, context)
Ejemplo n.º 8
0
 def post(self, request, *args, **kwargs):
     published = Form.objects.published(for_user=request.user)
     form = get_object_or_404(published, slug=kwargs["slug"])
     form_for_form = FormForForm(form, RequestContext(request), request.POST
                                 or None, request.FILES or None)
     if not form_for_form.is_valid():
         form_invalid.send(sender=request, form=form_for_form)
     else:
         # Attachments read must occur before model save,
         # or seek() will fail on large uploads.
         attachments = []
         for f in form_for_form.files.values():
             f.seek(0)
             attachments.append((f.name, f.read(), f.content_type))
         entry = form_for_form.save()
         form_valid.send(sender=request, form=form_for_form, entry=entry)
         self.send_emails(request, form_for_form, form, entry, attachments)
         # XXX: is_ajax() is deprecated since Django 3.1, removed in Django 4.0
         # https://docs.djangoproject.com/en/3.1/releases/3.1/#id2
         if not self.request.is_ajax():
             return redirect(
                 form.redirect_url
                 or reverse("form_sent", kwargs={"slug": form.slug}))
     context = {"form": form, "form_for_form": form_for_form}
     return self.render_to_response(context)
Ejemplo n.º 9
0
def form_detail(request, slug, template="forms/form_detail.html", success_url=None):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)
    if form.login_required and not request.user.is_authenticated():
        return redirect("%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                        urlquote(request.get_full_path())))
    request_context = RequestContext(request)
    args = (form, request_context, request.POST or None, request.FILES or None)
    form_for_form = FormForForm(*args)
    if request.method == "POST":
        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
        else:
            entry = form_for_form.save()
            subject = form.email_subject
            if not subject:
                subject = "%s - %s" % (form.title, entry.entry_time)
            fields = []
            for (k, v) in form_for_form.fields.items():
                value = form_for_form.cleaned_data[k]
                if isinstance(value, list):
                    value = ", ".join([i.strip() for i in value])
                fields.append((v.label, value))
            context = {
                "fields": fields,
                "message": form.email_message,
                "request": request,
            }
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            if email_to and form.send_email:
                send_mail_template(subject, "form_response", email_from,
                                   email_to, context=context,
                                   fail_silently=settings.DEBUG)
            email_copies = [e.strip() for e in form.email_copies.split(",")
                            if e.strip()]
            if email_copies:
                if email_to and SEND_FROM_SUBMITTER:
                    # Send from the email entered.
                    email_from = email_to
                attachments = []
                for f in form_for_form.files.values():
                    f.seek(0)
                    attachments.append((f.name, f.read()))
                send_mail_template(subject, "form_response", email_from,
                                   email_copies, context=context,
                                   attachments=attachments,
                                   fail_silently=settings.DEBUG)
            form_valid.send(sender=request, form=form_for_form, entry=entry)
            if success_url is None:
                success_url = reverse("form_sent", kwargs={"slug": form.slug})
            # Check to see if the POST data overrides the view's success_url argument.
            success_url = request.POST.get("success_url", success_url)
            return redirect(success_url)
    context = {"form": form}
    return render_to_response(template, context, request_context)
    def post(self, request, *args, **kwargs):
        # throw an error if this user is not authorized
        # TODO: find a way to do this with carteblanche
        if (self.request.user.is_staff != True) and (self.noun.members.filter(
                id=self.request.user.id).count() == 0):
            raise Exception(
                "You tried to create a record with a location you're not assigned to. You must be an Admin or a member of "
                + self.noun.title + " to create a new record.")
        indicator = get_object_or_404(cm.Indicator, id=kwargs["pk"])
        builder_form_object = indicator.get_builder_form_object()
        form = FormForForm(builder_form_object, RequestContext(request),
                           request.POST or None, request.FILES or None)
        if not form.is_valid():
            form_invalid.send(sender=request, form=self.form_for_form)
        else:
            # Attachments read must occur before model save,
            # or seek() will fail on large uploads.
            attachments = []
            for f in form.files.values():
                f.seek(0)
                attachments.append((f.name, f.read()))
            indicator = get_object_or_404(cm.Indicator, id=kwargs["pk"])
            location = get_object_or_404(cm.Location, id=kwargs["location_pk"])
            form.cleaned_data["user"] = request.user.get_full_name()
            form.cleaned_data["location"] = location.__str__()
            entry = form.save()
            form_valid.send(sender=request, form=form, entry=entry)
            form = self.prep_form(form)
            score = indicator.score_entry(entry)
            context = self.get_context_data(**kwargs)
            if score >= indicator.passing_percentage:
                messages.success(request, 'Passing score of ' + str(score))
                action.send(self.request.user,
                            verb='entered passing record',
                            action_object=context.get("indicator"),
                            target=self.noun)
            else:
                messages.error(request, 'Not passing score of ' + str(score))
                action.send(self.request.user,
                            verb='entered failing record',
                            action_object=context.get("indicator"),
                            target=self.noun)
            return HttpResponseRedirect(
                reverse(viewname='indicator_record_create',
                        args=(
                            kwargs['location_pk'],
                            kwargs['pk'],
                        ),
                        current_app='core'))

        context = {"builder_form_object": builder_form_object, "form": form}
        return self.render_to_response(context)
Ejemplo n.º 11
0
def form_detail(request, slug, template="forms/form_detail.html"):
    form = get_object_or_404(models.DocumentSetForm, slug=slug)
    request_context = RequestContext(request)
    args = (form, request_context, request.POST or None)

    form_for_form = DocumentSetFormForForm(*args)

    if request.method == 'POST':
        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
        else:
            entry = form_for_form.save()
            form_valid.send(sender=request, form=form_for_form, entry=entry)
            return redirect(reverse('form_sent', kwargs={"slug": form.slug}))
    return render_to_response(template, { 'form': form }, request_context)
Ejemplo n.º 12
0
 def post(self, request, *args, **kwargs):
     published = Form.objects.published(for_user=request.user)
     form = get_object_or_404(published, slug=kwargs["slug"])
     form_for_form = DisplayedForm(form, RequestContext(request),
                                   request.POST or None,
                                   request.FILES or None)
     if not form_for_form.is_valid():
         form_invalid.send(sender=request, form=form_for_form)
     else:
         entry = form_for_form.save()
         form_valid.send(sender=request, form=form_for_form, entry=entry)
         if not request.is_ajax():
             return redirect("form_sent", slug=form.slug)
     context = {"form": form, "form_for_form": form_for_form}
     return self.render_to_response(context)
Ejemplo n.º 13
0
def form_detail(request, slug, template="forms/form_detail.html"):
    form = get_object_or_404(models.DocumentSetForm, slug=slug)
    request_context = RequestContext(request)
    args = (form, request_context, request.POST or None)

    form_for_form = forms.DocumentSetFormForForm(*args)

    if request.method == 'POST':
        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
        else:
            entry = form_for_form.save()
            form_valid.send(sender=request, form=form_for_form, entry=entry, document_id=request.session['document_id_for_entry'])
            return HttpResponse('')
    return render_to_response(template, { 'form': form }, request_context)
Ejemplo n.º 14
0
def form_detail(request, slug, template="forms/form_detail.html"):
    form = get_object_or_404(models.DocumentSetForm, slug=slug)
    request_context = RequestContext(request)
    args = (form, request_context, request.POST or None)

    form_for_form = forms.DocumentSetFormForForm(*args)

    if request.method == 'POST':
        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
            return HttpResponseBadRequest(json.dumps(form_for_form.errors), content_type='application/json')
        else:
            entry = form_for_form.save()
            form_valid.send(sender=request, form=form_for_form, entry=entry, document_id=request.session['document_id_for_entry'])
            return HttpResponse('')
    return render_to_response(template, { 'form': form }, request_context)
Ejemplo n.º 15
0
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    if USE_SITES:
        published = published.filter(sites=Site.objects.get_current())
    form = get_object_or_404(published, slug=slug)
    if form.login_required and not request.user.is_authenticated():
        return redirect("%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                                      urlquote(request.get_full_path())))
    args = (form, request.POST or None, request.FILES or None)
    form_for_form = FormForForm(*args)
    if request.method == "POST":
        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
        else:
            entry = form_for_form.save()
            fields = [
                "%s: %s" % (v.label, form_for_form.cleaned_data[k])
                for (k, v) in form_for_form.fields.items()
            ]
            subject = form.email_subject
            if not subject:
                subject = "%s - %s" % (form.title, entry.entry_time)
            body = "\n".join(fields)
            if form.email_message:
                body = "%s\n\n%s" % (form.email_message, body)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            if email_to and form.send_email:
                msg = EmailMessage(subject, body, email_from, [email_to])
                msg.send()
            email_from = email_to or email_from  # Send from the email entered.
            email_copies = [
                e.strip() for e in form.email_copies.split(",") if e.strip()
            ]
            if email_copies:
                msg = EmailMessage(subject, body, email_from, email_copies)
                for f in form_for_form.files.values():
                    f.seek(0)
                    msg.attach(f.name, f.read())
                msg.send()
            form_valid.send(sender=request, form=form_for_form, entry=entry)
            return redirect(reverse("form_sent", kwargs={"slug": form.slug}))
    context = {"form": form, "form_for_form": form_for_form}
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 16
0
 def post(self, request, *args, **kwargs):
     published = Form.objects.published(for_user=request.user)
     form = get_object_or_404(published, slug=kwargs["slug"])
     entry_id = request.POST.get('entry_id')
     if entry_id:
         form_entry = get_object_or_404(FormEntry, pk=entry_id)
         form_for_form = FormForForm(form, RequestContext(request),
                                 request.POST or None,
                                 request.FILES or None, instance=form_entry)
     else:
         form_for_form = FormForForm(form, RequestContext(request),
                                 request.POST or None,
                                 request.FILES or None)
     if not form_for_form.is_valid():
         form_invalid.send(sender=request, form=form_for_form)
     else:
         # Attachments read must occur before model save,
         # or seek() will fail on large uploads.
         attachments = []
         for f in form_for_form.files.values():
             f.seek(0)
             attachments.append((f.name, f.read()))
         entry = form_for_form.save()
         form_valid.send(sender=request, form=form_for_form, entry=entry)
         self.send_emails(request, form_for_form, form, entry, attachments)
         if not self.request.is_ajax():
             redirect_url = form.redirect_url
             if redirect_url:
                 if '$' in redirect_url:
                     try:
                         import re
                         person__groupdict = re.match(r'^.+/\$(?P<tag_name>\w+)/?$',
                                                      redirect_url).groupdict()
                         tag_name = person__groupdict['tag_name']
                         field = entry.form.fields.get(label=tag_name)
                         field_entry, _ = entry.fields.get_or_create(field_id=field.id)
                         redirect_url = redirect_url.replace(tag_name, field_entry.value)
                         redirect_url = redirect_url.replace('$', '')
                         return redirect(redirect_url)
                     except:
                         return redirect(redirect_url)
                 return redirect(redirect_url or reverse("form_sent", kwargs={"slug": form.slug}))
             else:
                 return redirect(reverse("form_sent", kwargs={"slug": form.slug}))
     context = {"form": form, "form_for_form": form_for_form}
     return self.render_to_response(context)
Ejemplo n.º 17
0
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    if USE_SITES:
        published = published.filter(sites=Site.objects.get_current())
    form = get_object_or_404(published, slug=slug)
    if form.login_required and not request.user.is_authenticated():
        return redirect("%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                        urlquote(request.get_full_path())))
    args = (form, request.POST or None, request.FILES or None)
    form_for_form = FormForForm(*args)
    if request.method == "POST":
        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
        else:
            entry = form_for_form.save()
            fields = ["%s: %s" % (v.label, form_for_form.cleaned_data[k])
                for (k, v) in form_for_form.fields.items()]
            subject = form.email_subject
            if not subject:
                subject = "%s - %s" % (form.title, entry.entry_time)
            body = "\n".join(fields)
            if form.email_message:
                body = "%s\n\n%s" % (form.email_message, body)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            if email_to and form.send_email:
                msg = EmailMessage(subject, body, email_from, [email_to])
                msg.send()
            email_from = email_to or email_from # Send from the email entered.
            email_copies = [e.strip() for e in form.email_copies.split(",")
                if e.strip()]
            if email_copies:
                msg = EmailMessage(subject, body, email_from, email_copies)
                for f in form_for_form.files.values():
                    f.seek(0)
                    msg.attach(f.name, f.read())
                msg.send()
            form_valid.send(sender=request, form=form_for_form, entry=entry)
            return redirect(reverse("form_sent", kwargs={"slug": form.slug}))
    context = {"form": form, "form_for_form": form_for_form}
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 18
0
 def post(self, request, *args, **kwargs):
     published = Form.objects.published(for_user=request.user)
     form = get_object_or_404(published, slug=kwargs["slug"])
     form_for_form = FormForForm(request.user.username or "default",form, RequestContext(request), request.POST or None, request.FILES or None)
     if not form_for_form.is_valid():
         form_invalid.send(sender=request, form=form_for_form)
     else:
         # Attachments read must occur before model save,
         # or seek() will fail on large uploads.
         attachments = []
         for f in form_for_form.files.values():
             f.seek(0)
             attachments.append((f.name, f.read()))
         entry = form_for_form.save()
         form_valid.send(sender=request, form=form_for_form, entry=entry)
         self.send_emails(request, form_for_form, form, entry, attachments)
         if not self.request.is_ajax():
             return redirect(form.redirect_url or
                             reverse("forms:form_sent", kwargs={"slug": form.slug}))
     context = {"form": form, "form_for_form": form_for_form}
     return self.render_to_response(context)
Ejemplo n.º 19
0
 def post(self, request, *args, **kwargs):
     published = Form.objects.published(for_user=request.user)
     form = get_object_or_404(published, slug=kwargs["slug"])
     form_for_form = FormForForm(form, RequestContext(request),
                                 request.POST or None,
                                 request.FILES or None)
     if not form_for_form.is_valid():
         form_invalid.send(sender=request, form=form_for_form)
     else:
         # Attachments read must occur before model save,
         # or seek() will fail on large uploads.
         attachments = []
         for f in form_for_form.files.values():
             f.seek(0)
             attachments.append((f.name, f.read()))
         entry = form_for_form.save()
         form_valid.send(sender=request, form=form_for_form, entry=entry)
         if not self.request.is_ajax():
             return redirect(form.redirect_url or
                 reverse("form_sent", kwargs={"slug": form.slug}))
     context = {"form": form, "form_for_form": form_for_form}
     return self.render_to_response(context)
Ejemplo n.º 20
0
 def form_post(self, request, slug):
     published = Form.objects.published(for_user=request.user)
     form = get_object_or_404(published, slug=slug)
     form_for_form = FormForForm(form, RequestContext(request),
                                 request.POST or None,
                                 request.FILES or None)
     if not form_for_form.is_valid():
         form_invalid.send(sender=request, form=form_for_form)
     else:
         # Attachments read must occur before model save,
         # or seek() will fail on large uploads.
         attachments = []
         for f in form_for_form.files.values():
             f.seek(0)
             attachments.append((f.name, f.read()))
         entry = form_for_form.save()
         form_valid.send(sender=request, form=form_for_form, entry=entry)
         self.send_emails(request, form_for_form, form, entry, attachments)
         if not request.is_ajax():
             return False, form, {}
     context = {"form": form, "form_for_form": form_for_form}
     return True, form, context
Ejemplo n.º 21
0
def process_form(request, form, context={}, is_cms_plugin=False):
    if form.login_required and not request.user.is_authenticated():
        return redirect("%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                        urlquote(request.get_full_path())))
    args = (form, request.POST or None, request.FILES or None)
    form_for_form = FormForForm(*args)
    if request.method == "POST":
        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
        else:
            entry = form_for_form.save()
            fields = ["%s: %s" % (v.label, form_for_form.cleaned_data[k])
                for (k, v) in form_for_form.fields.items()]
            subject = form.email_subject
            if not subject:
                subject = "%s - %s" % (form.title, entry.entry_time)
            body = "\n".join(fields)
            if form.email_message:
                body = "%s\n\n%s" % (form.email_message, body)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            if email_to and form.send_email:
                msg = EmailMessage(subject, body, email_from, [email_to])
                msg.send()
            email_copies = [e.strip() for e in form.email_copies.split(",")
                if e.strip()]
            if email_copies:
                msg = EmailMessage(subject, body, email_from, email_copies)
                for f in form_for_form.files.values():
                    f.seek(0)
                    msg.attach(f.name, f.read())
                msg.send()
            form_valid.send(sender=request, form=form_for_form, entry=entry)
            if is_cms_plugin:
                context['form_sent'] = True
            else:
                return redirect(reverse("form_sent", kwargs={"slug": form.slug}))
    context.update({"form": form, "form_for_form": form_for_form})
    return context
Ejemplo n.º 22
0
    def post(self, request, *args, **kwargs):
        published = Form.objects.published(for_user=request.user)
        form = get_object_or_404(published, slug=kwargs["slug"])
        form_for_form = FormForForm(form, RequestContext(request),
                                    request.POST or None,
                                    request.FILES or None)

        current_form = Form.objects.get(slug=kwargs["slug"])
        entries_form = EntriesForm(current_form, self.request)
        form_struct = self.make_form_struct(entries_form, form)
        query_dict = dict(request.POST.iterlists())
        form_warnings = self.get_warning_messages(form_struct)

        reserve = False
        for question in form_warnings:
            question_decoded = unidecode(question).lower()
            if question_decoded in query_dict:
                for answer in query_dict[question_decoded]:
                    for answer_stats in form_warnings[question]:
                        if answer in answer_stats:
                            reserve = True


        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
        else:
            # Attachments read must occur before model save,
            # or seek() will fail on large uploads.
            attachments = []
            for f in form_for_form.files.values():
                f.seek(0)
                attachments.append((f.name, f.read()))
            entry = form_for_form.save(reserved=reserve)
            form_valid.send(sender=request, form=form_for_form, entry=entry)
            self.send_emails(request, form_for_form, form, entry, attachments)
            if not self.request.is_ajax():
                return redirect("form_sent", slug=form.slug)
        context = {"form": form, "form_for_form": form_for_form}
        return self.render_to_response(context)
Ejemplo n.º 23
0
    def post(self, request, *args, **kwargs):
        #throw an error if this user is not authorized
        #TODO: find a way to do this with carteblanche
        if (self.request.user.is_staff != True) and (self.noun.members.filter(id=self.request.user.id).count() == 0):
            raise Exception("You tried to create a record with a location you're not assigned to. You must be an Admin or a member of "+self.noun.title+" to create a new record.")
        indicator = get_object_or_404(cm.Indicator, id=kwargs["pk"])
        builder_form_object = indicator.get_builder_form_object()
        form = FormForForm(builder_form_object, RequestContext(request),
                                    request.POST or None,
                                    request.FILES or None)
        if not form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
        else:
            # Attachments read must occur before model save,
            # or seek() will fail on large uploads.
            attachments = []
            for f in form.files.values():
                f.seek(0)
                attachments.append((f.name, f.read()))
            indicator = get_object_or_404(cm.Indicator, id=kwargs["pk"])
            location = get_object_or_404(cm.Location, id=kwargs["location_pk"])
            form.cleaned_data["user"] = request.user.get_full_name()
            form.cleaned_data["location"] = location.__str__()
            entry = form.save()
            form_valid.send(sender=request, form=form, entry=entry)
            form = self.prep_form(form)
            score = indicator.score_entry(entry)
            context = self.get_context_data(**kwargs)
            if score >= indicator.passing_percentage:
                messages.success(request,'Passing score of '+str(score))
                action.send(self.request.user, verb='entered passing record', action_object=context.get("indicator"), target=self.noun)
            else:
                messages.error(request,'Not passing score of '+str(score))
                action.send(self.request.user, verb='entered failing record', action_object=context.get("indicator"), target=self.noun)
            return HttpResponseRedirect(reverse(viewname='indicator_record_create', args=(kwargs['location_pk'], kwargs['pk'],), current_app='core'))

        context = {"builder_form_object": builder_form_object, "form": form}
        return self.render_to_response(context)
Ejemplo n.º 24
0
 def post(self, request, *args, **kwargs):
     context = self.get_context_data(**kwargs)
     form_for_form = FormForForm(self.form, RequestContext(request),
                                 request.POST or None,
                                 request.FILES or None)
     if not form_for_form.is_valid():
         form_invalid.send(sender=request, form=form_for_form)
     else:
         # Attachments read must occur before model save,
         # or seek() will fail on large uploads.
         attachments = []
         for f in form_for_form.files.values():
             f.seek(0)
             attachments.append((f.name, f.read()))
         entry = form_for_form.save()
         form_valid.send(sender=request, form=form_for_form, entry=entry)
         self.send_emails(request, form_for_form, self.form, entry, attachments)
         if not self.request.is_ajax():
             return redirect(
                 self.form.redirect_url or reverse(
                     "form_sent", kwargs={"slug": self.form.slug}))
     context.update({"form_for_form": form_for_form})
     return self.render_to_response(context)
Ejemplo n.º 25
0
    def process(self, request, **kwargs):
        request_context = RequestContext(request)
        form = self.form
        args = (form, request_context,
                request.POST or None, request.FILES or None)
        form_for_form = FormForForm(*args)
        if request.method == "POST":
            if not form_for_form.is_valid():
                form_invalid.send(sender=request, form=form_for_form)
            else:
                entry = form_for_form.save()

                # send e-mail message to user
                email_to = form_for_form.email_to()
                if email_to and form.send_email:
                    send_email_message(form_for_form, email_to, entry)

                # send email to email_copies
                send_email_form(request, form_for_form, entry)

                form_valid.send(sender=request, form=form_for_form, entry=entry)

                if form.response.startswith('/') or form.response.startswith('http'):
                    return redirect(form.response)

                context = Context({
                    'form': form_for_form,
                    })
                template = Template(form.response)
                self.rendered_output = template.render(context)
                return

        context = {
                "form": form_for_form,
                }
        self.rendered_output = render_to_string(self.template, context,
                request_context)
Ejemplo n.º 26
0
 def process_form(self, request):
     if self.bound_form:
         return self.entry
     from .forms import FormForForm
     self.bound_form = FormForForm(self, request.POST, request.FILES)
     if not self.bound_form.is_valid():
         form_invalid.send(sender=request, form=self.bound_form)
         return None
     self.entry = self.bound_form.save()
     fields = [
         "%s: %s" % (v.label, self.bound_form.cleaned_data[k])
         for (k, v) in self.bound_form.fields.items()
     ]
     subject = self.email_subject
     if not subject:
         subject = "%s - %s" % (self.title, self.entry.entry_time)
     body = "\n".join(fields)
     if self.email_message:
         body = "%s\n\n%s" % (self.email_message, body)
     email_from = self.email_from or settings.DEFAULT_FROM_EMAIL
     email_to = self.bound_form.email_to()
     if email_to and self.send_email:
         msg = EmailMessage(subject, body, email_from, [email_to])
         msg.send()
     email_from = email_to or email_from  # Send from the email entered.
     email_copies = [
         e.strip() for e in self.email_copies.split(",") if e.strip()
     ]
     if email_copies:
         msg = EmailMessage(subject, body, email_from, email_copies)
         for f in self.bound_form.files.values():
             f.seek(0)
             msg.attach(f.name, f.read())
         msg.send()
     form_valid.send(sender=request, form=self.bound_form, entry=self.entry)
     return self.entry
Ejemplo n.º 27
0
def form_detail(request, slug, template="questionnaire/form_detail.html", extra_object_id=None):
    """
    Display a built form and handle its submission.
    
    object_id is the primary key of an object like Conversation or BuddyChatProfile that will be linked to this FormEntry
    via ConversationFormEntry or QuestionnaireFormEntry.
    """

    published = Form.objects.published(for_user=request.user)
    if USE_SITES:
        published = published.filter(sites=Site.objects.get_current())
    form = get_object_or_404(published, slug=slug)

    if form.login_required and not request.user.is_authenticated():
        return redirect("%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                        urlquote(request.get_full_path())))

    args = (form, request.POST or None, request.FILES or None)
    form_for_form = FormForForm(*args)

    if request.method == "POST":
        has_extra_permission = False

        # if the id of an extra object is given, make sure user has permissions and preconditions are met
        if extra_object_id > 0:
            if form.questionnaire.position == 'SC':
                conv = get_object_or_404(Conversation, pk=extra_object_id)

                # only staff member assigned to Conversation may take SC-Questionnaire
                has_permission = (conv.getStaff().user == request.user)
                # the SC-Questionnaire can be taken only once
                doesnt_exist = (form.questionnaire.conversationformentry_set.filter(conversation__id=extra_object_id).count() == 0)

                has_extra_permission = has_permission and doesnt_exist
            elif form.questionnaire.position == 'CR':
                profile = get_object_or_404(BuddyChatProfile, pk=extra_object_id)

                has_permission = (profile.user == request.user)
                doesnt_exist = (profile.questionnaires.filter(position='CR').count() == 0)

                has_extra_permission = has_permission and doesnt_exist
            elif form.questionnaire.position == 'CX':
                profile = get_object_or_404(BuddyChatProfile, pk=extra_object_id)
                has_extra_permission = (profile.user == request.user)
            elif form.questionnaire.position == 'SX':
                profile = get_object_or_404(BuddyChatProfile, pk=extra_object_id)

                # only careworker assigned to BuddyProfile may take SX-Questionnaire
                has_extra_permission = (profile.careworker == request.user)


        if not form_for_form.is_valid() or (extra_object_id > 0 and not has_extra_permission):
            form_invalid.send(sender=request, form=form_for_form)
        else:
            entry = form_for_form.save()

            # send email
            fields = ["%s: %s" % (v.label, form_for_form.cleaned_data[k])
                for (k, v) in form_for_form.fields.items()]
            subject = form.email_subject
            if not subject:
                subject = "%s - %s" % (form.title, entry.entry_time)
            body = "\n".join(fields)
            if form.email_message:
                body = "%s\n\n%s" % (form.email_message, body)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            if email_to and form.send_email:
                msg = EmailMessage(subject, body, email_from, [email_to])
                msg.send()
            email_from = email_to or email_from # Send from the email entered.
            email_copies = [e.strip() for e in form.email_copies.split(",")
                if e.strip()]
            if email_copies:
                msg = EmailMessage(subject, body, email_from, email_copies)
                for f in form_for_form.files.values():
                    f.seek(0)
                    msg.attach(f.name, f.read())
                msg.send()

            # send signals
            form_valid.send(sender=request, form=form_for_form, entry=entry)
            questionnaire_saved.send(sender=request, questionnaire=form.questionnaire, entry=entry, extra_object_id=extra_object_id)

            return redirect(reverse("form_sent", kwargs={"slug": form.slug, "entry": entry.pk}))

    context = {
        "form": form,
        "form_for_form": form_for_form,
    }

    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 28
0
Archivo: views.py Proyecto: xnx99/enjaz
 def post(self,
          request,
          content_type=None,
          object_id=None,
          form_detail_template="forms/form_detail.html",
          *args,
          **kwargs):
     self.object = get_object_or_404(
         content_type.model_class(),
         id=object_id) if content_type is not None else None
     published = Form.objects.published(
         for_user=request.user,
         for_object=self.object,
         editor_check=kwargs.get("edit_perm_check"))
     kw = {
         "slug": kwargs["slug"]
     } if wrapper_settings.USE_SLUGS else {
         "id": kwargs["form_id"]
     }
     form = get_object_or_404(published,
                              content_type=content_type,
                              object_id=object_id,
                              **kw)
     form_for_form = FormForForm(
         form,
         RequestContext(request),
         request.POST or None,
         request.FILES or None,
         instance=FormEntry(submitter=request.user if request.user.
                            is_authenticated() else None))
     if not form_for_form.is_valid():
         form_invalid.send(sender=request, form=form_for_form)
     else:
         # Attachments read must occur before model save,
         # or seek() will fail on large uploads.
         attachments = []
         for f in form_for_form.files.values():
             f.seek(0)
             attachments.append((f.name, f.read()))
         entry = form_for_form.save()
         form_valid.send(sender=request, form=form_for_form, entry=entry)
         self.send_emails(request, form_for_form, form, entry, attachments)
         if not self.request.is_ajax():
             key = "slug" if wrapper_settings.USE_SLUGS else "form_id"
             return redirect(
                 form.redirect_url
                 or reverse("forms:form_sent",
                            current_app=request.resolver_match.namespace,
                            kwargs={
                                key: form.get_url_attr(),
                                "object_id": object_id
                            }))
     context = {
         "form": form,
         "form_for_form": form_for_form,
         "object_id": object_id
     }
     context[kwargs.pop("object_context_name", "object")] = self.object
     context.update(kwargs.pop("custom_context", {}))
     self.template_name = form_detail_template
     return self.render_to_response(context)