Exemple #1
0
    def get_search_form(self):
        """
        Return list of form based on model
        """
        magic_dico_form = self.get_dict_for_forms()
        forms = []
        initial = list(self.request.GET.lists())

        for key, value in magic_dico_form.items():
            form = Form()
            model = value["model"]
            if not value["fields"]:
                continue
            for field in value["fields"]:
                formfield = get_formfield(model, field)
                formfield.widget.attrs.update({'class': self.css_class})
                form.fields.update({field: formfield})

            initial_tmp = {}
            for k, vals in initial:
                tmp_list = k.split(model.__name__ + "-")
                if len(tmp_list) == 2:
                    list_val_tmp = vals[0] if len(vals) == 1 else [
                        val for val in vals if val != ''
                    ]
                    initial_tmp[tmp_list[-1]] = list_val_tmp

            form.initial = initial_tmp
            form.prefix = model.__name__
            forms.append(form)
        return sorted(forms, key=lambda form: form.prefix)
Exemple #2
0
def simple_search(request):
    """Controlla form e crea ricerca semplice

    Controlla che il contenuto del form sia valido e in caso affermativo redirige
    alla pagina dei risultati, se no invoca una BadRequest

    :param request: richiesta HTTP
    :return: redirezione o HttpResponseBadRequest
    """
    if request.method != 'POST':
        return HttpResponseBadRequest(
            'Impossibile fare richiesta GET su simple_search view')
    elif request.POST['testo_ricerca'] == '':
        return HttpResponseRedirect(reverse('attivita:index'))

    form = Form(request.POST)
    if form.is_valid():
        if request.POST['testo_ricerca'] != '':
            ricerca = RicercaSemplice(testo=request.POST['testo_ricerca'])
            ricerca.save()
            return HttpResponseRedirect(
                reverse('search:simple_results', args=(ricerca.id, )))

    print('Qualcosa è andato storto')
    messages.error(request, "Errore nella compilazione form")
    return HttpResponseRedirect(reverse('attivita:index'))
Exemple #3
0
 def __init__(self, *args, **kwargs):
     self.instance = kwargs.pop('instance')
     Form.__init__(self, *args, **kwargs)
     self.fields['account'] = ModelChoiceField(
         self.instance.domain.account_set.exclude(
             mailinglists=self.instance),
         empty_label='')
Exemple #4
0
def cancel(request, payload):
    from itsdangerous import BadSignature
    s = get_serializer()
    try:
        appointment_id = s.loads(payload)
    except BadSignature:
        return Http404
    appointment = get_object_or_404(Appointment, pk=appointment_id)
    
    if appointment.is_cancelled():
        messages.warning(request, _("You've already cancelled this appointment."))    
        return redirect('finish')
    
    if 'POST' == request.method:
        form = Form(request.POST)
        if form.is_valid():    
            appointment.cancel()
            messages.info(request, _("You successfully cancelled your appointment."))
            return redirect('finish')

        # This doesn't seem to be the correct return code
        return Http404
    
    form = Form()
    return render(request, 'cancel.html', {'form': form})
Exemple #5
0
 def get(self, request, **kwargs):
     if request.method == 'GET':
         form = Form(request.GET)
         if form.is_valid():
             # Names
             name1 = request.GET.get('inputName1')
             name2 = request.GET.get('inputName2')
             if not name1:
                 name1 = 'Noname1'
             if not name2:
                 name2 = 'Noname2'
             # Calculations
             bdate1 = request.GET.get('inputDate1').split('-')
             bdate1 = bdate1[2] + '.' + bdate1[1] + '.' + bdate1[0]
             bdate2 = request.GET.get('inputDate2').split('-')
             bdate2 = bdate2[2] + '.' + bdate2[1] + '.' + bdate2[0]
             #
             data = match_all(bdate1, bdate2)
             data1 = data['p1p2']
             data2 = data['p2p1']
             items = list(data1.keys())
             #
             context = {
                 'name1': name1,
                 'name2': name2,
                 'items': ",".join(items),
                 'y1': ",".join([str(data1[i]) for i in items]),
                 'y2': ",".join([str(data2[i]) for i in items])
             }
         else:
             context = None
     return render(request, "match_engine1.html", context=context)
Exemple #6
0
def report_detail(request, slug):
    """Render report detail or list of reports in case of wrong report slug is specified"""
    data = {}
    all_reports = {}
    template = 'reporting/reports.html'
    report = None
    form = Form()
    reports_date_init = True
    try:
        # Retrieving report name by slug specified in an URL
        report = reporting.get_report(slug)(request)
    except reporting.NoReportException:
        pass

    if report is not None:
        form = report.form_class(request.POST or None)
        if request.method == "POST" and form.is_valid():
            if request.POST.get('generate', None):
                data = report.generate(**form.cleaned_data)
                reports_date_init = False
        template = report.template_name
    else:
        # Wrong report slug is specified. rendering all the reports list
        all_reports = [(slug, unicode(r.verbose_name))
                       for slug, r in reporting.all_reports()]
    return direct_to_template(
        request, template, {
            'form': form,
            'data': data,
            'report': report,
            'reports_date_init': reports_date_init,
            'object_list': all_reports,
        })
Exemple #7
0
def contact_edit(request, id, template_name='membership/entity_edit.html'):
    contact = get_object_or_404(Contact, id=id)

    # XXX: I hate this. Wasn't there a shortcut for creating a form from instance?
    class Form(ModelForm):
        class Meta:
            model = Contact

    before = contact.__dict__.copy() # Otherwise save() (or valid?) will change the dict, needs to be here
    if request.method == 'POST':
        if not request.user.has_perm('membership.manage_members'):
            messages.error(request, unicode(_("You are not authorized to modify memberships.")))
            return redirect('contact_edit', id)

        form = Form(request.POST, instance=contact)

        if form.is_valid():
            form.save()
            after = contact.__dict__
            log_change(contact, request.user, before, after)
            messages.success(request, unicode(_("Changes to contact %s saved.") % contact))
            return redirect('contact_edit', id) # form stays as POST otherwise if someone refreshes
        else:
            messages.error(request, unicode(_("Changes to contact %s not saved.") % contact))
    else:
        form =  Form(instance=contact)
        message = ""
    logentries = bake_log_entries(contact.logs.all())
    return render_to_response(template_name, {'form': form, 'contact': contact,
        'logentries': logentries},
        context_instance=RequestContext(request))
Exemple #8
0
 def get_payment_process_response(self, service, order, urls):
     address = order.billing_address
     payment = Payment(
         order_number=order.identifier,
         reference_number=order.reference_number[:20],
         amount=str(int(order.taxful_total_price * 100)),
         delivery_date=(order.order_date.date() + datetime.timedelta(1)).strftime("%Y%m%d"),
         return_url=urls.return_url,
         delayed_url=urls.return_url,
         cancel_url=urls.cancel_url,
         message=force_text(order),
         contact=Contact(
             first_name=flatten_unicode(address.first_name),
             last_name=flatten_unicode(address.last_name),
             email=flatten_unicode(address.email),
             phone=flatten_unicode(address.phone),
             address=flatten_unicode(address.street),
             postcode=address.postal_code,
             postoffice=flatten_unicode(address.city),
             country=address.country.alpha3
         )
     )
     form = Form()
     for key, value in self._get_checkout_object(service).get_offsite_button_data(payment).items():
         form.fields[key] = CharField(initial=value, widget=HiddenInput)
     html = TEMPLATE % {
         "form": form,
         "continue_text": _("Continue to Checkout.fi"),
     }
     return HttpResponse(html)
Exemple #9
0
def bill_edit(request, id, template_name='membership/entity_edit.html'):
    bill = get_object_or_404(Bill, id=id)

    class Form(ModelForm):
        class Meta:
            model = Bill
            exclude = ('billingcycle', 'reminder_count')

    before = bill.__dict__.copy() # Otherwise save() (or valid?) will change the dict, needs to be here
    if request.method == 'POST':
        form = Form(request.POST, instance=bill)
        if form.is_valid():
            form.save()
            after = bill.__dict__
            log_change(bill, request.user, before, after)
            messages.success(request, unicode(_("Changes to bill %s saved.") % bill))
            return redirect('bill_edit', id) # form stays as POST otherwise if someone refreshes
        else:
            messages.error(request, unicode(_("Changes to bill %s not saved.") % bill))
    else:
        form =  Form(instance=bill)
    logentries = bake_log_entries(bill.logs.all())
    return render_to_response(template_name, {'form': form, 'bill': bill,
        'logentries': logentries},
        context_instance=RequestContext(request))
Exemple #10
0
def setprimary(request, **kwargs):
    team_link = kwargs.get("team_link")
    picture_id = kwargs["picture_id"]
    account = get_object_or_404(Account, user=request.user)
    team = team_link and team_control.get_or_404(team_link) or None
    picture = get_object_or_404(Picture, id=picture_id)
    prefix = team_link and "/%s" % team_link or ""
    url = "%s/gallery/list/%s" % (prefix, picture.gallery.id)
    if team:
        assert_member(account, team)
    if request.method == "POST":
        form = Form(request.POST)
        if form.is_valid():
            control.setprimary(account, picture)
            return HttpResponseRedirect(url)
    else:
        form = Form()
    # TODO make template that shows the image being set!
    args = { 
        "form" : form, "form_title" : _("SET_AS_PRIMARY_PICTURE"), 
        "cancel_url" : url
    }
    if team:
        return rtr(team, None, request, "site/form.html", args)
    else:
        return render_response(request, "site/form.html", args)
Exemple #11
0
    def authorization_endpoint(request):
        auth_code_generator = AuthorizationCodeGenerator(missing_redirect_uri)

        try:
            auth_code_generator.validate(request)
        except AuthorizationError as authorization_error:
            return auth_code_generator.make_error_redirect(authorization_error)

        if request.method == 'GET':
            return render(
                request, authorization_template_name, {
                    'form':
                    Form(),
                    'client':
                    auth_code_generator.client,
                    'scopes':
                    auth_code_generator.valid_scope_objects,
                    'form_action':
                    update_parameters(
                        authorization_endpoint_uri,
                        auth_code_generator.get_request_uri_parameters(
                            as_dict=True)),
                })

        if request.method == 'POST':
            form = Form(request)
            if form.is_valid() and request.POST.get('user_action') == 'Accept':
                return auth_code_generator.make_success_redirect()
            else:
                return auth_code_generator.make_error_redirect()
Exemple #12
0
def report_detail(request, slug):
    """Render report detail or list of reports in case of wrong report slug is specified"""
    data = {}
    all_reports = {}
    template = 'reporting/reports.html'
    report = None
    form = Form()
    reports_date_init = True
    try:
        # Retrieving report name by slug specified in an URL
        report = reporting.get_report(slug)(request)
    except reporting.NoReportException:
        pass

    if report is not None:
        form = report.form_class(request.POST or None)
        if request.method == "POST" and form.is_valid():
            if request.POST.get('generate', None):
                data = report.generate(**form.cleaned_data)
                reports_date_init = False
        template = report.template_name
    else:
        # Wrong report slug is specified. rendering all the reports list
        all_reports = [(slug, unicode(r.verbose_name)) for slug, r in reporting.all_reports()]
    return direct_to_template(request, template, {
        'form': form,
        'data': data,
        'report': report,
        'reports_date_init': reports_date_init,
        'object_list': all_reports,
    })
Exemple #13
0
def upload_file(request):
    if request.method == 'POST':
        if request.user.is_authenticated():
            print "-------------------------upload file"
            form = Form(request.POST, request.FILES)
            if form.is_valid():
                print "file valid"
                print request.FILES
                directory = request.POST['directory']
                instance = UserFiles(user=request.user,
                                     directory=directory,
                                     file=request.FILES['file'])
                if directory == '':
                    json_helper.update_file(
                        settings.MEDIA_ROOT + 'users/' +
                        str(request.user.username) + '/', instance.file.name,
                        settings.MEDIA_ROOT + 'users/' +
                        str(request.user.username) + '/' + instance.file.name)
                else:
                    json_helper.update_file(
                        settings.MEDIA_ROOT + 'users/' +
                        str(request.user.username) + '/',
                        directory + '/' + instance.file.name,
                        settings.MEDIA_ROOT + 'users/' +
                        str(request.user.username) + '/' + directory + '/' +
                        instance.file.name)
                instance.save()
                json_helper.logger(settings.MEDIA_ROOT + 'log.txt',
                                   request.user.username, 'updated file: ',
                                   instance.file.name)

                response = HttpResponse()
                response.content = json.dumps(
                    json_helper.read_json(settings.MEDIA_ROOT + 'users/' +
                                          str(request.user.username) +
                                          '/file_list.txt'))
                response['Content-Type'] = 'application/json'
                response.status_code = 200
                return response
        else:
            response = HttpResponse()
            response.content = "User not authenticated"
            response.status_code = 497
            return response
    else:
        form = Form()

    if request.user.is_authenticated:
        documents = UserFiles.objects.filter(
            user__username=request.user.username)
    else:
        documents = {}
    return render_to_response('file_demo/upload_file.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
def test_form_validation_supercedes_model_validation_when_used_together(
        rf, modelcls):
    request = rf.get('/', data={'f': 'admin/should_not_exist.json'})
    Form = modelform_factory(modelcls, fields=['f'])
    form = Form(data=request.GET)
    assert form.is_valid() is False
    assert form.errors == {
        'f': [
            'Select a valid choice. admin/should_not_exist.json is not one of the available choices.'
        ]
    }
Exemple #15
0
 def __init__(self, formdata, request, *args, **kwargs):
     Form.__init__(self, formdata, *args, **kwargs)
     self.fields["entries_selected"] = ModelMultipleChoiceField(
         required=False, queryset=PomEntry.objects.filter(author=request.user)
     )
     self.fields["categories_selected"] = ModelMultipleChoiceField(
         required=False, queryset=PomCategory.objects.filter(pomentry__author=request.user).distinct()
     )
     self.fields["users_selected"] = ModelMultipleChoiceField(
         queryset=User.objects.exclude(username=request.user.username)
     )
def delete_tag(request, tag_id):
    
    tag = Tag.objects.get(id=tag_id)
    
    if request.method == 'POST':
        # use a dummy form just to verify the CSRF token
        form = Form(request.POST)
        if form.is_valid():
            tag.delete()

    return redirect(tag.entry.specific_instance())
Exemple #17
0
  def __init__(self, user, *args, **kwargs):
    Form.__init__(self, *args, **kwargs)

    assocs = UserAssociation.objects.filter(user=user)
    if assocs.count() == 0:
      raise UserAssociation.DoesNotExist()
    vals = assocs.order_by('openid_url').values_list('openid_url', flat=True)
    self.fields['openid_url_to_delete'].choices = ((val, val) for val in vals)

    self._user = user
    self._assoc = None
 def test_add_embargo_date_to_deposit_result(self, embargo):
     """
     If an embargo is set, add to deposit record, otherwise not
     """
     # We just set cleaned data directly
     f = Form()
     f.cleaned_data = dict()
     if embargo is not None:
         f.cleaned_data['embargo'] = embargo
     dr = DepositResult(status='pending')
     dr = self.protocol._add_embargo_date_to_deposit_result(dr, f)
     assert dr.embargo_date == embargo
Exemple #19
0
    def form_valid(self, form: Form) -> HttpResponse:
        """Complete the registration and return response."""
        try:
            # Return value is ignored, because we need whole attestation.
            self.complete_registration(form)
        except ValidationError as error:
            form.add_error(None, error)
            return self.form_invalid(form)

        Authenticator.objects.create(user=self.request.user, attestation=form.cleaned_data['attestation'],
                                     user_handle=form.cleaned_data.get('user_handle'),
                                     label=form.cleaned_data.get('label'))
        return super().form_valid(form)
Exemple #20
0
def logout(request):
    if request.method == 'POST':
        form = Form(request.POST)

        if form.is_valid():
            del request.session['ocf_user']
            return redirect_back(request)
    else:
        form = Form()

    return render_to_response('logout.html', {
        'user': request.session['ocf_user']
    }, context_instance=RequestContext(request))
    def testJsonResponseWithStatus400ReturnErrorsWhenSettingsSpecifyErrorReporting(self):
        settings.DYNAMICRESPONSE_JSON_FORM_ERRORS = True
        simple_form = Form()
        simple_form.is_valid = Mock(return_value=False)
        simple_form.errors[u'SimpleError'] = u'This was a very simple error, shame on you'
        simple_form.errors[u'Error2'] = u'This was a bit more serious'

        should_equal = simplejson.dumps({'field_errors': simple_form.errors}, indent=0)

        dynRes = DynamicResponse({}, extra={ 'form': simple_form }, status=CR_INVALID_DATA)
        serialized_result = dynRes.serialize()

        self.assertTrue(isinstance(serialized_result, JsonResponse))
        self.assertEqual(should_equal, serialized_result.content, 'Correct error message is not returned from JsonResponse')
Exemple #22
0
def get_variation_selection_form(request, product):  # pragma: no cover
    # TODO: Does this belong here? Eliding from coverage meanwhile.
    variables = ProductVariationVariable.objects.filter(product=product).order_by("name").values_list("id", "name")
    values = defaultdict(list)
    for var_id, val_id, val in (
        ProductVariationVariableValue.objects.filter(variable__product=product)
        .values_list("variable_id", "id", "value")
    ):
        values[var_id].append((val_id, val))
    form = Form(data=request.POST if request.POST else None)
    for variable_id, variable_name in variables:
        var_values = sorted(values.get(variable_id, ()))
        form.fields["var_%d" % variable_id] = IntegerField(label=variable_name, widget=Select(choices=var_values))
    return form
Exemple #23
0
 def _create_mass_actions_form(self):
     """
     Creates the actions form and bounds it to the request.POST
     """
     form = Form()
     form.fields['_selected_action'] = ChoiceField(
         label='Actions',
         required = False,
         choices=[('', '---')] + [(a.__name__, a.short_description) for a in self.mass_actions]
     )
     form.fields['_selected_objects'] = CharField(
         required = False,
         widget=HiddenInput()
     )
     return form
Exemple #24
0
def get_variation_selection_form(request, product):  # pragma: no cover
    # TODO: Does this belong here? Eliding from coverage meanwhile.
    variables = ProductVariationVariable.objects.filter(
        product=product).order_by("name").values_list("id", "name")
    values = defaultdict(list)
    for var_id, val_id, val in (ProductVariationVariableValue.objects.filter(
            variable__product=product).values_list("variable_id", "id",
                                                   "value")):
        values[var_id].append((val_id, val))
    form = Form(data=request.POST if request.POST else None)
    for variable_id, variable_name in variables:
        var_values = sorted(values.get(variable_id, ()))
        form.fields["var_%d" % variable_id] = IntegerField(
            label=variable_name, widget=Select(choices=var_values))
    return form
Exemple #25
0
 def test_add_license_to_deposit_result(self, license_chooser):
     """
     If a license is selected, add to deposit record, otherwise not
     """
     # We just set the cleaned data directly
     f = Form()
     f.cleaned_data = dict()
     if license_chooser:
         f.cleaned_data['license'] = license_chooser
     dr = DepositResult(status='pending')
     dr = self.protocol._add_license_to_deposit_result(dr, f)
     if license_chooser:
         assert dr.license == license_chooser.license
     else:
         assert dr.license == None
    def create_form(self, params):
        form = Form()
        form.fields[self.field_start] = DateField(
            label="from date", widget=AdminDateWidget, required=False, initial=params.get(self.field_start, "")
        )

        form.fields[self.field_end] = DateField(
            label="to date", widget=AdminDateWidget, required=False, initial=params.get(self.field_end, "")
        )

        for k, v in params.items():
            if not k.startswith(self.field_generic):
                form.fields[k] = CharField(widget=HiddenInput, required=False, initial=v)

        return form
Exemple #27
0
 def __init__(self, project, form=None):
     self.project = project
     self.form = form if form is not None else Form({})
     self.objects = []
     self.jobs = []
     self.max_group_depth = 1
     self.ns = None
Exemple #28
0
    def redirect_to_import_errors(
            self, form: Form, request: HttpRequest,
            capitalized_model_name: str, model_value: str,
            redirect_location: str) -> HttpResponseRedirect:
        non_field_errors = ", ".join(
            [error for error in form.non_field_errors()])
        field_errors = ", ".join([
            "Field '{field}': {errors}".format(field=field.label,
                                               errors=",".join(field.errors))
            for field in form if field.errors
        ])
        if non_field_errors:
            non_field_errors = "{}, ".format(non_field_errors)

        self.message_user(
            request,
            "Errors importing {model_name} '{model_value}': {errors} {field_errors}"
            .format(
                model_name=capitalized_model_name,
                model_value=model_value,
                errors=non_field_errors,
                field_errors=field_errors,
            ),
            level="error",
        )
        return HttpResponseRedirect(reverse(redirect_location))
Exemple #29
0
    def create(self, request):
        positionFile = request.FILES.get('positionFile')
        form = Form(request.POST)
        portfolioName = form.data['portfolio']

        positions = pd.read_excel(positionFile)
        for i in positions.index:
            #Skip empty quantity
            if math.isnan(positions['Qty (Current)'][i]):
                continue

            stock, created = Stock.objects.update_or_create(
                tick=positions["SecCode"][i],
                defaults={
                    'name': positions['Security Desc'][i],
                    'lastprice': positions['Last Px'][i]
                },
            )

            portfolio, created = Portfolio.objects.update_or_create(
                name=portfolioName)

            position, created = Position.objects.update_or_create(
                portfolio=portfolio,
                stock=stock,
                defaults={
                    'openprice': positions['Open Px'][i],
                    'quantity': positions['Qty (Current)'][i]
                })

        content_type = positionFile.content_type
        response = f'{content_type} is uploaded'
        return Response(response)
Exemple #30
0
    def form_valid(self, form: Form) -> Model:
        """ Called when the form is valid and an instance is to be created """
        instance = form.save(commit=False)
        instance.member = self.request.user.alumni
        instance.save()

        return instance
Exemple #31
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # fill in the table of "changed fields"
        context['changed_fields'] = []
        changed_field_names = self.object.changed_fields.split()

        for field in changed_field_names:
            if (field == 'artist'):
                #current = ' '.join(self.object.song.artist.all())
                current = "\n".join(
                    list(a.name for a in self.object.song.artist.all()))
                #new = ' '.join(self.object.artist.all())
                new = "\n".join(list(a.name for a in self.object.artist.all()))
            else:
                current = getattr(self.object.song, field)
                new = getattr(self.object, field)

            context['changed_fields'].append({
                'name': field,
                'current': current,
                'new': new,
            })

        # add a form for approve / reject
        context['form'] = Form()
        return context
Exemple #32
0
def upload_file(request):
    if request.method == 'POST':
        if request.user.is_authenticated():
            print "-------------------------upload file"
            form = Form(request.POST, request.FILES)
            if form.is_valid():
                print "file valid"
                print request.FILES
                directory = request.POST['directory']
                instance = UserFiles(user=request.user,directory=directory, file=request.FILES['file'])
                if directory == '':
                     json_helper.update_file(settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/',
                                            instance.file.name,
                                            settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/'+
                                            instance.file.name)
                else:
                    json_helper.update_file(settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/',
                                            directory+'/'+instance.file.name,
                                            settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/'+
                                            directory + '/' + instance.file.name)
                instance.save()
                json_helper.logger(settings.MEDIA_ROOT+'log.txt', request.user.username, 'updated file: ', instance.file.name)

                response = HttpResponse()
                response.content = json.dumps(json_helper.read_json(settings.MEDIA_ROOT+'users/'+
                                                            str(request.user.username)+'/file_list.txt'))
                response['Content-Type'] = 'application/json'
                response.status_code = 200
                return response
        else:
            response = HttpResponse()
            response.content = "User not authenticated"
            response.status_code = 497
            return response
    else:
        form = Form()

    if request.user.is_authenticated:
        documents =  UserFiles.objects.filter(user__username=request.user.username)
    else:
        documents = {}
    return render_to_response(
        'file_demo/upload_file.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
Exemple #33
0
def change_access(request, action, user_pk, login_pk):
    user = User.objects.select_related('_profile_cache').get(pk=user_pk)
    login = Login.objects.get(pk=login_pk)

    if request.method == 'POST':
        form = EmptyForm(request.POST) # Using empty form just for CSFR
        if form.is_valid():
            if action == 'permit':
                login.users.add(user)
            elif action == 'deny':
                login.users.remove(user)
            return redirect('ssheepdog.views.view_access_summary')
    else:
        form = EmptyForm()
    return render_to_response('confirm_toggle.html',
                              {'user': user, 'form': form,
                               'login': login, 'action': action},
                              context_instance=RequestContext(request))
Exemple #34
0
    def _create_search_form(self, request):
        form = Form(request.GET)
        form.fields[self.searchable_key] = CharField(
            label = self.searchable_label,
            required = False
        )
        form.fields[self.searchable_key].widget.attrs.update(
           {
               'class': 'searchable-form',
               'placeholder': '...',
           }
        )

        # Add hidden input fields to keep current query sting
        for key, value in request.GET.items():
            if key != self.searchable_key:
                form.fields[key] = CharField(widget=HiddenInput())

        return form
Exemple #35
0
 def payment_form(self, request: HttpRequest) -> Form:
     """
     This is called by the default implementation of :py:meth:`checkout_form_render`
     to obtain the form that is displayed to the user during the checkout
     process. The default implementation constructs the form using
     :py:attr:`checkout_form_fields` and sets appropriate prefixes for the form
     and all fields and fills the form with data form the user's session.
     """
     form = Form(
         data=(request.POST if request.method == 'POST' else None),
         prefix='payment_%s' % self.identifier,
         initial={
             k.replace('payment_%s_' % self.identifier, ''): v
             for k, v in request.session.items()
             if k.startswith('payment_%s_' % self.identifier)
         }
     )
     form.fields = self.payment_form_fields
     return form
Exemple #36
0
def delete(request, team_link, page_link):
    team = team_control.get_or_404(team_link)
    account = get_object_or_404(Account, user=request.user)
    assert_member(account, team)
    page = get_object_or_404(Page, link=page_link, team=team)

    if request.method == "POST":
        form = Form(request.POST)
        if form.is_valid():
            control.delete(account, page)
            return HttpResponseRedirect("/%s" % team.link)
    else:
        form = Form()
    cancel_url = "/%s/%s" % (team.link, page.link)
    args = { 
        "form" : form, "form_title" : _("PAGE_DELETE?"), 
        "form_subtitle" : page.name, "cancel_url" : cancel_url
    }
    return rtr(team, page.link, request, "site/form.html", args)
Exemple #37
0
def split_form(form):
    """
    move text_area fields to another form
    :param form: forms.Form object
    :return: two forms. First form without fields with Textarea widget
        and second form which contains fields with Textarea widget
    """
    if form.instance.id and not form.is_bound:
        text_area_form = CustomForm()
        text_area_form.is_bound = False
        text_area_form.prefix = form.prefix
        text_area_form.initial = QueryDict({}).copy()
        data = form.initial.copy()
        for k, v in form.fields.iteritems():
            if isinstance(v, CharField) and isinstance(v.widget, Textarea):
                text_area_form.fields.update({k: form.fields.pop(k)})
                if data.get(k):
                    text_area_form.initial.update({k: data.get(k)})
                    del data[k]
        form.data = data
        return (form, text_area_form)
    if form.is_bound:
        text_area_form = CustomForm()
        text_area_form.is_bound = True
        text_area_form.prefix = form.prefix
        text_area_form.data = QueryDict({}).copy()
        data = form.data.copy()
        for k, v in form.fields.iteritems():
            if isinstance(v, CharField) and isinstance(v.widget, Textarea):
                text_area_form.fields.update({k: form.fields.pop(k)})
                k = "%s-%s" % (form.prefix, k)
                if data.get(k):
                    text_area_form.data.update({k: data.get(k)})
                    del data[k]
        form.data = data
        return (form, text_area_form)
    else:
        text_area_form = CustomForm()
        for k, v in form.fields.iteritems():
            if isinstance(v, CharField) and isinstance(v.widget, Textarea):
                text_area_form.fields.update({k: form.fields.pop(k)})
        text_area_form.prefix = form.prefix
        return (form, text_area_form)
Exemple #38
0
def handle(request):
    user_pro = UserProfile.objects.all()[:4]
    blog_post = Post.objects.all()[:4]
    if request.method == 'POST':
        print('a form is posted')
        form_data = Form(request.POST)
        if form_data.is_valid():
            apply_name = request.POST["contactLname"]
            apply_email = request.POST["contactEmail"]
            apply_group = request.POST["selectList"]
            apply_msg = request.POST["contactMessage"]

        information = Handle(
            name=apply_name,
            email=apply_email,
            group=apply_group,
            intro=apply_msg,
        )
        information.save()
    return HttpResponseRedirect('/')
Exemple #39
0
def create_app_user(request):
    try:
        data = request.POST if request.POST else json.loads(request.body)
    except ValueError:
        return HttpResponseBadRequest()
    role = data.get('role')
    if not role or (role and role not in constants.USER_ROLES.keys()):
        return HttpResponseBadRequest(json.dumps('Role not supported'), content_type="application/json")
    form = Form()
    if role == constants.ROLES.student:
        form = StudentForm(data)
    elif role == constants.ROLES.teacher:
        form = TeacherForm(data)
    if form.is_valid():
        form.instance.is_active = True
        form.instance.set_password(form.cleaned_data['password'])
        form.instance.save()
        return HttpResponse(json.dumps({'token': Token.objects.last().key,
                                        'role': role}))
    else:
        return HttpResponseBadRequest(json.dumps(form.errors))
Exemple #40
0
def delete(request, team_link, blog_id):

    # get data
    team = team_control.get_or_404(team_link)
    account = get_object_or_404(Account, user=request.user)
    blog = get_object_or_404(Blog, team=team, id=blog_id)
    assert_member(account, team)

    if request.method == "POST":
        form = Form(request.POST)
        if form.is_valid():
            control.delete(account, blog)
            return HttpResponseRedirect("/%s/blog" % team.link)
    else:
        form = Form()
    args = {
        "form": form,
        "form_title": _("BLOG_DELETE?"),
        "form_subtitle": blog.name,
        "cancel_url": "/%s/blog" % team.link,
    }
    return rtr(team, "blog", request, "site/form.html", args)
Exemple #41
0
  def authorization_endpoint(request):
    auth_code_generator = AuthorizationCodeGenerator(missing_redirect_uri)

    try:
      auth_code_generator.validate(request)
    except AuthorizationException as authorization_exception:
      return auth_code_generator.make_error_redirect(authorization_exception)

    if request.method == 'GET':
      return render(request, authorization_template_name, {
          'form': Form(),
          'client': auth_code_generator.client,
          'scopes': auth_code_generator.valid_scope_objects,
          'form_action': update_parameters(
              authorization_endpoint_uri,
              auth_code_generator.get_request_uri_parameters(as_dict=True)),
        })

    if request.method == 'POST':
      form = Form(request)
      if form.is_valid() and request.POST.get('user_action') == 'Accept':
        return auth_code_generator.make_success_redirect()
      else:
        return auth_code_generator.make_error_redirect()
Exemple #42
0
def remove(request, **kwargs):
    team_link = kwargs.get("team_link")
    picture_id = kwargs["picture_id"]
    team = team_link and team_control.get_or_404(team_link) or None
    picture = get_object_or_404(Picture, id=picture_id)
    gallery = picture.gallery
    account = get_object_or_404(Account, user=request.user)
    prefix = team_link and "/%s" % team_link or ""
    url = "%s/gallery/list/%s" % (prefix, gallery.id)
    if request.method == "POST":
        form = Form(request.POST)
        if form.is_valid():
            control.remove(account, picture)
            return HttpResponseRedirect(url)
    else:
        form = Form()
    args = { 
        "form" : form, "form_title" : _("REMOVE_GALLERY_PICTURE"), 
        "cancel_url" : url
    }
    if team:
        return rtr(team, None, request, "site/form.html", args)
    else:
        return render_response(request, "site/form.html", args)
Exemple #43
0
def billingcycle_edit(request, id, template_name='membership/entity_edit.html'):
    cycle = get_object_or_404(BillingCycle, id=id)

    class Form(ModelForm):
        is_paid_forced = False
        class Meta:
            model = BillingCycle
            exclude = ('membership', 'start', 'end', 'sum', 'reference_number')

        def disable_fields(self):
            self.fields['is_paid'].required = False
            if cycle.amount_paid() >= cycle.sum and cycle.is_paid:
                self.fields['is_paid'].widget.attrs['disabled'] = 'disabled'
                self.is_paid_forced = True

        def clean_is_paid(self):
            if self.is_paid_forced:
                return cycle.is_paid
            else:
                return self.cleaned_data['is_paid']

    before = cycle.__dict__.copy() # Otherwise save() (or valid?) will change the dict, needs to be here
    if request.method == 'POST':
        form = Form(request.POST, instance=cycle)
        form.disable_fields()
        if form.is_valid():
            form.save()
            after = cycle.__dict__
            log_change(cycle, request.user, before, after)
            messages.success(request, unicode(_("Changes to billing cycle %s saved.") % cycle))
            return redirect('billingcycle_edit', id) # form stays as POST otherwise if someone refreshes
        else:
            messages.error(request, unicode(_("Changes to bill %s not saved.") % cycle))
    else:
        form =  Form(instance=cycle)
        form.disable_fields()
    logentries = bake_log_entries(cycle.logs.all())
    return render_to_response(template_name, {'form': form, 'cycle': cycle,
        'logentries': logentries},
        context_instance=RequestContext(request))
Exemple #44
0
def membership_edit(request, id, template_name='membership/membership_edit.html'):
    membership = get_object_or_404(Membership, id=id)

    class Form(ModelForm):
        class Meta:
            model = Membership
            exclude = ('person', 'billing_contact', 'tech_contact', 'organization')

        def clean_status(self):
            return membership.status
        def clean_approved(self):
            return membership.approved

        def disable_fields(self):
            self.fields['status'].required = False
            self.fields['status'].widget.attrs['disabled'] = 'disabled'
            self.fields['approved'].required = False
            self.fields['approved'].widget.attrs['disabled'] = 'disabled'

    if request.method == 'POST':
        if not request.user.has_perm('membership.manage_members'):
            return HttpResponseForbidden(_("Permission manage required"))
        form = Form(request.POST, instance=membership)
        before = membership.__dict__.copy()
        form.disable_fields()
        if form.is_valid():
            form.save()
            after = membership.__dict__
            log_change(membership, request.user, before, after)
            return redirect('membership_edit', id) # form stays as POST otherwise if someone refreshes
    else:
        form = Form(instance=membership)
        form.disable_fields()
    # Pretty print log entries for template
    logentries = bake_log_entries(membership.logs.all())
    return render_to_response(template_name, {'form': form,
        'membership': membership, 'logentries': logentries},
        context_instance=RequestContext(request))
Exemple #45
0
def vote(request, poll_id):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/")
    else:
        logged_in = True

    error = ""
    success = ""
    try:
        poll = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404

    username = request.user.username
    if (
        (not poll.is_allowed_voter(username))
        or poll.has_voted(username)
        or (poll.starts > datetime.datetime.now())
        or (poll.ends < datetime.datetime.now())
    ):
        return HttpResponseRedirect("/mypolls")

    poll_choices = Choice.objects.filter(poll=poll).order_by("id")
    choice_type = "radio"
    if poll.max_choices > 1:
        choice_type = "checkbox"

    vote_tag = ""
    vote_receipt_encrypted = ""

    if request.POST:
        form = Form(request.POST)
        if form.is_valid():
            choices = request.POST.getlist("choices")

            # Check that the submitted choices exist and belong to the poll
            for choice in choices:
                try:
                    c = Choice.objects.get(pk=choice, poll=poll)
                except Choice.DoesNotExist:
                    error = "The submitted choices are not valid choices of the poll"

                    # Check that the submitted choices are between min and max number of choices allowed for the poll
            if len(choices) > poll.max_choices:
                error = "You cannot vote for more than " + str(poll.max_choices) + " choices"
            if len(choices) < poll.min_choices:
                error = "You must vote for at least " + str(poll.min_choices) + " choices"
                if poll.max_choices == 1:  # a better error message for single choice polls
                    error = "You must select a choice"
            if list_has_duplicates(choices):
                error = "Each choice can be selected only once"

            if not error:
                # Construct a unique, random string to use as a vote tag
                while not vote_tag:
                    vote_tag = "".join(random.choice(string.ascii_uppercase + string.digits) for x in range(35))
                    try:
                        v = Vote.objects.get(tag=vote_tag)
                        vote_tag = ""
                    except Vote.DoesNotExist:  # our random string is unique so we can use it as a vote tag
                        # Encrypt the vote tag with user's public pgp key and sign it with the key of the system authority
                        gpg = GPG(gpgbinary=settings.GNUPGBINARY, gnupghome=settings.GNUPGHOME)
                        vote_receipt = """GPGVote: Vote Receipt
---------------------

You are voter: 
  %s

You voted for Poll:
  \'%s\'

Created by: 
  %s

Your Vote Tag is: %s
  
You made the following choices:""" % (
                            request.user.pgpkey.name + " <" + request.user.username + ">",
                            poll.question,
                            poll.creator.pgpkey.name + " <" + poll.creator.username + ">",
                            vote_tag,
                        )

                        for choice in choices:
                            choice = Choice.objects.get(pk=choice, poll=poll)
                            vote_receipt = vote_receipt + "\n  * %s" % choice.choice

                        vote_receipt_encrypted = gpg.encrypt(
                            vote_receipt,
                            request.user.pgpkey.fingerprint,
                            always_trust=True,
                            sign=settings.SYSTEM_KEY_FINGERPRINT,
                            passphrase=settings.SYSTEM_KEY_PASSWD,
                        )
                        # Create the actual vote records in database
                        for choice in choices:
                            vote = Vote(choice=Choice.objects.get(id=choice), tag=vote_tag)
                            vote.save()
                        poll.add_voter(voter=username, To="who_voted")
                        poll.save()

                success = "You have successfully voted for the poll"

    return render_to_response(
        "vote.html",
        {
            "user": username,
            "poll": poll,
            "choices": poll_choices,
            "choice_type": choice_type,
            "error": error,
            "success": success,
            "vote_receipt": vote_receipt_encrypted,
            "logged_in": logged_in,
        },
        context_instance=RequestContext(request),
    )
Exemple #46
0
 def render_form_actions(self):
     form = Form()
     form.opts = self.opts
     form.helper = DefaultFormHelper(self)
     form.helper.add_form_actions_only()
     return render_crispy_form(form)
Exemple #47
0
def payment_edit(request, id, template_name='membership/entity_edit.html'):
    payment = get_object_or_404(Payment, id=id)

    class SpeciallyLabeledModelChoiceField(ModelChoiceField):
        def label_from_instance(self, obj):
            return u"%s, %s" % (obj.membership, unicode(obj))

    class Form(ModelForm):
        class Meta:
            model = Payment
            #exclude = ('billingcycle')

        billingcycle = CharField(widget=HiddenInput(), required=False)
        #billingcycle = CharField(required=False)
        message = CharField(widget=Textarea(attrs={'rows': 5, 'cols': 60}))

        def disable_fields(self):
            if payment.billingcycle:
                self.fields['ignore'].required = False
                self.fields['ignore'].widget.attrs['disabled'] = 'disabled'
            self.fields['billingcycle'].required = False
            self.fields['billingcycle'].widget.attrs['disabled'] = 'disabled'
            self.fields['reference_number'].required = False
            self.fields['reference_number'].widget.attrs['disabled'] = 'disabled'
            self.fields['message'].required = False
            self.fields['message'].widget.attrs['disabled'] = 'disabled'
            self.fields['transaction_id'].required = False
            self.fields['transaction_id'].widget.attrs['disabled'] = 'disabled'
            self.fields['payment_day'].required = False
            self.fields['payment_day'].widget.attrs['disabled'] = 'disabled'
            self.fields['amount'].required = False
            self.fields['amount'].widget.attrs['disabled'] = 'disabled'
            self.fields['type'].required = False
            self.fields['type'].widget.attrs['disabled'] = 'disabled'
            self.fields['payer_name'].required = False
            self.fields['payer_name'].widget.attrs['disabled'] = 'disabled'
            self.fields['comment'].required = False

        def clean_ignore(self):
            if payment.billingcycle:
                return False
            else:
                return self.cleaned_data['ignore']
        def clean_billingcycle(self):
            return payment.billingcycle
        def clean_reference_number(self):
            return payment.reference_number
        def clean_message(self):
            return payment.message
        def clean_transaction_id(self):
            return payment.transaction_id
        def clean_payment_day(self):
            return payment.payment_day
        def clean_amount(self):
            return payment.amount
        def clean_type(self):
            return payment.type
        def clean_payer_name(self):
            return payment.payer_name

    before = payment.__dict__.copy() # Otherwise save() (or valid?) will change the dict, needs to be here
    oldcycle = payment.billingcycle
    if request.method == 'POST':
        form = Form(request.POST, instance=payment)
        form.disable_fields()
        if form.is_valid():
            form.save()
            newcycle = payment.billingcycle
            if oldcycle != newcycle:
                if oldcycle:
                    oldcycle.update_is_paid()
            if newcycle:
              newcycle.update_is_paid()
            after = payment.__dict__
            log_change(payment, request.user, before, after)
            messages.success(request, unicode(_("Changes to payment %s saved.") % payment))
            return redirect('payment_edit', id) # form stays as POST otherwise if someone refreshes
        else:
            messages.error(request, unicode(_("Changes to payment %s not saved.") % payment))
            return redirect('payment_edit', id) # form clears otherwise, this is a borderline acceptable hack
    else:
        form = Form(instance=payment)
        form.disable_fields()

    logentries = bake_log_entries(payment.logs.all())
    return render_to_response(template_name, {'form': form, 'payment': payment,
        'logentries': logentries},
        context_instance=RequestContext(request))