Beispiel #1
0
def user_setup(request):
    site_pk = _get_site_pk(request)
    current_site, administered_sites = _get_user_sites(request.user, site_pk)
    UserFormSet = formset_factory(UserForm, formset=BaseUserFormSet, extra=1)
    assigned_users = get_site_users(current_site)
    PageFormSet = formset_factory(
        _get_page_form_class(current_site),
        formset=BasePageFormSet, extra=1)
    page_formsets = {}
    if request.method == 'POST':
        user_formset = UserFormSet(request.POST, request.FILES,
                                   prefix='user-roles')
        user_pages = {}
        if user_formset.is_valid():
            submitted_users = {}
            page_formsets_have_errors = False
            for user_form in user_formset.forms:
                user = user_form.cleaned_data.get('user', None)
                role = user_form.cleaned_data.get('role', None)
                if user is None and role is None:
                    continue
                submitted_users[user] = role
                if not role.is_site_wide and _formset_available(request, user):
                    page_formset = PageFormSet(
                        request.POST, request.FILES,
                        prefix=_get_page_formset_prefix(user))
                    if page_formset.is_valid():
                        user_pages[user] = _get_user_pages(page_formset)
                    else:
                        page_formsets[unicode(user.pk)] = page_formset
                        page_formsets_have_errors = True
            if not page_formsets_have_errors:
                _update_site_users(request, current_site, assigned_users,
                                   submitted_users, user_pages)
                return _get_redirect(request, site_pk)

    else:
        initial_data = [
            {'user': user, 'role': role, 'current_site': current_site}
            for user, role in assigned_users.iteritems()]
        user_formset = UserFormSet(initial=initial_data, prefix='user-roles')

    all_roles = Role.objects.all()
    role_pk_to_site_wide = dict((role.pk, role.is_site_wide) for role in all_roles)
    # so that the empty form template doesn't have an 'assign pages' link
    role_pk_to_site_wide[None] = True
    context = {
        'opts': {'app_label': 'cmsroles'},
        'app_label': 'Cmsroles',
        'administered_sites': administered_sites,
        'current_site': current_site,
        'user_formset': user_formset,
        'page_formsets': page_formsets,
        'user': request.user,
        'role_pk_to_site_wide_js': [
            (role.pk, 'true' if role.is_site_wide else 'false')
            for role in all_roles],
        'role_pk_to_site_wide': role_pk_to_site_wide}
    return render_to_response('admin/cmsroles/user_setup.html', context,
                              context_instance=RequestContext(request))
Beispiel #2
0
    def test_formset_iteration(self):
        # Regression tests for #16455 -- formset instances are iterable
        ChoiceFormset = formset_factory(Choice, extra=3)
        formset = ChoiceFormset()

        # confirm iterated formset yields formset.forms
        forms = list(formset)
        self.assertEqual(forms, formset.forms)
        self.assertEqual(len(formset), len(forms))

        # confirm indexing of formset
        self.assertEqual(formset[0], forms[0])
        try:
            formset[3]
            self.fail('Requesting an invalid formset index should raise an exception')
        except IndexError:
            pass

        # Formets can override the default iteration order
        class BaseReverseFormSet(BaseFormSet):
            def __iter__(self):
                return reversed(self.forms)

            def __getitem__(self, idx):
                return super(BaseReverseFormSet, self).__getitem__(len(self) - idx - 1)

        ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3)
        reverse_formset = ReverseChoiceFormset()

        # confirm that __iter__ modifies rendering order
        # compare forms from "reverse" formset with forms from original formset
        self.assertEqual(str(reverse_formset[0]), str(forms[-1]))
        self.assertEqual(str(reverse_formset[1]), str(forms[-2]))
        self.assertEqual(len(reverse_formset), len(forms))
Beispiel #3
0
def send_meeting(request):
    if request.method == "POST":
        form = MeetingChangeForm(request.POST)
        formset = formset_factory(ReportChangeForm)(request.POST)
        if form.is_valid() and formset.is_valid():
            meeting = form.save()
            for report_form in formset:
                report = report_form.save(commit=False)
                report.meeting = meeting
                report.save()
            for user in User.objects.all():
                user.email_user(
                    'New HEP group meeting at %s'%meeting.meeting_date,
                    """This message was auto generated because of new HEP group meeting, please don't reply on it.

If you wish to report, send the email with your topic to Volodymyr Klavdiienko([email protected]).
Then, after Volodymyr will add your report to meeting you will be able to attach file in your profile page(http://exp-hep.univ.kiev.ua/members/profile).
                    """,
                    '[email protected]	'
                )
            return HttpResponseRedirect(reverse('members:meeting_change'))
    else:
        form = MeetingChangeForm()
        formset = formset_factory(ReportChangeForm)
    return render(request, 'members/meeting_change.html', {'form': form, 'formset': formset, })
Beispiel #4
0
    def test_more_initial_than_max_num(self):
        # More initial forms than max_num will result in only the first max_num of
        # them to be displayed with no extra forms.

        initial = [
            {'name': 'Gin Tonic'},
            {'name': 'Bloody Mary'},
            {'name': 'Jack and Coke'},
        ]
        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2)
        formset = LimitedFavoriteDrinkFormSet(initial=initial)
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" value="Bloody Mary" id="id_form-1-name" /></td></tr>""")

        # One form from initial and extra=3 with max_num=2 should result in the one
        # initial form and one extra.
        initial = [
            {'name': 'Gin Tonic'},
        ]
        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=2)
        formset = LimitedFavoriteDrinkFormSet(initial=initial)
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""")
def books_count(request, profile_id):
    if request.method == "POST":
        form = BooksCountForm(request.POST, request.FILES)
        if form.is_valid():
            a = form.save()
            a.psrn = profile_id
            numberOfBooks = form.cleaned_data.get("booksPublished")
            a.save()

        form = FunkyBooksForm(request.POST, request.FILES)
        FunkyFormSet = formset_factory(FunkyBooksForm, extra=numberOfBooks, max_num=numberOfBooks)
        formset = FunkyFormSet()

        args = {}
        args.update(csrf(request))
        args["formset"] = formset
        args["form"] = form
        args["profile_id"] = profile_id
        return render_to_response("books.html", args)
    else:
        FunkyFormSet = formset_factory(FunkyForm, extra=10, max_num=10)
        formset = FunkyFormSet()
        form = FunkyForm()
    args = {}
    args.update(csrf(request))

    args["formset"] = formset
    args["form"] = form
    args["profile_id"] = profile_id
    return render_to_response("books_count.html", args)
def courses(request, profile_id):
    if request.method == "POST":
        FunkyFormSet = formset_factory(FunkyCourseForm, extra=3, max_num=3)
        formset = FunkyFormSet(request.POST)
        form = FunkyCourseForm(request.POST, request.FILES)
        for f_form in formset:
            if f_form.is_valid():
                # found_user = Profile.objects.get(psrn=profile_id)
                a = f_form.save()
                a.psrn = profile_id
                a.save()

        raForm = ResearchAgencyCountForm()
        args = {}
        args.update(csrf(request))
        args["form"] = raForm
        args["profile_id"] = profile_id
        return render_to_response("researchAgency_count.html", args)
        # return HttpResponseRedirect('/all/')
    else:
        FunkyFormSet = formset_factory(FunkyCourseForm, extra=10, max_num=10)
        formset = FunkyFormSet()
        form = FunkyCourseForm()
    args = {}
    args.update(csrf(request))

    args["formset"] = formset
    args["form"] = form
    args["profile_id"] = profile_id
    return render_to_response("courses.html", args)
Beispiel #7
0
def profile_settings(request):
    """
    Allows a user to update their own profile.
    """
    user = request.user

    has_skills = Skill.objects.count() > 0
    has_roles = Role.objects.count() > 0

    SkillFormSet = formset_factory(SkillForm, formset=BaseSkillFormSet)

    user_skills = UserSkill.objects.filter(user=user).order_by('skill__name')
    skill_data = [{'skill': s.skill, 'proficiency': s.proficiency}
                    for s in user_skills]

    LinkFormSet = formset_factory(LinkForm, formset=BaseLinkFormSet)

    user_links = UserLink.objects.filter(user=user).order_by('anchor')
    link_data = [{'anchor': l.anchor, 'url': l.url}
                    for l in user_links]

    if request.method == 'POST':
        form = ProfileForm(request.POST, user=user)
        skill_formset = SkillFormSet(request.POST, prefix='skill')
        link_formset = LinkFormSet(request.POST, prefix='link')

        if form.is_valid() and skill_formset.is_valid() and link_formset.is_valid():
            # Save user info
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.bio = form.cleaned_data['bio']
            user.roles = form.cleaned_data['roles']

            user.save()

            save_skills(request, user, skill_formset)
            save_links(request, user, link_formset)

            user_links = UserLink.objects.filter(user=user)
            match_link_to_brand(user_links)

            site = get_current_site(request)
            messages.success(request,
                _('Your {} profile has been updated.'.format(site.name)))

    else:
        form = ProfileForm(user=user)
        skill_formset = SkillFormSet(initial=skill_data, prefix='skill')
        link_formset = LinkFormSet(initial=link_data, prefix='link')


    context = {
        'form': form,
        'skill_formset': skill_formset,
        'link_formset': link_formset,
        'has_skills': has_skills,
        'has_roles': has_roles,
    }

    return render(request, 'accounts/profile_settings.html', context)
def createPapers(request, profile_id):
    if request.method == "POST":

        FunkyFormSet = formset_factory(FunkyForm, extra=3, max_num=3)
        formset = FunkyFormSet(request.POST)
        form = FunkyForm(request.POST, request.FILES)
        for f_form in formset:
            if f_form.is_valid():
                # found_user = Profile.objects.get(psrn=profile_id)
                a = f_form.save()
                a.psrn = profile_id
                a.save()

        bform = BooksCountForm()
        args = {}
        args.update(csrf(request))
        args["form"] = bform
        args["profile_id"] = profile_id
        return render_to_response("books_count.html", args)
    else:
        FunkyFormSet = formset_factory(FunkyForm, extra=10, max_num=10)
        formset = FunkyFormSet()
        form = FunkyForm()
    args = {}
    args.update(csrf(request))

    args["formset"] = formset
    args["form"] = form
    args["profile_id"] = profile_id
    return render_to_response("createPapers.html", args)
Beispiel #9
0
    def get_context_data(self, **kwargs):
        (host_eg, guest_eg) = self.get_egs()

        if host_eg:
            if not host_eg.group.is_admin(self.request.user):
                raise PermissionDenied

        kwargs['host_eg'] = host_eg

        context = super(EventHostInviteView, self).get_context_data(**kwargs)

        (dates, day_initial, meal_initial) = self.get_meals(host_eg, guest_eg, 'manage' in self.request.GET)

        day_factory = formset_factory(EventInviteDayForm, extra=0)
        meal_factory = formset_factory(EventInviteMealForm, extra=0)
        day_formset = day_factory(prefix='days', initial=day_initial)
        meal_formset = meal_factory(prefix='meals', initial=meal_initial)

        dates = self.get_meal_dates(dates, day_formset, meal_formset)

        context['invite_dates'] = dates
        context['day_formset'] = day_formset
        context['meal_formset'] = meal_formset
        context['host_eg'] = host_eg
        context['guest_eg'] = guest_eg
        context['manage'] = 'manage' in self.request.GET
        return context
Beispiel #10
0
def redirectView(request):
    MemberFormSet = formset_factory(wraps(reloadForm)(partial(reloadForm)))
    formTree = ProductSelectionForm(request.POST or None)
    if request.method == 'POST':
         #as I use formsets this is mandatory
        formset = MemberFormSet(request.POST)
        #make sure every form is validMemberFormSet = formset_factory(wraps(PostFormEFactor)(partial(PostFormEFactor)))
        if formset.is_valid():
            #start retrieving formset data, which is all filter data except FancyTree
            for f in formset:
                cd = f.cleaned_data

                print("selection:")
                selection = cd.get('selection')
                print(selection)
                #

                #start getting some form skeletons now!
                ArticleFormSet = formset_factory(PostFormEFactor)
                formset = ArticleFormSet()
                formset = formset_factory(wraps(PostFormEFactor)(partial(PostFormEFactor)), extra=1)
                #updata dictionary for filter options: form skeletons

                selectionForm = formset_factory(wraps(reloadForm)(partial(reloadForm)), extra=1)
                dict = ({'selectionForm': selectionForm})
                #now send some other forms to the filter interface
                dict.update({'formset':formset})
                dict.update({'formTree': formTree})
                #send signal for popup
                popup = 1
                dict.update({'popup': popup})
                return render(request,"ExioVisuals/distribution.html", dict)
Beispiel #11
0
def new_print_annotation(request, print_id):
    print_pid = '%s:%s' % (PID_PREFIX, print_id)
    from .forms import AnnotationForm, PersonForm, InscriptionForm
    PersonFormSet = formset_factory(PersonForm)
    InscriptionFormSet = formset_factory(InscriptionForm)
    if request.method == 'POST':
        form = AnnotationForm(request.POST)
        person_formset = PersonFormSet(request.POST, prefix='people')
        inscription_formset = InscriptionFormSet(request.POST, prefix='inscriptions')
        if form.is_valid() and person_formset.is_valid() and inscription_formset.is_valid():
            if request.user.first_name:
                annotator = u'%s %s' % (request.user.first_name, request.user.last_name)
            else:
                annotator = u'%s' % request.user.username
            annotation = Annotation.from_form_data(print_pid, annotator, form.cleaned_data, person_formset.cleaned_data, inscription_formset.cleaned_data)
            try:
                response = annotation.save_to_bdr()
                logger.info('%s added annotation %s for %s' % (request.user.username, response['pid'], print_id))
                return HttpResponseRedirect(reverse('specific_print', kwargs={'print_id': print_id}))
            except Exception as e:
                logger.error('%s' % e)
                return HttpResponseServerError('Internal server error. Check log.')
    else:
        inscription_formset = InscriptionFormSet(prefix='inscriptions')
        person_formset = PersonFormSet(prefix='people')
        form = AnnotationForm()

    image_link = zoom_viewer_url(print_pid)
    return render(request, 'rome_templates/new_annotation.html',
            {'form': form, 'person_formset': person_formset, 'inscription_formset': inscription_formset, 'image_link': image_link})
Beispiel #12
0
def schema_properties_mend(request, graph_slug, element_type):
    graph = get_object_or_404(Graph, slug=graph_slug)
    if not 'schema_changed_props' in request.session and \
            not 'schema_deleted_props' in request.session:
        return redirect(reverse("schema_edit", args=[graph.slug]))
    changed_props = request.session.get('schema_changed_props', [])
    deleted_props = request.session.get('schema_deleted_props', [])
    ElementTypeChangedFormSet = formset_factory(ElementTypeChangedForm,
                                                extra=0)
    ElementTypeDeletedFormSet = formset_factory(ElementTypeDeletedForm,
                                                extra=0)
    changed_formset = ElementTypeChangedFormSet(initial=changed_props,
                                                prefix='changed')
    deleted_formset = ElementTypeDeletedFormSet(initial=deleted_props,
                                                prefix='deleted')
    if request.POST:
        data = request.POST.copy()
        if changed_props:
            changed_formset = ElementTypeChangedFormSet(data=data,
                                                        initial=changed_props,
                                                        prefix='changed')
        if deleted_props:
            deleted_formset = ElementTypeDeletedFormSet(data=data,
                                                        initial=deleted_props,
                                                        prefix='deleted')
        fixed = False
        if changed_props and deleted_props:
            if changed_formset.is_valid() and deleted_formset.is_valid():
                for cdata in changed_formset.cleaned_data:
                    mend_schema_property(element_type, cdata['option'],
                                         cdata['key'], cdata['new_key'])
                for cdata in deleted_formset.cleaned_data:
                    mend_schema_property(element_type, cdata['option'],
                                         cdata['key'])
                request.session.pop('schema_changed_props')
                request.session.pop('schema_deleted_props')
                fixed = True
        elif changed_props and changed_formset.is_valid():
            for cdata in changed_formset.cleaned_data:
                mend_schema_property(element_type, cdata['option'],
                                     cdata['key'], cdata['new_key'])
            request.session.pop('schema_changed_props')
            fixed = True
        elif deleted_props and deleted_formset.is_valid():
            for cdata in deleted_formset.cleaned_data:
                mend_schema_property(element_type, cdata['option'],
                                     cdata['key'])
            request.session.pop('schema_deleted_props')
            fixed = True
        if fixed:
            return redirect(reverse("schema_edit", args=[graph.slug]))
    return render_to_response('schemas_properties_mend.html',
                              {"graph": graph,
                               "item_type_label": _("Type"),
                               "element_type": element_type,
                               "changed_formset": changed_formset,
                               "deleted_formset": deleted_formset,
                               "changed_props": changed_props,
                               "deleted_props": deleted_props},
                              context_instance=RequestContext(request))
    def __init__(self, *args, **kwargs):
        super(RPMOverrideFormView, self).__init__(*args, **kwargs)

        self.checkbox_form_factory = formset_factory(ComposeRPMDisableForm, extra=0)
        self.override_form_factory = formset_factory(OverrideRPMForm, extra=0)
        self.variant_form_factory = formset_factory(VariantArchForm, extra=1)
        self.override_v_form_factory = formset_factory(OverrideRPMForm, extra=0)
def researchAgency(request, profile_id):
    if request.method == "POST":
        FunkyFormSet = formset_factory(FunkyResearchAgencyForm, extra=3, max_num=3)
        formset = FunkyFormSet(request.POST)
        form = FunkyResearchAgencyForm(request.POST, request.FILES)
        for f_form in formset:
            if f_form.is_valid():
                # found_user = Profile.objects.get(psrn=profile_id)
                a = f_form.save()
                a.psrn = profile_id
                a.save()

        # form = FunkyForm(request.POST,request.FILES)
        # FunkyFormSet = formset_factory(FunkyBooksForm,extra=numberOfBooks, max_num=numberOfBooks)
        # formset = FunkyFormSet()

        # args = {}
        # args.update(csrf(request))
        # args['form'] = bform
        # args['profile_id'] = profile_id
        # return render_to_response('books_count.html',args)
        return HttpResponseRedirect("/all/")
    else:
        FunkyFormSet = formset_factory(FunkyResearchAgencyForm, extra=10, max_num=10)
        formset = FunkyFormSet()
        form = FunkyResearchAgencyForm()
    args = {}
    args.update(csrf(request))

    args["formset"] = formset
    args["form"] = form
    args["profile_id"] = profile_id
    return render_to_response("researchAgency.html", args)
def researchAgency_count(request, profile_id):
    if request.method == "POST":
        form = ResearchAgencyCountForm(request.POST, request.FILES)
        if form.is_valid():
            a = form.save()
            a.psrn = profile_id
            numberOfGrants = form.cleaned_data.get("grants")
            print numberOfGrants
            a.save()

        form = FunkyCourseForm(request.POST, request.FILES)
        FunkyFormSet = formset_factory(FunkyResearchAgencyForm, extra=numberOfGrants, max_num=numberOfGrants)
        formset = FunkyFormSet()

        args = {}
        args.update(csrf(request))
        args["formset"] = formset
        args["form"] = form
        args["profile_id"] = profile_id
        return render_to_response("researchAgency.html", args)
    else:
        FunkyFormSet = formset_factory(FunkyForm, extra=10, max_num=10)
        formset = FunkyFormSet()
        form = FunkyForm()
    args = {}
    args.update(csrf(request))

    args["formset"] = formset
    args["form"] = form
    args["profile_id"] = profile_id
    return render_to_response("researchAgency_count.html", args)
Beispiel #16
0
 def __init__(self, request):
     self.batchpath = request.GET.get('batchpath') or request.POST.get('batchpath') or DEFAULT_BATCH_PATH
     self.batch = Batch(self.batchpath)
     self.ArtistFormSet = formset_factory(ArtistForm, formset=DataFormSet, extra=0)
     self.LabelFormSet = formset_factory(LabelForm, formset=DataFormSet, extra=0)
     self.ReleaseFormSet = formset_factory(ReleaseForm, formset=DataFormSet, extra=0)
     self.bad_deliveries = list(self.batch.bad_deliveries())
Beispiel #17
0
    def change_view(self, request, object_id, form_url='', extra_context=None):
        if request.method == 'POST':
            res = formset_factory(RadioElementForm,
                                  formset=RadioElementFormSet)
            rs = res(request.POST)
            rs.save()
            return HttpResponseRedirect(reverse('admin:geoforms_radioelementmodel_changelist'))
        else:
            initial_data = []
            question_data = {'question': []}
            radioelement = RadioElementModel.objects.get(id = object_id)

            for i, lang in enumerate(settings.LANGUAGES):
                html = getattr(radioelement,'html_%s' % lang[0])
                if html == None:
                    html = getattr(radioelement,'html_%s' % settings.LANGUAGES[0][0])
                soup = BeautifulSoup(html)
                question_data['question'].append(soup.p.text)
                if soup.find(attrs={'data-random': 'true'}):
                    question_data['randomize'] = True
                labels = soup.find_all('label')
                for j, label in enumerate(labels):
                    if i == 0:
                        initial_data.append({u'label': [label.text.strip()]})
                    else:
                        initial_data[j]['label'].append(label.text.strip())

            return super(RadioElementAdmin, self).change_view(request,
                                                              object_id,
                                                              form_url = '',
                                                              extra_context = {
                                                                'current_app': self.admin_site.name,
                                                                'form': QuestionForm(initial = question_data),
                                                                'formset': formset_factory(RadioElementForm,
                                                                                           extra = 0)(initial = initial_data)})
def buildForm(resource={}):
    fields = {}
    try:
        fields = {'name': resource[str(ns['skos']['prefLabel'])][0]['value']}
    except:
        pass
    #TODO: find better way to make empty form fields when there is no data
    try:
        fields['firstName'] = resource[str(ns['foaf']['givenName'])][0]['value'] 
    except:
        pass
    try:
        fields['lastName']= resource[str(ns['foaf']['familyName'])][0]['value']
    except:
        pass

    altLabel = str(ns['skos']['altLabel'])
    hiddenLabel = str(ns['skos']['hiddenLabel'])
    initial = []

    if (altLabel in resource):
        for variant in resource[altLabel]:
                initial.append({'variant':variant['value'], 'isHidden':False})

    if (hiddenLabel in resource):
        for variant in resource[hiddenLabel]:
            initial.append({'variant':variant['value'], 'isHidden':True})

        VariantFormSet = formset_factory(VariantForm, extra=0, formset=BaseVariantFormSet)
    else:
        VariantFormSet = formset_factory(VariantForm, extra=1, formset=BaseVariantFormSet)
    variantForm =  VariantFormSet(initial = initial)
    
    form = ResourceForm(fields)
    return {'form':form, 'variants':variantForm}
Beispiel #19
0
    def test_more_initial_than_max_num(self):
        # More initial forms than max_num now results in all initial forms
        # being displayed (but no extra forms).  This behavior was changed
        # from max_num taking precedence in the patch for #20084

        initial = [
            {'name': 'Gin Tonic'},
            {'name': 'Bloody Mary'},
            {'name': 'Jack and Coke'},
        ]
        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2)
        formset = LimitedFavoriteDrinkFormSet(initial=initial)
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))
        self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary" /></td></tr>
<tr><th><label for="id_form-2-name">Name:</label></th><td><input id="id_form-2-name" name="form-2-name" type="text" value="Jack and Coke" /></td></tr>""")

        # One form from initial and extra=3 with max_num=2 should result in the one
        # initial form and one extra.
        initial = [
            {'name': 'Gin Tonic'},
        ]
        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=2)
        formset = LimitedFavoriteDrinkFormSet(initial=initial)
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""")
Beispiel #20
0
    def test_max_num_zero(self):
        # If max_num is 0 then no form is rendered at all, regardless of extra,
        # unless initial data is present. (This changed in the patch for bug
        # 20084 -- previously max_num=0 trumped initial data)

        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=0)
        formset = LimitedFavoriteDrinkFormSet()
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertEqual('\n'.join(form_output), "")

        # test that initial trumps max_num

        initial = [
            {'name': 'Fernet and Coke'},
            {'name': 'Bloody Mary'},
        ]
        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=0)
        formset = LimitedFavoriteDrinkFormSet(initial=initial)
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))
        self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" name="form-0-name" type="text" value="Fernet and Coke" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary" /></td></tr>""")
Beispiel #21
0
def invitation_inscription(request):
    #TODO
    # A REVOIR CRADE
    user = request.user
    if user.get_profile().Finished  == False :
        Caracs = Carac.objects.all()
        Skills = Skill.objects.all()
        Items = Item.objects.all()
        initial = []
        for carac in Caracs :
            initial.append({'carac': carac.Nom,'id':carac.id})
        CaracFormSet = formset_factory(CaracForm, extra=0)
        CaracFormSet = CaracFormSet(prefix='carac',initial=initial)
        initial = []
        # algo de skills a revoir pour le classement
        for skill in Skills :
            initial.append({'skill': skill.Nom,'id':skill.id})
        SkillFormSet = formset_factory(SkillForm, extra=0)
        SkillFormSet = SkillFormSet(prefix='skill',initial=initial)
        initial = []
        for item in Items :
            initial.append({'item': item.Nom,'id':item.id})
        ItemFormSet = formset_factory(ItemForm, extra=0)
        ItemFormSet = ItemFormSet(prefix='item',initial=initial)
        
        print CaracFormSet.management_form
        formJack = JackRegisterForm()
        return render_to_response('invitinscription.html',{"CaracFormSet":CaracFormSet,'SkillFormSet':SkillFormSet,'ItemFormSet':ItemFormSet,'formJack':formJack},RequestContext(request))
    else :
        return HttpResponseRedirect('../')
Beispiel #22
0
    def post(self, request, pk, **kwargs):
        self.object = self.get_object()
        ruleset_id = self.object.id
        class RuleFormWithRuleset(RuleForm):
            def clean(self):
                # HACK! How to add ruleset info to extra fields in a meaningful way?
                cleaned_data = super(RuleForm, self).clean()
                if "ruleset" not in cleaned_data and len(self._errors.get("ruleset", [])) == 1 and self._errors["ruleset"][0] == u"This field is required.":
                    cleaned_data["ruleset"] = RuleSet.objects.get(pk=ruleset_id)
                    del self._errors["ruleset"]
                for field in ("insert", "remove", "where"):
                    self.cleaned_data[field] = _normalize_quotes(self.cleaned_data[field])
                return cleaned_data
            
        ruleset_form = modelform_factory(RuleSet)(request.POST, instance=self.object)
        if ruleset_form.is_valid():
            ruleset_form.save()
        
        formset = formset_factory(RuleFormWithRuleset, formset=BaseModelFormSet, can_delete=True)
        formset.model = Rule
        formset = formset(request.POST, request.FILES, queryset=self.object.rules.all())
        if formset.is_valid():
            formset.save()
            formset = formset_factory(RuleForm, formset=BaseModelFormSet, can_delete=True)
            formset.model = Rule
            formset = formset(queryset=self.object.rules.all())


        return self.render_to_response(self.get_context_data(formset=formset, ruleset_form=ruleset_form))
Beispiel #23
0
def submit_recipe(request):
  '''
  Handle a submitted recipe form
  '''
  print request.POST
  HoeveelheidFormset = formset_factory(HoeveelheidForm)
  ImageFormset = formset_factory(ImageForm)
  if request.method=='POST' and 'submit_recipe' in request.POST:
    recept_form = ReceptForm(request.POST, request.FILES)
    hoeveelheid_formset = HoeveelheidFormset(request.POST)
    image_formset = ImageFormset(request.POST, request.FILES, prefix="image_form")
    # Check if the forms are valid, and add the recipe. Redirect to home page
    # afterwards
    if recept_form.is_valid():
      if hoeveelheid_formset.is_valid():
        data = recept_form.cleaned_data
        hoeveelheid_data = hoeveelheid_formset.cleaned_data
        if request.POST['pk']=="-1":
          recept = Recept()
        else:
          recept = Recept.objects.get(pk=request.POST['pk'])
          # Remove present doel and hoeveelheden, to avoid duplicates, wrong information
          Hoeveelheid.objects.filter(recept=recept).delete()
          for doel in recept.doel.all():
            recept.doel.remove(doel)
        recept.naam = data['naam']
        recept.user = request.user
        recept.bereidingstijd = data['bereidingstijd']
        recept.aantal_personen = data['aantal_personen']
        recept.bereiding = data['bereiding']
        recept.seizoen = data['seizoen']
        recept.vegetarisch = data['vegetarisch']
        
        # Saving the recipe, before adding relations
        recept.save()
        
        if image_formset.is_valid():
          for (i, f) in enumerate(request.FILES.keys()):
            foto = Foto.objects.create(image=request.FILES[f], naam=data['naam']+'image_' + str(i))
            recept.fotos.add(foto)
        if 'doel' in request.POST:
          recept.doel.add(request.POST['doel'])
        for h_data in hoeveelheid_data:
          try:
            h = Hoeveelheid.objects.create(hoeveelheid=h_data['hoeveelheid'],
                                           recept=recept,
                                           ingredient=h_data['ingredient'])
          except:
            continue
            
        return redirect('/')
      else:
        # TODO: Return some useful error message.
        pass
  else:
    recept_form = ReceptForm()
    hoeveelheid_formset = HoeveelheidFormset()
    image_formset = ImageFormset(prefix="image_form")
  return toevoegen(request, recept_form=recept_form, hoeveelheid_formset=hoeveelheid_formset, image_formset=image_formset)
Beispiel #24
0
def recipe_edit(request, recipe_id):
    
    recipe = get_object_or_404(Recipe, pk=recipe_id)
    for ingredient in recipe.ingredient_set.all():
        get_object_or_404(Ingredient, pk=ingredient.id)
    for instruction in recipe.instruction_set.all():
        get_object_or_404(Instruction, pk=instruction.id)
    
     # if this is a POST request we need to process the form data
    ingredientformset = formset_factory(AddIngredientForm, can_delete = True, extra = 0)
    instructionformset = formset_factory(AddInstructionForm, can_delete = True, extra = 0)
    extraingredientformset = formset_factory(AddIngredientForm, can_delete = True)
    extrainstructionformset = formset_factory(AddInstructionForm, can_delete = True)


    
    if request.method == "POST":
        recipeform = AddRecipeForm(request.POST, instance=recipe)
        ingrformset = ingredientformset(request.POST, request.FILES, prefix = 'ingredients', initial=recipe.ingredient_set.all().values())
        instrucformset = instructionformset(request.POST, request.FILES, prefix = 'instructions', initial=recipe.instruction_set.all().values())
        extraingrformset = extraingredientformset(request.POST, request.FILES, prefix = 'extra_ingredients')
        extrainstrucformset = extrainstructionformset(request.POST, request.FILES, prefix = 'extra_instructions')
        
        if recipeform.is_valid() and ingrformset.is_valid() and instrucformset.is_valid() and extraingrformset.is_valid() and extrainstrucformset.is_valid():
            # Prepare the ingredient and instruction models, but don't commit it to the database just yet.
            # Add the recipe ForeignKey by saving the secondary form we setup
            savedrecipe = recipeform.save()
            
            for ingrform in ingrformset:
                ingredient = ingrform.save(commit=False)
                ingredient.recipe = savedrecipe
                ingredient.save()
            
            for ingrform in extraingrformset:
                ingredient = ingrform.save(commit=False)
                ingredient.recipe = savedrecipe
                ingredient.save()
            
            for instrucform in instrucformset:
                instruction = instrucform.save(commit = False)
                instruction.recipe = savedrecipe
                instruction.save()
                
            for instrucform in extrainstrucformset:
                instruction = instrucform.save(commit = False)
                instruction.recipe = savedrecipe
                instruction.save()
            
            # redirect to a new URL:
            return HttpResponseRedirect(reverse('addrecipe:thank', args=(savedrecipe.id,)))
        
    else:
        recipeform = AddRecipeForm(instance=recipe)
        ingrformset = ingredientformset(prefix = 'ingredients', initial=recipe.ingredient_set.all().values())
        instrucformset = instructionformset(prefix = 'instructions', initial=recipe.instruction_set.all().values())
        extraingrformset = extraingredientformset(prefix = 'extra_ingredients')
        extrainstrucformset = extrainstructionformset(prefix = 'extra_instructions')
        
    return render(request, 'addrecipe/post_edit.html', {'recipeform': recipeform, 'ingrformset' : ingrformset, 'instrucformset' : instrucformset , 'extra_ingredients' : extraingrformset, 'extra_instructions' : extrainstrucformset, 'recipe' : recipe})    
Beispiel #25
0
def subscribe(request):
    if request.method != 'POST':
        response = HttpResponseNotAllowed('Method not allowed')
        response['Accept'] = 'POST'
        return response

    if not request.user.is_authenticated():
        return redirect(reverse('login') + '?from=bookmarklet')

    if 'source' in request.POST and 'html' in request.POST:
        SubscriptionFormSet = formset_factory(SubscriptionForm, extra=0)

        xml = lxml.html.fromstring(request.POST['html'])
        xml.make_links_absolute(request.POST['source'])  # lxml FTW
        links = xml.xpath(('//link[@type="application/atom+xml" or '
                           '@type="application/rss+xml"]'))
        parsed_links = []
        for link in links:
            parsed_links.append({
                'url': link.get('href'),
                'name': link.get('title'),
                'subscribe': True,
            })
        formset = SubscriptionFormSet(initial=parsed_links)
        cats = [(str(c.pk), c.name) for c in request.user.categories.all()]
        for form in formset:
            form.fields['category'].choices = cats
        return render(request, 'feeds/bookmarklet_subscribe.html',
                      {'formset': formset, 'source': request.POST['source']})

    else:
        response = manual_csrf_check(request)
        if response is not None:
            return response

        SubscriptionFormSet = formset_factory(SubscriptionForm, extra=0)
        formset = SubscriptionFormSet(data=request.POST)
        cats = [(str(c.pk), c.name) for c in request.user.categories.all()]
        for form in formset:
            form.fields['category'].choices = cats
        if formset.is_valid():
            created = 0
            for form in formset:
                if form.cleaned_data['subscribe']:
                    category = request.user.categories.get(
                        pk=form.cleaned_data['category'],
                    )
                    category.feeds.create(name=form.cleaned_data['name'],
                                          url=form.cleaned_data['url'])
                    created += 1
            if created == 1:
                message = _('1 feed has been added')
            else:
                message = _('%s feeds have been added') % created
            messages.success(request, message)
            return redirect(reverse('feeds:home'))
        else:
            return render(request, 'feeds/bookmarklet_subscribe.html',
                          {'formset': formset})
Beispiel #26
0
    def post(self,request,contact_id):
        

        class RequiredFormSet(BaseFormSet):
            def __init__(self, *args, **kwargs):
                super(RequiredFormSet, self).__init__(*args, **kwargs)
                for form in self.forms:
                    form.empty_permitted = False


        tipo_alarma = int(self.request.POST['tipo_alarma'])
        

        if tipo_alarma==1 :
            contact = get_object_or_404(AlarmaHumo, pk=contact_id)
            alarm_form_set = formset_factory(AlarmaHumoForm, extra=0, max_num=10, formset=RequiredFormSet)
        elif tipo_alarma==2:
            contact = get_object_or_404(AlarmaEstado, pk=contact_id)
            alarm_form_set = formset_factory(AlarmaEstado2Form, extra=0, max_num=10, formset=RequiredFormSet)
        elif tipo_alarma==3:
            contact = get_object_or_404(AlarmaAcceso, pk=contact_id)
            alarm_form_set = formset_factory(AlarmaAccesoForm, extra=0, max_num=10, formset=RequiredFormSet)    
        elif tipo_alarma==4:
            contact = get_object_or_404(AlarmaEstado, pk=contact_id)
            alarm_form_set = formset_factory(AlarmaEstadoForm, extra=0, max_num=10, formset=RequiredFormSet)
        
        alarma_formset = alarm_form_set(request.POST, request.FILES, instance=contact)
        sensor_id = self.request.POST.get('sensor_select',False)
        nivel_id = self.request.POST.get('nivel_select',False)

        
        if alarma_formset.is_valid():
            if sensor_id != '0':
                set_form_data()
                for form in alarma_formset.forms:
                    alarma = form.save(commit=False)
                    sensor = Sensor.objects.all().filter(id = sensor_id)
                    alarma.sensor = sensor[0]
                    alarma.nivel_alarma = nivel_id
                    self.set_data_alarma(tipo_alarma,alarma)
                    
                    alarma.save()
            else:
                error_sensor= '* This field is required.'
                i = alarmas.Alarma()
                sensores = i.consul_elementos_sensor( tipo_sensor = tipo_alarma)
                return  render_to_response(self.template_name, locals(),
                        RequestContext(request))
                    
        else:
            
            i = alarmas.Alarma()
            sensores = i.consul_elementos_sensor( tipo_sensor = tipo_alarma)
            
            return  render_to_response(self.template_name, locals(),
                    RequestContext(request))

        return HttpResponseRedirect('../')
Beispiel #27
0
def list(request):
    # This class is for list type of dynamic problems in QBank
	class RequiredFormSet(BaseFormSet):
		def __init__(self, *args, **kwargs):
			super(RequiredFormSet, self).__init__(*args, **kwargs)
			for form in self.forms:
				form.empty_permitted = True
	VariableFormSet = formset_factory(VariableForm, max_num = 10, formset = RequiredFormSet)
	HintFormSet = formset_factory(HintForm, max_num = 10, formset = RequiredFormSet)
	#ChoiceFormSet = formset_factory(ChoiceForm, max_num = 10, formset = RequiredFormSet)


	if request.method == 'POST': # If the form has been submitted...
	
		problem_form = ListProblemForm(request.POST)
		problem_template_form = ProblemTemplateForm(request.POST, prefix='template')
		answer_form = AnswerForm(request.POST, prefix='answer')
		variable_formset = VariableFormSet(request.POST,request.FILES, prefix='variables')
		hint_formset = HintFormSet(request.POST, request.FILES, prefix='hints')
		#choice_formset = ChoiceFormSet(request.POST, request.FILES, prefix='choices')
		if problem_form.is_valid() and problem_template_form.is_valid() and variable_formset.is_valid() and hint_formset.is_valid() and answer_form.is_valid():
			problem = problem_form.save()
			problem_template = problem_template_form.save(commit = False)
			problem_template.problem = problem
			problem_template.save()

			answer = answer_form.save(commit = False)
			answer.problem = problem
			answer.save()

            	
			for form in variable_formset.forms:
				variable = form.save(commit = False)
				variable.problem = problem
				variable.save() # Redirect to a 'success' page
			for form in hint_formset.forms:
				hint = form.save(commit = False)
				hint.problem = problem
				hint.save()
			
			return HttpResponseRedirect('/qbank/problems/')
	else:
		problem_form = ListProblemForm()
		problem_template_form = ProblemTemplateForm(prefix='template')
		answer_form = AnswerForm(prefix='answer')	
		variable_formset = VariableFormSet(prefix='variables')
		#choice_formset = ChoiceFormSet(prefix='choices')
		hint_formset = HintFormSet(prefix='hints')
	c = {'problem_form' : problem_form,
	     'problem_template_form' : problem_template_form,
	     'answer_form': answer_form,
	     'variable_formset' : variable_formset,
	     #'choice_formset': choice_formset,
	     'hint_formset' : hint_formset,
	}
	c.update(csrf(request))
	return render_to_response('list.html', c)
Beispiel #28
0
    def get_post_formsets(self, request):
        formsets = super(EventHostRegisterView, self).get_post_formsets(request)

        GroupHostFormset = formset_factory(EventGroupHostForm, extra=0)
        FeaturesFormset = formset_factory(EventGroupHostFeaturesForm, extra=0)
        formsets['grouphost_formset'] = GroupHostFormset(request.POST, prefix='grouphost')
        formsets['features_formset'] = FeaturesFormset(request.POST, prefix='features')
    
        return formsets
Beispiel #29
0
    def test_limiting_max_forms(self):
        # Limiting the maximum number of forms ########################################
        # Base case for max_num.

        # When not passed, max_num will take its default value of None, i.e. unlimited
        # number of forms, only controlled by the value of the extra parameter.

        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3)
        formset = LimitedFavoriteDrinkFormSet()
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertEqual(
            "\n".join(form_output),
            """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>
<tr><th><label for="id_form-2-name">Name:</label></th><td><input type="text" name="form-2-name" id="id_form-2-name" /></td></tr>""",
        )

        # If max_num is 0 then no form is rendered at all.
        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=0)
        formset = LimitedFavoriteDrinkFormSet()
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertEqual("\n".join(form_output), "")

        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=5, max_num=2)
        formset = LimitedFavoriteDrinkFormSet()
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertEqual(
            "\n".join(form_output),
            """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""",
        )

        # Ensure that max_num has no effect when extra is less than max_num.

        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2)
        formset = LimitedFavoriteDrinkFormSet()
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertEqual(
            "\n".join(form_output),
            """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>""",
        )
Beispiel #30
0
def editQuestion(request, question_index):

  NewOptionsFormset = formset_factory(NewOptionForm, max_num=15, extra=0)

  if request.method == 'POST': # receiving question info
    print(request.POST)

    question_form = NewQuestionForm(request.POST)
    options_formset = NewOptionsFormset(request.POST, request.FILES)

    if question_form.is_valid() and options_formset.is_valid():

      if question_index == -1: # Saving new question
        q = question_form.save()
        print("saving question...")

      else: # Updating existing question
        q = Question.objects.get(pk=question_index)
        form = NewQuestionForm(request.POST, instance=q)
        form.save()

        Option.objects.filter(question=question_index).delete()

      for form in options_formset.forms:
        option = form.save(commit=False) #commit = false
        option.question = q
        option.save()
        
      #redirect to options page unless fill in the blank
      #return HttpResponseRedirect(previous_page(request.path))
      return HttpResponseRedirect('/questions/questionHome')
      
  else: # render page
    if question_index == -1:
      NewOptionsFormset = formset_factory(NewOptionForm, max_num=15, extra=1)
      question_form = NewQuestionForm()
      options_formset = NewOptionsFormset()
    else: ##** The else statement needs to load the forms with data from database
      question = get_object_or_404(Question, id=question_index)
      options =  Option.objects.all().filter(question=question).values()

      #branch select couldn't find option['branch_id'] so insert option['branch']
      for option in options:
        option['branch'] = option['branch_id']

      if not options:
        NewOptionsFormset = formset_factory(NewOptionForm, max_num=15, extra=1)
      else:
        NewOptionsFormset = formset_factory(NewOptionForm, max_num=15, extra=0)

      question_form = NewQuestionForm(instance=question)
      print("options ===> ", options)
      options_formset = NewOptionsFormset(initial=options)
      print(options_formset)
  context = { 'question_form': question_form, 'options_formset': options_formset}
  context['previous_page'] = previous_page(request.path)
  return render(request, 'questions/addQuestion.html', context)
Beispiel #31
0
def modify_sensor(request, sensor_id):
    errors = False
    user = request.user
    VariableFormSet = formset_factory(ModifyVariableForm, extra=0)
    if request.method == 'POST':
        if user.auth_level < 2:
            context = {'title':'Not authorized!', 'error_msg':'You are not allowed to modify sensor values. Please contact admin to request rights to modify/add sensors.'}
            return render(request, 'management/error.html', context)
        else:
            modified_sensor = Sensor.objects.get(pk=sensor_id)
            modified_sensor_form = ModifySensorForm(request.POST, instance=modified_sensor, prefix='modify_sensor')
            communication_technology = request.POST['communication_technology']
            protocol = request.POST['protocol']
            if communication_technology ==  'Wlan':
                instance = Wlan.objects.get(pk=request.POST['communication_instance'])
                modified_wlan_form = ModifyWlanForm(request.POST, instance=instance, prefix='wlan')
                communication_instances = Wlan.objects.all()
                modify_communication_form = modified_wlan_form
                if modified_wlan_form.is_valid():
                    modified_wlan_form.save()
                    modified_sensor.communication_object = instance
                else:
                    errors = True
            elif communication_technology == 'Nb_iot':
                instance = Nb_iot.objects.get(pk=request.POST['communication_instance'])
                modified_nb_iot_form = ModifyNbIotForm(request.POST, instance=instance, prefix='nb_iot')
                communication_instances = Nb_iot.objects.all()
                modify_communication_form = modified_nb_iot_form
                if modified_nb_iot_form.is_valid():
                    modified_nb_iot_form.save()
                    modified_sensor.communication_object = instance
                else:
                    errors = True
            if protocol == 'HTTP':
                instance = HTTP.objects.get(pk=request.POST['protocol_instance'])
                modified_http_form = ModifyHTTPForm(request.POST, instance=instance, prefix='http')
                protocol_instances = HTTP.objects.all()
                modify_protocol_form = modified_http_form
                if modified_http_form.is_valid():
                    modified_http_form.save()
                    modified_sensor.protocol_object = instance
                else:
                    errors = True
            elif protocol == 'HTTPS':
                instance = HTTPS.objects.get(pk=request.POST['protocol_instance'])
                modified_https_form = ModifyHTTPSForm(request.POST, instance=instance, prefix='https')
                protocol_instances = HTTPS.objects.all()
                modify_protocol_form = modified_https_form
                if modified_https_form.is_valid():
                    modified_https_form.save()
                    modified_sensor.protocol_object = instance
                else:
                    errors = True
            elif protocol == 'MQTT':
                instance = MQTT.objects.get(pk=request.POST['protocol_instance'])
                modified_MQTT_form = ModifyMQTTForm(request.POST, instance=instance, prefix='mqtt')
                protocol_instances = MQTT.objects.all()
                modify_protocol_form = modified_MQTT_form
                if modified_MQTT_form.is_valid():
                    modified_MQTT_form.save()
                    modified_sensor.protocol_object = instance
                else:
                    errors = True
            old_key = modified_sensor.sensor_key
            modify_sensor_form = modified_sensor_form
            variable_formset = VariableFormSet(request.POST)
            if variable_formset.is_valid():
                old_variables = Variable.objects.filter(sensor=modified_sensor)
                for o in old_variables:
                    o.delete()
                for variable_form in variable_formset:
                    name = variable_form.cleaned_data.get('name')
                    unit = variable_form.cleaned_data.get('unit')
                    if name and unit:
                        v = Variable(sensor=modified_sensor, name=name, unit=unit)
                        v.save()
            else:
                errors = True
            if modified_sensor_form.is_valid():
                if not errors:
                    modified_sensor.sample_rate = Sample_rate.objects.get(id=request.POST['modify_sensor-sample_rate'])
                    modified_sensor.sensitivity = Sensitivity.objects.get(id=request.POST['modify_sensor-sensitivity'])
                    if old_key != request.POST['modify_sensor-sensor_key']:
                        modified_sensor.sensor_key_old = old_key
                    modified_sensor_form.save()
                    if modified_sensor.status != Sensor.WAITING_FOR_UPDATE:
                        modified_sensor.status = Sensor.MEASURING_WAITING_FOR_UPDATE
                    modified_sensor.latest_modifier = user
                    modified_sensor.date_modified = datetime.datetime.now()
                    modified_sensor.save()
                    update_sensor(modified_sensor)
                    return redirect('browse_sensors')
            else:
                errors = True
    #If not post fill the form
    sensor = Sensor.objects.get(pk=sensor_id)
    communication_object = sensor.communication_object
    communication_type = communication_object.__class__.__name__
    protocol_object = sensor.protocol_object
    protocol = protocol_object.__class__.__name__
    if user.auth_level >= 2:
        if not errors:
            modify_sensor_form = ModifySensorForm(instance=sensor, prefix='modify_sensor')
            if communication_type == 'Wlan':
                modify_communication_form = ModifyWlanForm(instance=communication_object, prefix='wlan')
                communication_instances = Wlan.objects.all()
            elif communication_type == 'Nb_iot':
                modify_communication_form = ModifyNbIotForm(instance=communication_object, prefix='nb_iot')
                communication_instances = Nb_iot.objects.all()
            else:
                raise Http404("Page doesn't exist")
            if protocol == 'HTTP':
                modify_protocol_form = ModifyHTTPForm(instance=protocol_object, prefix='http')
                protocol_instances = HTTP.objects.all()
            elif protocol == 'HTTPS':
                modify_protocol_form = ModifyHTTPSForm(instance=protocol_object, prefix='https')
                protocol_instances = HTTPS.objects.all()
            elif protocol == 'MQTT':
                modify_protocol_form = ModifyMQTTForm(instance=protocol_object, prefix='mqtt')
                protocol_instances = MQTT.objects.all()
            else:
                raise Http404("Page doesn't exist")
    else:
        return render(request, 'management/error.html', {'title' : 'You are not allowed to modify sensor', 'error_msg' : 'Ask rights to modify sensor from admin.'})
    variables = Variable.objects.filter(sensor=Sensor.objects.get(pk=sensor_id))
    initial_data = [{'name': v.name, 'unit': v.unit}
                    for v in variables]
    modify_variable_forms = VariableFormSet(initial=initial_data)
    available_sample_rates = Sample_rate.objects.filter(model=sensor.model.pk)
    available_sensitivities = sensor.sample_rate.supported_sensitivities.all()
    current_model = sensor.model.sensor_model
    context =   {'modify_sensor_form' : modify_sensor_form,
                'available_sample_rates': available_sample_rates,
                'current_sample_rate': sensor.sample_rate.id,
                'available_sensitivities': available_sensitivities,
                'current_sensitivity': sensor.sensitivity.id,
                'current_communication_technology': sensor.communication_object.__class__.__name__,
                'current_communication_id': sensor.communication_object.id,
                'communication_instances': communication_instances,
                'modify_communication_form': modify_communication_form,
                'available_communication_technologies':AVAILABLE_COMMUNICATION_TECHNOLOGIES,
                'current_protocol': sensor.protocol_object.__class__.__name__,
                'current_protocol_id': sensor.protocol_object.id,
                'protocol_instances': protocol_instances,
                'modify_protocol_form': modify_protocol_form,
                'available_protocols': AVAILABLE_PROTOCOLS,
                'modify_variable_forms': modify_variable_forms,
                'sensor_id': sensor_id,
                'current_model': current_model,
    }
    return render(request, 'management/modify_sensor.html', context)
Beispiel #32
0
    def post(self, *args, **kwargs):
        tally_id = kwargs.get('tally_id')
        post_data = self.request.POST
        pk = session_matches_post_result_form(post_data, self.request)
        result_form = get_object_or_404(ResultForm, pk=pk, tally__id=tally_id)
        form_in_data_entry_state(result_form)
        formset, forms_and_candidates = get_formset_and_candidates(result_form,
                                                                   post_data)
        recon_form = ReconForm(post_data)
        data_entry_number = get_data_entry_number(result_form.form_state)
        candidates = result_form.candidates
        CandidateFormSet = formset_factory(CandidateForm,
                                           extra=len(candidates),
                                           formset=BaseCandidateFormSet)
        formset = CandidateFormSet(post_data)

        if (not result_form.has_recon or
                recon_form.is_valid()) and formset.is_valid():
            check_form = check_state_and_group(
                result_form, self.request.user, recon_form)

            if check_form:
                return self.form_invalid(check_form)

            entry_version = None
            new_state = None

            if result_form.form_state == FormState.DATA_ENTRY_1:
                entry_version = EntryVersion.DATA_ENTRY_1
                new_state = FormState.DATA_ENTRY_2
            else:
                entry_version = EntryVersion.DATA_ENTRY_2
                new_state = FormState.CORRECTION

            for i, form in enumerate(formset.forms):
                votes = form.cleaned_data['votes']
                Result.objects.create(
                    candidate=candidates[i],
                    result_form=result_form,
                    entry_version=entry_version,
                    votes=votes,
                    user=self.request.user.userprofile
                )

            if result_form.has_recon:
                re_form = recon_form.save(commit=False)
                re_form.entry_version = entry_version
                re_form.result_form = result_form
                re_form.user = self.request.user.userprofile
                re_form.save()

            result_form.form_state = new_state
            result_form.duplicate_reviewed = False
            result_form.save()

            return redirect(self.success_url, tally_id=tally_id)
        else:
            return self.render_to_response(self.get_context_data(
                formset=formset,
                forms_and_candidates=forms_and_candidates,
                reconciliation_form=recon_form,
                result_form=result_form,
                data_entry_number=data_entry_number,
                tally_id=tally_id))
Beispiel #33
0
	spoc=forms.CharField(label='SPOC',widget=forms.TextInput(attrs={'readonly':'readonly'}),)
	consultants = forms.ModelMultipleChoiceField(label='Choose Consultants',queryset=None, widget=forms.CheckboxSelectMultiple, required=True)
	bankname=forms.ModelChoiceField(label='Bankname',queryset=Bank.objects.all(),empty_label='Select Bank')
	From=forms.DateField(label='From Date',widget=forms.DateInput(attrs={'type':'date'}),required=True)
	To=forms.DateField(label='To Date',widget=forms.DateInput(attrs={'type':'date'}),required=True)

	requests_recieved = forms.CharField(widget=TinyMCE(attrs={'cols': 30, 'rows': 7}))
	summary_of_response = forms.CharField(widget=TinyMCE(attrs={'cols': 15, 'rows': 15}))
	summary_of_workdone = forms.CharField(widget=TinyMCE(attrs={'cols': 15, 'rows': 6}))
	learnings = forms.CharField(widget=TinyMCE(attrs={'cols': 15, 'rows': 6}))


class AttachmentsForm(forms.Form):
	file=forms.FileField(required=False,label='Upload File')
AttachmentsFormset= formset_factory(AttachmentsForm)

class QAForm(forms.Form):
	file=forms.FileField(required=False,label='Upload File')
QA_Formset= formset_factory(QAForm)

class CreateReportForm(forms.Form):
	def __init__(self, *args, **kwargs):
		user = kwargs.pop('user')
		super(CreateReportForm, self).__init__(*args, **kwargs)
		self.fields['consultants'].queryset = User.objects.filter(is_consultant=True).exclude(name=user)
		self.fields['spoc'].initial = User.objects.get(name=user)
	spoc=forms.CharField(label='SPOC',widget=forms.TextInput(attrs={'readonly':'readonly'}),)
	consultants = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple, required=True)	
	bankname=forms.ModelChoiceField(queryset=Bank.objects.all(),required=True,empty_label='Select Bank')
	date=forms.DateField(label='Date',widget=forms.DateInput(attrs={'type':'date'}))
Beispiel #34
0
    def engine_call(self, request, engine_method, format=None, is_detail=True, 
                    form_class=RequestForm, serialize=True, download=True, 
                    limit=False):
        mutable_get = request.GET.copy()
        mutable_get.update(request.POST.copy())
        mutable_get['output'] = 'json'
        if format is not None:
            format = 'prettyjson' if format == 'pjson' else format
            format = 'json_array' if format == 'ajson' else format
            format = 'json' if format == 'jsonp' else format
            mutable_get['output'] = format 

        if limit:
            max_rows = int(self.get_max_rows(request))
            param_rows = mutable_get.get('limit', None)
            if max_rows > 0 and (not param_rows or int(param_rows) <= 0 or int(param_rows) > max_rows):
                mutable_get['limit'] = max_rows
             
        resource = {}
        if is_detail:
            resource = self.get_object()
            mutable_get['revision_id'] = resource[self.dao_pk]
            mutable_get.update(self.get_default_parameters(request))

        items = dict(mutable_get.items())
        
        formset=formset_factory(form_class, formset=RequestFormSet)
        form = formset(items)
        if not form.is_valid():
            logger.info("form errors: %s" % form.errors)
            # TODO: correct handling
            raise Exception("Wrong arguments")        

        command = AbstractCommandFactory(self.app).create(engine_method, 
            self.data_types[0], form.cleaned_data)
        result = command.run()
        if not result:
            # TODO: correct handling
            raise Exception('Wrong engine answer')

        
        resource['result'] = result[0] if result[0] else {}
        resource['format'] = result[1]

        if serialize:
            serializer = self.get_serializer(resource)
            return Response(serializer.data)

        serializer = EngineSerializer(resource, 
            context={'dao_filename': self.dao_filename})

        if download and 'redirect' in serializer.data and serializer.data['redirect']:
            response = HttpResponse(content_type='application/force-download')
            filename = serializer.data['filename']
            # UGLY HOTFIX
            # ENGINE SEND SOMETHING LIKE 
            ### Nivel_Rendimiento_anio_2008.xlsx?AWSAccessKeyId=AKIAI65****H2VI25OA&Expires=1452008148&Signature=u84IIwXrpIoE%3D
            filename2 = filename.split('?AWSAccessKeyId')[0]
            #TODO get the real name (title) or someting nice
            
            response['Content-Disposition'] = 'attachment; filename="{0}"'.format(filename2)
            redir = urllib2.urlopen(serializer.data['result']['fUri'])
            status = redir.getcode()
            resp = redir.read()
            url = redir.geturl()
            if settings.DEBUG: logger.info('REDIR %d %s -- %s -- %s -- %s' % (status, url, redir.info(), filename, filename2))
            response.write(resp)
            return response

        response = Response(serializer.data['result'], content_type=resource['format'])
        
        #TODO hacer una lista de los formatos que esperan forzar una descarga y los que se mostraran en pantalla
        output = mutable_get['output']
        if download and output not in ['json', 'html']: 
            # reemplazar la extension si la tuviera
            filename = serializer.data['filename']
            name = filename if len(filename.split('.')) == 1 else '.'.join(filename.split('.')[:-1])
            final_filename = '{}.{}'.format(name, output)
            response['Content-Disposition'] = 'attachment; filename="{}"'.format(final_filename)
            

        # Si es un recurso, trato de guardar el timestamp si corresponde
        if is_detail and format == 'json':
            self.update_timestamp(response, resource)

        return response
Beispiel #35
0
def volumemanager(request):

    if request.method == "POST":
        form = forms.VolumeManagerForm(request.POST)
        VdevFormSet = formset_factory(forms.VolumeVdevForm,
                                      formset=forms.VdevFormSet)
        formset = VdevFormSet(request.POST, prefix='layout')
        formset.form = form
        if form.is_valid() and formset.is_valid() and form.done(formset):
            return JsonResp(request, message=_("Volume successfully added."))
        else:
            return JsonResp(request, form=form, formsets={'layout': formset})
    disks = []

    # Grab disk list
    # Root device already ruled out
    for disk, info in notifier().get_disks().items():
        disks.append(
            forms.Disk(info['devname'],
                       info['capacity'],
                       serial=info.get('ident')))
    disks = sorted(disks, key=lambda x: (x.size, x.dev), cmp=_diskcmp)

    # Exclude what's already added
    used_disks = []
    for v in models.Volume.objects.all():
        used_disks.extend(v.get_disks())

    qs = iSCSITargetExtent.objects.filter(iscsi_target_extent_type='Disk')
    used_disks.extend([i.get_device()[5:] for i in qs])

    bysize = dict()
    for d in list(disks):
        if d.dev in used_disks:
            continue
        hsize = forms.humanize_number_si(d.size)
        if hsize not in bysize:
            bysize[hsize] = []
        bysize[hsize].append({
            'dev': d.dev,
            'name': str(d),
            'size': d.size,
            'serial': d.serial,
        })

    bysize = OrderedDict(sorted(bysize.iteritems(), reverse=True))

    qs = models.Volume.objects.filter(vol_fstype='ZFS')
    swap = Advanced.objects.latest('id').adv_swapondrive

    return render(
        request, "storage/volumemanager.html", {
            'disks':
            json.dumps(bysize),
            'dedup_warning':
            forms.DEDUP_WARNING,
            'swap_size':
            swap * 1024 * 1024 * 1024,
            'extend':
            json.dumps([{
                'value': '',
                'label': '-----'
            }] + [{
                'label': x.vol_name,
                'value': x.vol_name,
                'enc': x.vol_encrypt > 0
            } for x in qs]),
        })
Beispiel #36
0
def modelformset_factory(
    model,
    form=ModelForm,
    formfield_callback=None,
    formset=BaseModelFormSet,
    extra=1,
    can_delete=False,
    can_order=False,
    max_num=None,
    fields=None,
    exclude=None,
    widgets=None,
    validate_max=False,
    localized_fields=None,
    labels=None,
    help_texts=None,
    error_messages=None,
    min_num=None,
    validate_min=False,
    field_classes=None,
    session=None,
):
    """Return a FormSet class for the given sqlalchemy model class."""
    _meta = getattr(form, "Meta", None)
    fields = getattr(_meta, "fields", fields)
    exclude = getattr(_meta, "exclude", exclude)
    if fields is None and exclude is None:
        raise ImproperlyConfigured(
            "Calling modelformset_factory without defining 'fields' or "
            "'exclude' explicitly is prohibited.")

    form = modelform_factory(
        model,
        form=form,
        fields=fields,
        exclude=exclude,
        formfield_callback=formfield_callback,
        widgets=widgets,
        localized_fields=localized_fields,
        labels=labels,
        help_texts=help_texts,
        error_messages=error_messages,
        field_classes=field_classes,
        session=session,
    )

    FormSet = formset_factory(
        form,
        formset,
        extra=extra,
        min_num=min_num,
        max_num=max_num,
        can_order=can_order,
        can_delete=can_delete,
        validate_min=validate_min,
        validate_max=validate_max,
    )
    class_name = model.__name__ + "FormSet"
    return type(form)(str(class_name), (FormSet, ), {
        "model": model,
        "session": session
    })
Beispiel #37
0
def student_take_quiz(request, Quiz_Order):
    assignment = Assignment.objects.get(assignNum=Quiz_Order)
    submitassign = SubmitAssign.objects.get(assignNum=assignment,
                                            studentID=request.user)
    '''
    #check if submittime is before 5hours
    if timezone.now() - submitassign.submitTime < timedelta(hours=5):
        #submitAssigns = SubmitAssign.objects.filter(studentID__username = request.user.username).filter(assignNum__subjectNum = assignment.subjectNum.subjectNum)
        #return render(request, 'student/student_quiz.html', {'submitassigns':submitAssigns})
        return student_quiz(request, assignment.subjectNum.subjectNum)
    '''
    if assignment.amountQuizShort is None:
        takequizshorts = quiz_short.objects.filter(AssignNum=Quiz_Order)
    else:
        quiz_id_list = quiz_shortManager.objects.filter(
            submitAssign=submitassign).values_list('quiz', flat=True)
        if len(quiz_id_list) == 0:
            id_list = quiz_short.objects.filter(
                AssignNum=Quiz_Order).values_list('id', flat=True)
            random_id_list = random.sample(
                list(id_list),
                min(len(list(id_list)), assignment.amountQuizShort))
            #takequizshorts = quiz_short.objects.filter(id__in=random_id_list)
            for quiz_id in random_id_list:
                quiz_shortManager.objects.create(submitAssign=submitassign,
                                                 quiz_id=quiz_id)
            quiz_id_list = quiz_shortManager.objects.filter(
                submitAssign=submitassign).values_list('quiz', flat=True)
            takequizshorts = quiz_short.objects.filter(id__in=quiz_id_list)
        else:
            takequizshorts = quiz_short.objects.filter(id__in=quiz_id_list)

    if assignment.amountQuizOne is None:
        takequizones = quiz_one.objects.filter(AssignNum=Quiz_Order)
    else:
        quiz_id_list = quiz_oneManager.objects.filter(
            submitAssign=submitassign).values_list('quiz', flat=True)
        if len(quiz_id_list) == 0:
            id_list = quiz_one.objects.filter(
                AssignNum=Quiz_Order).values_list('id', flat=True)
            random_id_list = random.sample(
                list(id_list), min(len(list(id_list)),
                                   assignment.amountQuizOne))
            #takequizones = quiz_one.objects.filter(id__in=random_id_list)
            for quiz_id in random_id_list:
                quiz_oneManager.objects.create(submitAssign=submitassign,
                                               quiz_id=quiz_id)
            quiz_id_list = quiz_oneManager.objects.filter(
                submitAssign=submitassign).values_list('quiz', flat=True)
            takequizones = quiz_one.objects.filter(id__in=quiz_id_list)
        else:
            takequizones = quiz_one.objects.filter(id__in=quiz_id_list)

    if assignment.amountQuizMulti is None:
        takequizmultis = quiz_multi.objects.filter(AssignNum=Quiz_Order)
    else:
        quiz_id_list = quiz_multiManager.objects.filter(
            submitAssign=submitassign).values_list('quiz', flat=True)
        if len(quiz_id_list) == 0:
            id_list = quiz_multi.objects.filter(
                AssignNum=Quiz_Order).values_list('id', flat=True)
            random_id_list = random.sample(
                list(id_list),
                min(len(list(id_list)), assignment.amountQuizMulti))
            #takequizmultis = quiz_multi.objects.filter(id__in=random_id_list)
            for quiz_id in random_id_list:
                quiz_multiManager.objects.create(submitAssign=submitassign,
                                                 quiz_id=quiz_id)
            quiz_id_list = quiz_multiManager.objects.filter(
                submitAssign=submitassign).values_list('quiz', flat=True)
            takequizmultis = quiz_multi.objects.filter(id__in=quiz_id_list)
        else:
            takequizmultis = quiz_multi.objects.filter(id__in=quiz_id_list)

    #takequizones = quiz_one.objects.filter(AssignNum = Quiz_Order)
    #takequizmultis = quiz_multi.objects.filter(AssignNum = Quiz_Order)

    my_iterator_short = takequizshorts.iterator()
    FormSet_Short_Answer_Forms = formset_factory(ShortAnswerForm,
                                                 extra=len(takequizshorts))
    try:
        FormSet_Short_Answer_Forms.form = staticmethod(
            curry(ShortAnswerForm, item_iterator_short=my_iterator_short))
    except:
        pass

    my_iterator = takequizones.iterator()
    FormSet_One_Answer_Forms = formset_factory(OneChoiceForm,
                                               extra=len(takequizones))
    try:
        FormSet_One_Answer_Forms.form = staticmethod(
            curry(OneChoiceForm, item_iterator=my_iterator))
    except:
        pass

    my_iterator_multi = takequizmultis.iterator()
    FormSet_Multi_Answer_Forms = formset_factory(MultiChoiceForm,
                                                 extra=len(takequizmultis))
    try:
        FormSet_Multi_Answer_Forms.form = staticmethod(
            curry(MultiChoiceForm, item_iterator_multi=my_iterator_multi))
    except:
        pass

    if request.method == 'POST':
        formset_short_answer_forms = FormSet_Short_Answer_Forms(
            request.POST, prefix="short_answer_forms")
        formset_one_answer_forms = FormSet_One_Answer_Forms(
            request.POST, prefix="one_answer_forms")
        formset_multi_answer_forms = FormSet_Multi_Answer_Forms(
            request.POST, prefix="multi_answer_forms")
        print(request.POST)

        grade = 0

        if formset_short_answer_forms.is_valid(
        ) and formset_one_answer_forms.is_valid(
        ) and formset_multi_answer_forms.is_valid():
            for f in formset_short_answer_forms:
                cd = f.cleaned_data
                answer = cd.get('answer')
                '''
                short_answer_result[sar]=f.quiz_short.Answer
                print(short_answer_result[sar])
                '''
                f.correct_short = f.quiz_short.Answer == answer

                if f.correct_short:
                    grade = grade + 1

            for f in formset_one_answer_forms:
                cd = f.cleaned_data
                answer_key = cd.get('one_answer')
                '''
                print(dict(f.fields['one_answer'].choices).get(answer_key))
                #if f.quiz_one.Answer == one_answer :
                if f.quiz_one.Answer == dict(f.fields['one_answer'].choices).get(answer_key):
                    grade = grade + 1
                '''

                f.correct_one_check = f.quiz_one.Check == answer_key
                if f.correct_one_check:
                    grade = grade + 1
                '''
                correct_list_multi = []
                if f.quiz_one.Check_1 == True:
                    correct_list_multi.append('1')
                if f.quiz_one.Check_2 == True:
                    correct_list_multi.append('2')
                if f.quiz_one.Check_3 == True:
                    correct_list_multi.append('3')
                if f.quiz_one.Check_4 == True:
                    correct_list_multi.append('4')

                if correct_list_multi == answer_list_multi :
                    grade = grade + 1
                '''

            for f in formset_multi_answer_forms:
                cd = f.cleaned_data
                answer_list = cd.get('multi_answer')

                correct_list = []
                if f.quiz_multi.Check_1 == True:
                    correct_list.append('a_multi')
                if f.quiz_multi.Check_2 == True:
                    correct_list.append('b_multi')
                if f.quiz_multi.Check_3 == True:
                    correct_list.append('c_multi')
                if f.quiz_multi.Check_4 == True:
                    correct_list.append('d_multi')

                f.correct_multi_check = correct_list == answer_list
                if f.correct_multi_check:
                    grade = grade + 1
            assignment = Assignment.objects.get(assignNum=Quiz_Order)
            submitassign = SubmitAssign.objects.filter(assignNum=assignment,
                                                       studentID=request.user)
            submitassign.update(grade=grade, submitTime=timezone.now())

            quiz_oneManager.objects.filter(submitAssign=submitassign).delete()
            quiz_multiManager.objects.filter(
                submitAssign=submitassign).delete()
            quiz_shortManager.objects.filter(
                submitAssign=submitassign).delete()
            #            context =  {'takequizshorts':takequizshorts, 'takequizones':takequizones, 'takequizmultis':takequizmultis, 'formsetshortanswerforms':formset_short_answer_forms, 'formsetoneanswerforms':formset_one_answer_forms, 'formsetmultianswerforms':formset_multi_answer_forms}
            #            return HttpResponseRedirect('student_quiz_result.html', context)

            questionquantity = len(takequizshorts) + len(takequizones) + len(
                takequizmultis)
            context = {
                'takequizshorts': takequizshorts,
                'takequizones': takequizones,
                'takequizmultis': takequizmultis,
                'formsetshortanswerforms': formset_short_answer_forms,
                'formsetoneanswerforms': formset_one_answer_forms,
                'formsetmultianswerforms': formset_multi_answer_forms,
                'grade': grade,
                'questionquantity': questionquantity
            }
            return render(request, 'student/student_quiz_result.html', context)
    else:
        formset_short_answer_forms = FormSet_Short_Answer_Forms(
            prefix="short_answer_forms")
        formset_one_answer_forms = FormSet_One_Answer_Forms(
            prefix="one_answer_forms")
        formset_multi_answer_forms = FormSet_Multi_Answer_Forms(
            prefix="multi_answer_forms")

    context = {
        'takequizshorts': takequizshorts,
        'takequizones': takequizones,
        'takequizmultis': takequizmultis,
        'formsetshortanswerforms': formset_short_answer_forms,
        'formsetoneanswerforms': formset_one_answer_forms,
        'formsetmultianswerforms': formset_multi_answer_forms
    }
    return render(request, 'student/student_take_quiz.html', context)
Beispiel #38
0
            self.forms.append(
                self._construct_form(i, model_fields=self.model_fields))

    @cached_property
    def forms(self):
        # override the original property to include `model_fields` argument
        forms = [
            self._construct_form(i, model_fields=self.model_fields)
            for i in range(self.total_form_count())
        ]
        forms.append(self.empty_form)  # add initial empty form
        return forms


AFQFormSet = formset_factory(AdvancedFilterQueryForm,
                             formset=AdvancedFilterFormSet,
                             extra=1,
                             can_delete=True)

AFQFormSetNoExtra = formset_factory(AdvancedFilterQueryForm,
                                    formset=AdvancedFilterFormSet,
                                    extra=0,
                                    can_delete=True)


class AdvancedFilterForm(CleanWhiteSpacesMixin, forms.ModelForm):
    """ Form to save/edit advanced filter forms """
    class Meta:
        model = AdvancedFilter
        fields = ('title', )

    class Media:
Beispiel #39
0
    def clean(self):
        """No two email addresses are the same."""
        if any(self.errors):
            # Don't bother validating the formset unless each form is valid
            return

        emails = []
        for form in self.forms:
            email = form.cleaned_data['email']
            if email in emails:
                raise ValidationError(
                    "Forms in a set must have distinct email addresses.")
            emails.append(email)


TestFormSet = formset_factory(TestForm, BaseTestFormSet)


def formset_view(request):
    "A view that tests a simple formset"
    if request.method == 'POST':
        formset = TestFormSet(request.POST)
        if formset.is_valid():
            t = Template('Valid POST data.', name='Valid POST Template')
            c = Context()
        else:
            t = Template('Invalid POST data. {{ my_formset.errors }}',
                         name='Invalid POST Template')
            c = Context({'my_formset': formset})
    else:
        formset = TestForm(request.GET)
Beispiel #40
0
def index(request):

    if request.method == "POST":
        all_forms = {
            "form1": forms.Form1,
            "form2": forms.Form2,
            "form3": forms.Form3,
            "form4": forms.Form4,
            "form5": forms.Form5,
            "form6": formset_factory(forms.Form6, extra=4),
        }

        for i in range(1, len(all_forms) + 1):

            all_forms[f"form{i}"] = all_forms[f"form{i}"](prefix=f"form{i}",
                                                          data=request.POST)

        if all(all_forms[i].is_valid() for i in all_forms):
            document.main(all_forms)

        else:
            return HttpResponse(
                f"<h1>INVALID FORM : CLICK BACK BUTTON TOP LEFT<br>"
                "{'\n'.join(map(lambda x:x.errors if not x.is_valid() else "
                ", all_forms.values()))}</h1>")

        return HttpResponse("<h1>Sent</h1>")

    all_forms = {
        "form1": forms.Form1,
        "form2": forms.Form2,
        "form3": forms.Form3,
        "form4": forms.Form4,
        "form5": forms.Form5,
        "form6": formset_factory(forms.Form6, extra=4),
    }
    sections = [
        f"mainapp/section{i}.html" for i in range(1,
                                                  len(all_forms) + 1)
    ]

    for i in range(1, len(all_forms) + 1):
        all_forms[f"form{i}"] = all_forms[f"form{i}"](prefix=f"form{i}")

    return render(
        request,
        "mainapp/index.html",
        context={
            **all_forms,
            "sections":
            sections,
            "section8": [
                "Grant agency Title of the project and reference number",
                "Duration(from mm/yy to mm/yy)",
                "Percentage of time devoted /being devoted/to be devoted, in many months",
                "Amount in lakh Rs."
            ],
            "section9": [],
            "section10": [],
            "section11": [],
            "section12": [],
        })
Beispiel #41
0
                    BaseLeaveFormSet, EmployeeCommonForm, LeaveSegmentForm,
                    StudentApplicationForm, AcademicReplacementFormOffline,
                    AdminReplacementFormOffline, BaseLeaveFormSetOffline,
                    EmployeeCommonFormOffline, LeaveSegmentFormOffline)
from .helpers import (create_migrations, deduct_leave_balance,
                      get_pending_leave_requests, restore_leave_balance,
                      get_designation)
from .models import (Leave, LeaveRequest, LeaveSegment, LeaveType,
                     ReplacementSegment, LeaveOffline, LeaveSegmentOffline,
                     ReplacementSegmentOffline)
from applications.globals.models import HoldsDesignation
from notification.views import leave_module_notif

LeaveFormSet = formset_factory(LeaveSegmentForm,
                               extra=0,
                               max_num=3,
                               min_num=1,
                               formset=BaseLeaveFormSet)
AcadFormSet = formset_factory(AcademicReplacementForm,
                              extra=0,
                              max_num=3,
                              min_num=1)
AdminFormSet = formset_factory(AdminReplacementForm,
                               extra=0,
                               max_num=3,
                               min_num=1)
common_form = EmployeeCommonForm()

LeaveFormSetOffline = formset_factory(LeaveSegmentFormOffline,
                                      formset=BaseLeaveFormSetOffline,
                                      extra=0,
Beispiel #42
0
    def deadline_management(self, request, tl, one, two, module, extra, prog):
        #   Define a formset for editing multiple perms simultaneously.
        EditPermissionFormset = formset_factory(EditPermissionForm)

        #   Define a status message
        message = ''

        #   Handle 'open' / 'close' actions
        if extra == 'open' and 'id' in request.GET:
            perm = Permission.objects.get(id=request.GET['id'])
            #   Clear any duplicate user permissions
            Permission.objects.filter(
                permission_type=perm.permission_type,
                program=perm.program,
                user__isnull=True,
                role=perm.role).exclude(id=perm.id).delete()
            perm.end_date = None
            perm.save()
            message = 'Deadline opened: %s.' % perm.nice_name()

        elif extra == 'close' and 'id' in request.GET:
            perm = Permission.objects.get(id=request.GET['id'])
            #   Clear any duplicate user permissions
            Permission.objects.filter(
                permission_type=perm.permission_type,
                program=perm.program,
                user__isnull=True,
                role=perm.role).exclude(id=perm.id).delete()
            perm.end_date = datetime.now()
            perm.save()
            message = 'Deadline closed: %s.' % perm.nice_name()

        #   Check incoming form data
        if request.method == 'POST':
            edit_formset = EditPermissionFormset(request.POST.copy(),
                                                 prefix='edit')
            create_form = NewPermissionForm(request.POST.copy())
            if edit_formset.is_valid():
                num_forms = 0
                for form in edit_formset.forms:
                    #   Check if the permission with the specified ID exists.
                    #   It may have been deleted by previous iterations of this loop
                    #   deleting duplicate permissions.
                    if 'id' in form.cleaned_data and Permission.objects.filter(
                            id=form.cleaned_data['id']).exists():
                        num_forms += 1
                        perm = Permission.objects.get(
                            id=form.cleaned_data['id'])
                        #   Clear any duplicate perms
                        Permission.objects.filter(
                            permission_type=perm.permission_type,
                            program=perm.program,
                            user__isnull=True,
                            role=perm.role).exclude(id=perm.id).delete()
                        perm.start_date = form.cleaned_data['start_date']
                        perm.end_date = form.cleaned_data['end_date']
                        perm.save()
                if num_forms > 0:
                    message = 'Changes saved.'
            if create_form.is_valid():
                perm, created = Permission.objects.get_or_create(
                    user=None,
                    permission_type=create_form.
                    cleaned_data['permission_type'],
                    role=Group.objects.get(
                        name=create_form.cleaned_data['role']),
                    program=prog)
                if not created:
                    message = 'Deadline already exists: %s.  Please modify the existing deadline.' % perm.nice_name(
                    )
                else:
                    perm.start_date = create_form.cleaned_data['start_date']
                    perm.end_date = create_form.cleaned_data['end_date']
                    perm.save()
                    message = 'Deadline created: %s.' % perm.nice_name()
            else:
                message = 'No activities selected.  Please select a deadline type from the list before creating a deadline.'

        #   find all the existing permissions with this program
        #   Only consider global permissions -- those that apply to all users
        #   of a particular role.  Permissions added for individual users
        #   should be managed in the admin interface.
        perms = Permission.deadlines().filter(program=self.program,
                                              user__isnull=True)
        perm_map = {p.permission_type: p for p in perms}

        #   Populate template context to render page with forms
        context = {}

        #   Set a flag on each perm for whether it has ended
        #   TODO(benkraft): refactor users to just call is_valid themselves.
        for perm in perms:
            perm.open_now = perm.is_valid()

        #   For each permission, determine which other ones it implies
        for perm in perms:
            includes = Permission.implications.get(perm.permission_type, [])
            perm.includes = []
            perm.name = perm.nice_name()
            for p in includes:
                if p == perm.permission_type: continue
                perm.includes.append({
                    'type':
                    p,
                    'nice_name':
                    Permission.nice_name_lookup(p)
                })
                if p in perm_map:
                    perm.includes[-1].update({
                        'overridden': True,
                        'overridden_by': perm_map[p],
                        'bit_open': perm_map[p].open_now
                    })

        #   Supply initial data for forms
        formset = EditPermissionFormset(
            initial=[perm.__dict__ for perm in perms], prefix='edit')
        for i in range(len(perms)):
            perms[i].form = formset.forms[i]

        context['message'] = message
        context['manage_form'] = formset.management_form
        context['perms'] = perms
        context['create_form'] = NewPermissionForm()

        return render_to_response(self.baseDir() + 'deadlines.html', request,
                                  context)
Beispiel #43
0
        return encoding


class RenameForm(forms.Form):
    op = "rename"
    src_path = CharField(label=_("File to rename"),
                         help_text=_("The file to rename."))
    dest_path = CharField(label=_("New name"),
                          help_text=_("Rename the file to:"))


class BaseRenameFormSet(FormSet):
    op = "rename"


RenameFormSet = formset_factory(RenameForm, formset=BaseRenameFormSet, extra=0)


class CopyForm(forms.Form):
    op = "copy"
    src_path = CharField(label=_("File to copy"),
                         help_text=_("The file to copy."))
    dest_path = CharField(label=_("Destination location"),
                          help_text=_("Copy the file to:"))


class BaseCopyFormSet(FormSet):
    op = "copy"


CopyFormSet = formset_factory(CopyForm, formset=BaseCopyFormSet, extra=0)
Beispiel #44
0
def get_sensor_variables(request, sensor_id):
    variables = Variable.objects.filter(sensor=Sensor.objects.get(pk=sensor_id))
    initial_data = [{'name': v.name, 'unit': v.unit}
                    for v in variables]
    VariableFormSet = formset_factory(ModifyVariableForm, extra=0)
    return render(request, 'management/variable_table.html', context = {'modify_variable_forms': VariableFormSet(initial=initial_data)})
Beispiel #45
0
    pass


class ContactBaseFormSet(BaseFormSet):
    def add_fields(self, form, index):
        super(ContactBaseFormSet, self).add_fields(form, index)

    def clean(self):
        super(ContactBaseFormSet, self).clean()
        raise forms.ValidationError(
            "This error was added to show the non form errors styling")


ContactFormSet = formset_factory(TestForm,
                                 formset=ContactBaseFormSet,
                                 extra=2,
                                 max_num=4,
                                 validate_max=True)


class FilesForm(forms.Form):
    text1 = forms.CharField()
    file1 = forms.FileField()
    file2 = forms.FileField(required=False)
    file3 = forms.FileField(widget=forms.ClearableFileInput)
    file4 = forms.FileField(required=False, widget=forms.ClearableFileInput)


class ArticleForm(forms.Form):
    title = forms.CharField()
    pub_date = forms.DateField()
Beispiel #46
0
    def _get_lookup(self, operator, over):
        lookup = Field().get_db_prep_lookup(operator,
                                            over,
                                            connection=self._db_connection,
                                            prepared=True)
        if isinstance(lookup, (tuple, list)):
            return lookup[0]
        return lookup

    def _get_selects_with_extra_ids(self):
        qn = self._db_operations.quote_name
        selects = []
        for select in self._selects:
            appmodel, field = select.split(".")
            appmodel = self._unquote_name(appmodel)
            field = self._unquote_name(field)
            selects.append(select)
            if appmodel in self._models:
                pk_name = self._models[appmodel]._meta.pk.name
            else:
                pk_name = u"id"
            selects.append("%s.%s" % (qn(appmodel), qn(pk_name)))
        return selects


QueryByExampleFormSet = formset_factory(QueryByExampleForm,
                                        formset=BaseQueryByExampleFormSet,
                                        extra=1,
                                        can_delete=True)
Beispiel #47
0
    def clean(self):
        if any(self.errors):
            return
        if (not self.forms or not any(
                f.cleaned_data.get('enabled')
                for f in self.forms if f.app == amo.FIREFOX)):
            # L10n: {0} is Firefox.
            raise forms.ValidationError(
                _(u'{0} is a required target application.').format(
                    amo.FIREFOX.pretty))
        return self.cleaned_data


PackagerCompatFormSet = formset_factory(PackagerCompatForm,
                                        formset=PackagerCompatBaseFormSet,
                                        extra=0)


class PackagerFeaturesForm(forms.Form):
    about_dialog = forms.BooleanField(
        required=False,
        label=_lazy(u'About dialog'),
        help_text=_lazy(u'Creates a standard About dialog for your '
                        'extension'))
    preferences_dialog = forms.BooleanField(
        required=False,
        label=_lazy(u'Preferences dialog'),
        help_text=_lazy(u'Creates an example Preferences window'))
    toolbar = forms.BooleanField(
        required=False,
Beispiel #48
0
class Page1(forms.Form):
    name = forms.CharField(max_length=100)
    user = forms.ModelChoiceField(queryset=User.objects.all())
    thirsty = forms.NullBooleanField()


class Page2(forms.Form):
    address1 = forms.CharField(max_length=100)
    address2 = forms.CharField(max_length=100)


class Page3(forms.Form):
    random_crap = forms.CharField(max_length=100)


Page4 = formset_factory(Page3, extra=2)


class ContactWizard(NamedUrlWizardView):
    def done(self, form_list, **kwargs):
        c = Context({
            'form_list': [x.cleaned_data for x in form_list],
            'all_cleaned_data': self.get_all_cleaned_data()
        })

        for form in self.form_list.keys():
            c[form] = self.get_cleaned_data_for_step(form)

        c['this_will_fail'] = self.get_cleaned_data_for_step('this_will_fail')
        return HttpResponse(Template('').render(c))
Beispiel #49
0
class BaseDetalleOrdenServiciosFormSet(formsets.BaseFormSet):
    def clean(self):
        for form in self.forms:
            if form.cleaned_data:
                pass
            else:
                raise forms.ValidationError('Registro de datos incompletos.',
                                            code='datos_incompletos')


class BaseDetalleConformidadServicioFormSet(formsets.BaseFormSet):
    def clean(self):
        for form in self.forms:
            if form.cleaned_data:
                pass
            else:
                raise forms.ValidationError('Registro de datos incompletos.',
                                            code='datos_incompletos')


DetalleCotizacionFormSet = formsets.formset_factory(
    FormularioDetalleCotizacion, BaseDetalleCotizacionFormSet, 0)
DetalleOrdenCompraFormSet = formsets.formset_factory(
    FormularioDetalleOrdenCompra, BaseDetalleOrdenCompraFormSet, 0)
DetalleOrdenServiciosFormSet = formsets.formset_factory(
    FormularioDetalleOrdenServicios, BaseDetalleOrdenServiciosFormSet, 0)
DetalleConformidadServicioFormSet = formsets.formset_factory(
    FormularioDetalleConformidadServicio,
    BaseDetalleConformidadServicioFormSet, 0)
Beispiel #50
0
def edit_appointment(request, appointment):
    appointment = get_object_or_404(Appointment, pk=appointment)
    EditAppointmentFormset = formset_factory(OrderAppointmentForm, formset=EditAppointmentBaseFormset, can_delete=True, extra=0)
    date_start = EventRelation.objects.get_events_for_object(appointment).values()[0]['start'].astimezone(timezone(settings.TIME_ZONE))
    date_end = EventRelation.objects.get_events_for_object(appointment).values()[0]['end'].astimezone(timezone(settings.TIME_ZONE))

    initial_data_form = {'customer': appointment.customer, 'comment':appointment.comment, 'duration': date_end.hour - date_start.hour}
    for service in ProductCategory.objects.filter(service=True):
        found = False
        for order in appointment.orders.all():
            if service == order.category:
                initial_data_form['show_{}'.format(service.id)] = True
                initial_data_form['service_{}'.format(service.id)] = order.product
                initial_data_form['cost_{}'.format(service.id)] = order.cost
                found = True
        if not found:
            initial_data_form['show_{}'.format(service.id)] = False

    initial_data_formset = []
    for order in appointment.orders.filter(category__service=False):
        initial_data_formset.append({'category': order.category,'product': order.product, 'quantity': order.quantity, 'cost': order.cost})

    if request.method == 'POST':
        formset = EditAppointmentFormset(request.POST, initial=initial_data_formset)
        form_app = CreateAppointmentForm(request.POST, date=date_start, initial=initial_data_form, appointment=appointment)
        if form_app.is_valid() and formset.is_valid():
            if form_app.has_changed():
                date = form_app.cleaned_data['date']
                event = EventRelation.objects.get_events_for_object(appointment).get()
                event.start = date
                event.end = event.start + timedelta(hours=int(form_app.cleaned_data['duration']))
                event.save()
                appointment.customer = form_app.cleaned_data['customer']
                appointment.comment = form_app.cleaned_data['comment']
                appointment.barber = form_app.cleaned_data['barber']
            for service in ProductCategory.objects.filter(service=True):
                order = appointment.orders.filter(category=service)
                if order:
                    order = order.get()
                    if form_app.cleaned_data['show_{}'.format(service.id)]:
                        order.cost = form_app.cleaned_data['cost_{}'.format(service.id)]
                        order.save()
                    else:
                        order.delete()
                else:
                    if form_app.cleaned_data['show_{}'.format(service.id)]:
                        order = OrderDetail.objects.create(category=service, product=form_app.cleaned_data['service_{}'.format(service.id)], quantity=1, cost=form_app.cleaned_data['cost_{}'.format(service.id)], date=date_start, barber=appointment.barber, customer=form_app.cleaned_data['customer'], appointment_fk=appointment)
                        appointment.orders.add(order)
            if formset.has_changed():
                bulk_edit = []
                bulk_create = []
                for index, form in enumerate(formset):
                    if form.has_changed():
                        product = initial_data_formset[index]['product'] if index < len(initial_data_formset) else None
                        order = appointment.orders.filter(product=product)
                        if form in formset.deleted_forms and order:
                            order = order.get()
                            order.delete()
                        else:
                            if order:
                                bulk_edit.append((order.get().id, {'product': form.cleaned_data['product'], 'cost': form.cleaned_data['cost'], 'quantity': form.cleaned_data['quantity']}))
                            else:
                                if form not in formset.deleted_forms:
                                    bulk_create.append({'category': form.cleaned_data['category'], 'product': form.cleaned_data['product'], 'quantity': form.cleaned_data['quantity'], 'cost': form.cleaned_data['cost']})
                for bulk in bulk_edit:
                    order = OrderDetail.objects.get(pk=bulk[0])
                    order.product = bulk[1]['product']
                    order.cost = bulk[1]['cost']
                    order.quantity = bulk[1]['quantity']
                    order.save()
                for bulk in bulk_create:
                    order = OrderDetail.objects.create(category=bulk['category'], product=bulk['product'], quantity=bulk['quantity'], cost=bulk['cost'], date=date_start, barber=appointment.barber, customer=appointment.customer, appointment_fk=appointment)
                    appointment.orders.add(order)
            appointment.save()
    else:
        formset = EditAppointmentFormset(initial=initial_data_formset)
        form_app = CreateAppointmentForm(date=date_start, initial=initial_data_form, barber=appointment.barber)

    return render(request, 'admin/edit_appointment.html', {'appointment': appointment, 'formset': formset, 'barber': appointment.barber, 'form': form_app, 'time':'{}-00'.format(date_start.hour)})
Beispiel #51
0
        self.extra = len(self.mxcells)
        self.max_num = len(self.mxcells)
        self.absolute_max = len(self.mxcells)
        self.validate_max = len(self.mxcells)
        super(BaseICMatrixFormset, self).__init__(*args, **kwargs)

    def _construct_form(self, i, **kwargs):
        kwargs['mxcell'] = self.mxcells[i]

        # print(kwargs)
        form = super(BaseICMatrixFormset, self)._construct_form(i, **kwargs)
        # print(form)
        return form


BaseFormset = formset_factory(form=ICMatrix, formset=BaseICMatrixFormset)
print(BaseFormSet)


class ObjectivesForm(forms.ModelForm):
    class Meta:
        model = Objectives
        exclude = ('assessed_cr', )

    def __init__(self, *args, **kwargs):
        super(ObjectivesForm,
              self).__init__(*args, **kwargs)  # Call to ModelForm constructor
        self.fields['transaction_objective'].widget.attrs[
            'style'] = "width:850px"
        # self.fields['transaction_objective'].required = False
        # for i in range(2):
Beispiel #52
0
            form.app = app
            cats = sorted(app_cats[key], key=lambda x: x.name)
            form.fields['categories'].choices = [(c.id, c.name) for c in cats]

            # If this add-on is featured for this application, category
            # changes are forbidden.
            if not acl.action_allowed(self.request, 'Addons', 'Edit'):
                form.disabled = (app and self.addon.is_featured(app))

    def save(self):
        for f in self.forms:
            f.save(self.addon)


CategoryFormSet = formset_factory(form=CategoryForm,
                                  formset=BaseCategoryFormSet,
                                  extra=0)


def icons():
    """
    Generates a list of tuples for the default icons for add-ons,
    in the format (psuedo-mime-type, description).
    """
    icons = [('image/jpeg', 'jpeg'), ('image/png', 'png'), ('', 'default')]
    dirs, files = storage.listdir(settings.ADDON_ICONS_DEFAULT_PATH)
    for fname in files:
        if '32' in fname and not 'default' in fname:
            icon_name = fname.split('-')[0]
            icons.append(('icon/%s' % icon_name, icon_name))
    return icons
Beispiel #53
0
 def get_formset(self):
     """
     Returns the formset class from the formset factory
     """
     return formset_factory(self.get_form_class(),
                            **self.get_factory_kwargs())
Beispiel #54
0
    def post(self, request):
        """
        The form has been submitted, process it.
        """
        logger = logging.getLogger(
            "peering.manager.views.ImportFromObjectView")

        if "_add" in request.POST and not request.POST.getlist("pk"):
            messages.error(request, "No objects selected.")
            return redirect(self.get_return_url(request))

        # Prepare the form
        if not self.custom_formset:
            ObjectFormSet = formset_factory(self.form_model, extra=0)
        else:
            ObjectFormSet = formset_factory(self.form_model,
                                            formset=self.custom_formset,
                                            extra=0)

        # Get dependencies
        base_objects = self.get_base_objects(request.POST.getlist("pk"))
        if not base_objects:
            # We don't have base objects to handle, proceed as if we were in the next
            # step of the form (object creation)
            formset = ObjectFormSet(data=request.POST)
        else:
            # Proceed base object and fill in the form
            processed_base_objects = [
                self.process_base_object(request, o) for o in base_objects
            ]
            formset = ObjectFormSet(
                initial=self.sort_objects(processed_base_objects))

        created_objects = []
        if formset.is_valid():
            logger.debug("formset validation was successful")

            with transaction.atomic():
                for form in formset:
                    if form.is_valid():
                        instance = form.save()
                        created_objects.append(instance)

            if created_objects:
                count = len(created_objects)
                msg = f"Imported {count} {created_objects[0]._meta.verbose_name if count == 1 else created_objects[0]._meta.verbose_name_plural}"
                logger.info(msg)
                messages.success(request, msg)

            return redirect(self.get_return_url(request))
        else:
            logger.debug("formset validation failed")

        return render(
            request,
            self.template_name,
            {
                "formset": formset,
                "object_type": self.form_model._meta.model._meta.verbose_name,
                "return_url": self.get_return_url(request),
            },
        )
Beispiel #55
0
            'twitter_feed',
            'tags',
        ]


class RelatedLinkForm(forms.Form):
    link = forms.URLField(
        required=False,    # because we'll only save those that are there anyway
        error_messages={'invalid': 'Please enter a full URL, including the ‘http://’!'},
        widget=forms.TextInput,
    )

    def clean_link(self):
        link = self.cleaned_data.get('link')
        if not link:
            return None
        if not link.startswith('http://') or link.startswith('https://'):
            return 'http://' + link
        else:
            return link
RelatedLinkFormset = formset_factory(RelatedLinkForm, extra=1, formset=OrderedFormset)
RelatedLinkFormset.title = 'Web links'
RelatedLinkFormset.help_text = 'Paste in the URL of the website in full, including the ‘http://’'


class AreaForm(forms.Form):
    area = forms.ModelChoiceField(queryset=Area.objects.all())

AreaFormSet = formset_factory(AreaForm, extra=1, formset=OrderedFormset)
AreaFormSet.title = 'Areas'
AreaFormSet.help_text = help_text=help_text('rca.RcaNowPageArea', 'area')
Beispiel #56
0
    def questions_update_view(self, request, election, poll):
        from zeus.utils import poll_reverse
        from zeus.forms import ScoresForm, RequiredFormset, DEFAULT_ANSWERS_COUNT

        extra = 1
        if poll.questions_data:
            extra = 0

        questions_formset = formset_factory(ScoresForm,
                                            formset=RequiredFormset,
                                            extra=extra,
                                            can_delete=True,
                                            can_order=True)
        if request.method == 'POST':
            formset = questions_formset(request.POST)
            if formset.is_valid():
                questions_data = []
                for question in formset.cleaned_data:
                    if not question:
                        continue

                    # force sort of answers by extracting index from answer key.
                    # cast answer index to integer, otherwise answer_10 would
                    # be placed before answer_2
                    answer_index = lambda a: int(a[0].replace('answer_', ''))
                    isanswer = lambda a: a[0].startswith('answer_')
                    answer_values = list(
                        filter(isanswer, iter(question.items())))
                    sorted_answers = sorted(answer_values, key=answer_index)

                    question['answers'] = [x[1] for x in sorted_answers]
                    question['scores'] = [
                        p for p in question['scores'] if p is not None
                    ]
                    question['question_subtitle'] = ",".join(
                        question['scores'])

                    for k in list(question.keys()):
                        if k in ['DELETE', 'ORDER']:
                            del question[k]

                    questions_data.append(question)

                poll.questions_data = questions_data
                poll.update_answers()
                poll.logger.info("Poll ballot updated")
                poll.save()

                url = poll_reverse(poll, 'questions')
                return HttpResponseRedirect(url)
        else:
            formset = questions_formset(initial=poll.questions_data)

        context = {
            'default_answers_count': DEFAULT_ANSWERS_COUNT,
            'formset': formset,
            'max_questions_limit': 1,
            'election': election,
            'poll': poll,
            'module': self
        }

        set_menu('questions', context)
        tpl = 'election_modules/simple/election_poll_questions_manage'
        return render_template(request, tpl, context)
Beispiel #57
0
def add_sensor(request):
    user = request.user
    VariableFormSet = formset_factory(ModifyVariableForm, extra=0)
    errors_sensor_form = False
    errors = False
    if request.method == 'POST':
        if user.auth_level < 2:
            context = {'title':'Not authorized!', 'error_msg':'You are not allowed to add sensors. Please contact admin to request rights to modify/add sensors.'}
            return render(request, 'management/error.html', context)
        else:
            add_sensor_form = AddSensorForm(request.POST, prefix='add_sensor')
            communication_technology = request.POST['communication_technology']
            protocol = request.POST['protocol']
            if add_sensor_form.is_valid():
                new_sensor = add_sensor_form.save()
                new_sensor.sample_rate = Sample_rate.objects.get(id=request.POST['add_sensor-sample_rate'])
                new_sensor.sensitivity = Sensitivity.objects.get(id=request.POST['add_sensor-sensitivity'])
                if communication_technology ==  'Wlan':
                    instance = Wlan.objects.get(pk=request.POST['communication_instance'])
                    modified_wlan_form = ModifyWlanForm(request.POST, instance=instance, prefix='wlan')
                    communication_instances = Wlan.objects.all()
                    modify_communication_form = modified_wlan_form
                    if modified_wlan_form.is_valid():
                        modified_wlan_form.save()
                        new_sensor.communication_object = instance
                    else:
                        errors = True
                elif communication_technology == 'Nb_iot':
                    instance = Nb_iot.objects.get(pk=request.POST['communication_instance'])
                    modified_nb_iot_form = ModifyNbIotForm(request.POST, instance=instance, prefix='nb_iot')
                    communication_instances = Nb_iot.objects.all()
                    modify_communication_form = modified_nb_iot_form
                    if modified_nb_iot_form.is_valid():
                        modified_nb_iot_form.save()
                        new_sensor.communication_object = instance
                    else:
                        errors = True
                if protocol == 'HTTP':
                    instance = HTTP.objects.get(pk=request.POST['protocol_instance'])
                    modified_http_form = ModifyHTTPForm(request.POST, instance=instance, prefix='http')
                    protocol_instances = HTTP.objects.all()
                    modify_protocol_form = modified_http_form
                    if modified_http_form.is_valid():
                        modified_http_form.save()
                        new_sensor.protocol_object = instance
                    else:
                        errors = True
                elif protocol == 'HTTPS':
                    instance = HTTPS.objects.get(pk=request.POST['protocol_instance'])
                    modified_https_form = ModifyHTTPSForm(request.POST, instance=instance, prefix='https')
                    protocol_instances = HTTPS.objects.all()
                    modify_protocol_form = modified_https_form
                    if modified_https_form.is_valid():
                        modified_https_form.save()
                        new_sensor.protocol_object = instance
                    else:
                        errors = True
                elif protocol == 'MQTT':
                    instance = MQTT.objects.get(pk=request.POST['protocol_instance'])
                    modified_MQTT_form = ModifyMQTTForm(request.POST, instance=instance, prefix='mqtt')
                    mqtt_instances = MQTT.objects.all()
                    modify_protocol_form = modified_MQTT_form
                    if modified_MQTT_form.is_valid():
                        modified_MQTT_form.save()
                        new_sensor.protocol_object = instance
                    else:
                        errors = True
                variable_formset = VariableFormSet(request.POST)
                if variable_formset.is_valid():
                    for variable_form in variable_formset:
                        name = variable_form.cleaned_data.get('name')
                        unit = variable_form.cleaned_data.get('unit')
                        if name and unit:
                            v = Variable(sensor=new_sensor, name=name, unit=unit)
                            v.save()
                else:
                    errors = True
                if not errors:
                    new_sensor.status = Sensor.WAITING_FOR_UPDATE
                    new_sensor.adder = user
                    new_sensor.latest_modifier = user
                    new_sensor.save()
                    create_new_sensor(new_sensor)
                    return redirect('browse_sensors')

                else:
                    new_sensor.delete()
            else:
                errors_sensor_form = True
    #If not post fill the form
    #Give initial values
    found = False
    for communication_type_class in AVAILABLE_COMMUNICATION_TECHNOLOGIES_CLASSES:
        if communication_type_class.objects.all().exists():
            found = True
            communication_object = communication_type_class.objects.all()[0]
            communication_type = communication_object.__class__.__name__
            break
    if not found:
        context = {'title':'You need to create communication object!', 'error_msg':'You need to create communication object before adding new sensors.'}
        return render(request, 'configurator/error.html', context)
    found = False
    for protocol_type_class in AVAILABLE_PROTOCOLS_CLASSES:
        if protocol_type_class.objects.all().exists():
            found = True
            protocol_object = protocol_type_class.objects.all()[0]
            protocol = protocol_object.__class__.__name__
            break
    if not found:
        context = {'title':'You need to add application layer protocol objects!', 'error_msg':'You need to create application layer protocol object before adding sensor.'}
        return render(request, 'configurator/error.html', context)
    if not Type_of_sensor.objects.all().exists():
        context = {'title':'Not authorized!', 'error_msg':'You are not allowed to add sensor. Please contact admin to request rights to modify/add sensors.'}
        return render(request, 'configurator/error.html', context)
    initial_sensor_type = Type_of_sensor.objects.all()[0]
    available_sample_rates = Sample_rate.objects.filter(model=initial_sensor_type.pk)
    initial_sample_rate = available_sample_rates[0]
    available_sensitivities = initial_sample_rate.supported_sensitivities.all()
    initial_sensitivity = available_sensitivities[0]
    default_variables = Default_variable.objects.filter(type_of_sensor=initial_sensor_type)
    initial_data = [{'name': dv.name, 'unit': dv.unit}
                    for dv in default_variables]
    modify_variable_forms = VariableFormSet(initial=initial_data)
    if user.auth_level >= 2:
        if not errors_sensor_form:
            add_sensor_form = AddSensorForm(prefix='add_sensor')
        if not errors:
            modify_communication_form = ModifyWlanForm(instance=communication_object, prefix='wlan')
            communication_instances = Wlan.objects.all()
            modify_protocol_form = ModifyHTTPForm(instance=protocol_object, prefix='http')
            protocol_instances = HTTP.objects.all()
    else:
        context = {'title':'Not authorized!', 'error_msg':'You are not allowed to add sensor. Please contact admin to request rights to modify/add sensors.'}
        return render(request, 'management/error.html', context)
    context =   {'add_sensor_form' : add_sensor_form,
                'available_sample_rates': available_sample_rates,
                'current_sample_rate': initial_sample_rate.id,
                'available_sensitivities': available_sensitivities,
                'current_sensitivity': initial_sensitivity.id,
                'current_communication_technology': communication_object.__class__.__name__,
                'current_communication_id': communication_object.id,
                'communication_instances': communication_instances,
                'modify_communication_form': modify_communication_form,
                'available_communication_technologies': AVAILABLE_COMMUNICATION_TECHNOLOGIES,
                'current_protocol': protocol_object.__class__.__name__,
                'current_protocol_id': protocol_object.id,
                'protocol_instances': protocol_instances,
                'modify_protocol_form': modify_protocol_form,
                'available_protocols': AVAILABLE_PROTOCOLS,
                'modify_variable_forms': modify_variable_forms,
    }
    return render(request, 'management/add_sensor.html', context)
Beispiel #58
0
 def get_children_formset(self):
     if self.module.child_form:
         return formset_factory(self.module.child_form, can_delete=True, extra=1)(**self.get_children_formset_kwargs())
def _initialize_offer_preference_formset(internships_offers):
    offer_preference_formset = formset_factory(OfferPreferenceForm, formset=OfferPreferenceFormSet,
                                               extra=internships_offers.count(), min_num=internships_offers.count(),
                                               max_num=internships_offers.count(), validate_min=True, validate_max=True)
    return offer_preference_formset
Beispiel #60
0
def campaign_edit_target(request, listid, targetid):
    target = get_object_or_404(Target, id=targetid)
    targetlist = get_object_or_404(TargetList, id=listid)

    if targetlist.author not in request.user.swordphishuser.visible_users():
        return HttpResponseForbidden()

    if not targetlist.targets.filter(id=targetid):
        return HttpResponseForbidden()

    targetform = NewTargetForm(instance=target)

    formset = formset_factory(AttributeForm, extra=0)

    attformset = formset(initial=target.attributes.all().values())

    if request.method == "GET":
        return render(
            request, 'Main/Campaigns/Targets/edittarget.html', {
                'targetlist': targetlist,
                'targetid': targetid,
                'targetform': targetform,
                'attformset': attformset
            })

    if request.method == "POST":
        targetform = NewTargetForm(request.POST)
        attformset = formset(request.POST)

        if not (targetform.is_valid() and attformset.is_valid()):
            return render(
                request, 'Main/Campaigns/Targets/edittarget.html', {
                    'targetlist': targetlist,
                    'targetid': targetid,
                    'targetform': targetform,
                    'attformset': attformset
                })

        tl = targetlist.targets.filter(
            mail_address=targetform.cleaned_data["mail_address"])

        for tar in tl:
            if tar.id != target.id:
                return render(
                    request, 'Main/Campaigns/Targets/edittarget.html', {
                        'targetlist': targetlist,
                        'targetid': targetid,
                        'targetform': targetform,
                        'attformset': attformset,
                        'target_already_exists': True
                    })

        target.mail_address = targetform.cleaned_data["mail_address"]
        target.save()
        target.attributes.all().delete()
        for attform in attformset:
            target.addAttribute(attform.cleaned_data["key"],
                                attform.cleaned_data["value"])

        return HttpResponse("Ok")

    return HttpResponseForbidden()