def __init__(self, *args, **kwargs): super(CheckoutForm, self).__init__(*args, **kwargs) data_projects_url = reverse("shepherd:ajax_load_projects") data_project_url = reverse("shepherd:ajax_load_project") overwatch_url = reverse("shepherd:ajax_domain_overwatch") for field in self.fields: self.fields[field].widget.attrs["autocomplete"] = "off" self.fields["client"].empty_label = "-- Select a Client --" self.fields["client"].label = "" self.fields["activity_type"].empty_label = "-- Select Activity --" self.fields["activity_type"].label = "" self.fields["project"].empty_label = "-- Select a Client First --" self.fields["project"].label = "" self.fields["project"].queryset = Project.objects.none() self.fields["start_date"].widget.attrs["placeholder"] = "mm/dd/yyyy" self.fields["start_date"].widget.input_type = "date" self.fields["end_date"].widget.attrs["placeholder"] = "mm/dd/yyyy" self.fields["end_date"].widget.input_type = "date" self.fields["note"].widget.attrs[ "placeholder"] = "This domain will be used for..." self.fields["note"].label = "" self.helper = FormHelper() self.helper.form_method = "post" self.helper.form_class = "newitem" self.helper.form_show_labels = False self.helper.attrs = { "data-projects-url": data_projects_url, "data-project-url": data_project_url, "overwatch-url": overwatch_url, } self.helper.form_id = "checkout-form" self.helper.layout = Layout( HTML(""" <h4 class="icon project-icon">Project & Activity Information</h4> <hr> """), "client", "project", Row( Column("start_date", css_class="form-group col-md-6 mb-0"), Column("end_date", css_class="form-group col-md-6 mb-0"), css_class="form-row", ), "activity_type", HTML(""" <h4 class="icon comment-icon">Additional Information</h4> <hr> """), "note", "domain", "operator", ButtonHolder( Submit("submit", "Submit", css_class="btn btn-primary col-md-4"), HTML(""" <button onclick="window.location.href='{{ cancel_link }}'" class="btn btn-outline-secondary col-md-4" type="button">Cancel</button> """), ), ) # Prevent "not one of the valid options" errors from AJAX project filtering if "client" in self.data: try: client_id = int(self.data.get("client")) self.fields["project"].queryset = Project.objects.filter( client_id=client_id).order_by("codename") except (ValueError, TypeError): pass elif self.instance.pk: self.fields[ "project"].queryset = self.instance.client.project_set.order_by( "codename")
subsidencePackage = forms.CharField(max_length=100, required=False) ModelInputLayoutEdit = Layout( HTML( '<div class="col-xs-12 col-sm-6"> ' '<div class="form-group" id="modelinput"> ' '{% load crispy_forms_tags %} ' '{% for form in model_input_formset.forms %} ' '<form id="{{form.form_id}}" action="{{ form.action }}" ' 'method="POST" enctype="multipart/form-data"> ' '{% crispy form %} ' '<div class="row" style="margin-top:10px">' '<div class="col-md-12">' '<span class="glyphicon glyphicon-trash icon-button btn-remove" data-toggle="modal" ' 'data-placement="auto" title="Delete Model Input" ' 'data-target="#delete-modelinput-element-dialog_{{ form.number }}"></span>' '</div>' '<div class="col-md-3">' '<button type="button" class="btn btn-primary pull-right btn-form-submit">' 'Save changes</button>' # TODO: TESTING '</div>' '</div>' '{% crispy form.delete_modal_form %} ' '</form> ' '{% endfor %}</div>' '</div> '), HTML( '<div style="margin-top:10px" class="col-md-2">' '<p><a id="add-modelinput" class="btn btn-success" data-toggle="modal" ' 'data-target="#add-modelinput-dialog">'
def __init__(self, *args, **kwargs): super(GroupForm, self).__init__(*args, **kwargs) # add MacroGroups by users self.fields['macrogroups'].queryset = get_objects_for_user(self.request.user, 'view_macrogroup', MacroGroup) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div( Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>".format(_('General data'))), css_class='box-header with-border' ), Div( 'name', 'title', Field('description', css_class='wys5', style="width:100%;"), Field('lang', css_class='select2', style="width:100%;"), css_class='box-body', ), css_class='box box-success' ), css_class='col-md-6' ), crispyBoxACL(self), crispyBoxMacroGroups(self), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-globe'></i> {}</h3>".format(_('GEO data'))), css_class='box-header with-border' ), Div( Div( Div( Field('srid', css_class='select2', style="width:100%;"), css_class='col-md-12' ), css_class='row' ), css_class='box-body' ), css_class='box box-danger' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-map'></i> {}</h3>".format(_('Base Layers and Map default features'))), Div( HTML("<button class='btn btn-box-tool' data-widget='collapse'><i class='fa fa-minus'></i></button>"), css_class='box-tools', ), css_class='box-header with-border' ), Div( Field('mapcontrols', **{'css_class': 'select2 col-md-12', 'multiple': 'multiple', 'style': 'width:100%;'}), Field('baselayers', **{'css_class': 'select2 col-md-12', 'multiple': 'multiple', 'style': 'width:100%;'}), AppendedText('background_color', '<i></i>', css_class='colorpicker'), css_class='box-body' ), css_class='box box-danger' ), css_class='col-md-6' ), css_class='row' ), Div( Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-file-image-o'></i> {}</h3>".format(_('Logo/Picture'))), css_class='box-header with-border' ), Div( Div( 'header_logo_img', HTML("""<img {% if not form.header_logo_img.value %}style="display:none;"{% endif %} class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.header_logo_img.value }}">""", ), 'form_id', 'upload_url', 'delete_url', css_class='col-md-12' ), Div( #AppendedText('header_logo_height','px'), 'header_logo_link', css_class='col-md-12' ), css_class='box-body' ), css_class='box box-primary' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-copyright'></i> {}</h3>".format(_('Copyright'))), Div( HTML("<button class='btn btn-box-tool' data-widget='collapse'><i class='fa fa-minus'></i></button>"), css_class='box-tools', ), css_class='box-header with-border' ), Div( Field('header_terms_of_use_text',css_class='wys5'), 'header_terms_of_use_link', css_class='box-body' ), css_class='box box-default {}'.format(self.checkEmptyInitialsData('header_terms_of_use_text','header_terms_of_use_link')) ), css_class='col-md-6' ), css_class='row' ) )
def __init__(self, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.fields['langlevel'] = forms.ChoiceField( choices=((str(x), x) for x in range(1, 101))) self.fields['langlevel'].label = '2° Language Level' self.fields['feecode'].empty_label = 'Neutral mood' self.helper = FormHelper() self.helper.layout = Layout( Div( Field('cliname', css_class='form-control'), Field('gencode', css_class='form-control'), Field('feecode', css_class='form-control'), Field('clidescription', css_class='form-control'), css_class='edit-details', ), Div( Field('marcode', css_class='form-control'), Field('clibirthdate', css_class='form-control'), Field('citcode', css_class='form-control'), Field('ethcode', css_class='form-control'), Field('educode', css_class='form-control'), css_class='column-edit', ), Div( Field('lancodefirst', css_class='form-control'), Field('lancodesecond', css_class='form-control'), Field('langlevel', css_class='form-control'), HTML('<label class="lblpercent">%</label>'), Field('ocucode', css_class='form-control'), HTML('<label class="lblpercent">$</label>'), Field('inccode', css_class='form-control'), HTML('<label class="lblpercent">USD</label>'), css_class='col-md-6 col-xs-12 column-edit', ), Div( HTML('<span class="title">Physical description</span><hr >'), css_class='separator', ), Div( Field('bodycode', css_class='form-control'), Field('heicode', css_class='form-control'), Field('weicode', css_class='form-control'), css_class='column-edit', ), Div( Field('eyecode', css_class='form-control'), Field('haicode', css_class='form-control'), Field('hlecode', css_class='form-control'), css_class='column-edit', ), Div( HTML('<span class="title">Other</span><hr >'), css_class='separator', ), Div( Field('frecodedrink', css_class='form-control'), Field('frecodesmoke', css_class='form-control'), Field('zodcode', css_class='form-control'), css_class='column-edit', ), Div( Field('relcode', css_class='form-control'), Field('chicode', css_class='form-control'), css_class='column-edit', ), FormActions( Submit('submit', 'SAVE', css_class='btn-primary form-control')), )
class HazardForm(forms.ModelForm): helper = FormHelper() helper.form_tag = False # removes auto-inclusion of form tag in template helper.disable_csrf = True helper.layout = Layout( Accordion( AccordionGroup( _('Hazard Details'), Field('geom', type='hidden', id='hazPoint'), Field('date', id='hazard_date', template='mapApp/util/%s_datepicker.html', autocomplete='off'), Field('hazard_category', id='hazard-category', type="hidden"), Field('i_type', id='hazard-type'), ), AccordionGroup( _('Description'), Field('details', placeholder=_('optional')), css_id='hazard-description', ), AccordionGroup( _('Personal Details'), HTML(why_personal_link), Div(Div(HTML(why_personal_well), css_class="well"), css_class='why-personal collapse'), Field('source'), Field('age'), Field('birthmonth'), Field('sex'), Field('regular_cyclist'), css_id='hazard-personal-details', ), )) def is_valid(self): # run default, parent validation first valid = super(HazardForm, self).is_valid() # check date to ensure incident occurred within the past 2 years and not in the future limit = datetime.timedelta(weeks=-52) min_date = datetime.datetime.today() + limit if 'date' in self.cleaned_data: submitted_date = self.cleaned_data['date'] if submitted_date > datetime.datetime.today(): self._errors['date'] = [ _(u'The date can\'t be in the future.') ] return False if submitted_date < min_date: self._errors['date'] = [ _(u'Incidents must have occurred within the past year.') ] return False return valid class Meta: model = Hazard exclude = ['p_type', 'hazard_fixed', 'expires_date']
def create_sale_tickets_form(festival, sale, performance, post_data = None): # Validate parameters assert festival assert sale assert performance # Get ticket types and efringers ticket_types = [] for ticket_type in sale.festival.ticket_types.order_by('seqno'): ticket_types.append(ticket_type) efringers = [] if sale.customer_user: for fringer in sale.customer_user.fringers.order_by('name'): efringers.append(fringer) # Create form form = SaleTicketsForm(ticket_types, efringers, data = post_data) # Add crispy form helper form.helper = FormHelper() form.helper.form_id = 'sale-tickets-form' form.helper.form_class = 'form-horizontal' form.helper.label_class = 'col-6' form.helper.field_class = 'col-6' tabs = [Tab('Tickets', *(Field(form.ticket_field_name(tt)) for tt in form.ticket_types), css_class = 'pt-2')] if sale.customer_user: tab_content = [] if form.efringers: fringers_available = [] fringers_used = [] fringers_empty = [] for fringer in form.efringers: if fringer.is_available(performance): fringers_available.append(fringer) else: form.fields[SaleTicketsForm.efringer_field_name(fringer)].disabled = True if fringer.is_available(): fringers_used.append(fringer) else: fringers_empty.append(fringer) if fringers_available: tab_content.append(HTML("<p>Available for this performance.</p>")) tab_content.extend(Field(form.efringer_field_name(ef)) for ef in fringers_available) if fringers_used: tab_content.append(HTML("<p>Already used for this performance.</p>")) tab_content.extend(Field(form.efringer_field_name(ef)) for ef in fringers_used) if fringers_empty: tab_content.append(HTML("<p>No tickets remaining.</p>")) tab_content.extend(Field(form.efringer_field_name(ef)) for ef in fringers_empty) else: tab_content.append(HTML("<p>None.</p>")) tabs.append(Tab( 'eFringers', *tab_content, css_class = 'pt-2', )) form.helper.layout = Layout( TabHolder(*tabs), Button('add', 'Add', css_class = 'btn-primary', onclick = 'saleAddTickets()'), ) # Return form return form
def __init__(self, *args, **kwargs): if 'domain' not in kwargs: raise Exception("Expected domain in kwargs") self.domain = kwargs.pop('domain') self.enhancements_enabled = AUTO_CASE_UPDATE_ENHANCEMENTS.enabled( self.domain) super(AddAutomaticCaseUpdateRuleForm, self).__init__(*args, **kwargs) if not self.enhancements_enabled: # Always set the value of filter_on_server_modified to true when the # enhancement toggle is not set self.data = self.data.copy() self.initial['filter_on_server_modified'] = 'true' self.data['filter_on_server_modified'] = 'true' # We can't set these fields to be required because they are displayed # conditionally and we'll confuse django validation if we make them # required. However, we should show the asterisk for consistency, since # when they are displayed they are required. self.fields['update_property_name'].label = _( "Property") + '<span class="asteriskField">*</span>' self.fields['update_property_value'].label = _( "Value") + '<span class="asteriskField">*</span>' self.helper = FormHelper() self.helper.form_class = 'form form-horizontal' self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-4 col-md-3' self.helper.form_method = 'POST' self.helper.form_action = '#' if self.enhancements_enabled: self.allow_updates_without_closing() _update_property_fields = [ _f for _f in [ Field( 'update_property_name', ng_model='update_property_name', css_class='case-property-typeahead', ), Field( 'property_value_type', ng_model='property_value_type', ) if self.enhancements_enabled else None, Field( 'update_property_value', ng_model='update_property_value', ) ] if _f ] _basic_info_fields = [ _f for _f in [ Field( 'name', ng_model='name', ), Field( 'case_type', ng_model='case_type', ), Field( 'filter_on_server_modified', ng_model='filter_on_server_modified', ) if self.enhancements_enabled else None, hqcrispy.B3MultiField( _("Close Case") + '<span class="asteriskField">*</span>', Div( hqcrispy.MultiInlineField( 'server_modified_boundary', ng_model='server_modified_boundary', ), css_class='col-sm-6', ), Div( HTML('<label class="control-label">%s</label>' % _('days after the case was last modified.')), css_class='col-sm-6', ), help_bubble_text=_( "This will close the case if it has been " "more than the chosen number of days since " "the case was last modified. Cases are " "checked against this rule weekly."), css_id='server_modified_boundary_multifield', label_class=self.helper.label_class, field_class='col-sm-8 col-md-6', ng_show='showServerModifiedBoundaryField()', ), Field( 'action', ng_model='action', ), Div(*_update_property_fields, ng_show='showUpdateProperty()') ] if _f ] self.set_case_type_choices(self.initial.get('case_type')) self.helper.layout = Layout( Fieldset(_("Basic Information"), *_basic_info_fields), Fieldset( _("Filter Cases to Close (Optional)"), Field( 'conditions', type='hidden', ng_value='conditions', ), Div(ng_include='', src="'conditions.tpl'"), ), FormActions( StrictButton( _("Save"), type='submit', css_class='btn btn-primary col-sm-offset-1', ), ), )
def __init__(self, *args, **kwargs): super(PersonForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper = FormHelper() self.helper.form_method = "post" self.helper.html5_required = True if self.instance is not None and self.instance.membertype == Person.CHILD: nameFieldSet = Fieldset( "Barnets oplysninger", Div( Div(Field("gender"), css_class="col-md-2"), Div(Field("name"), css_class="col-md-10"), Div( Field( "birthday", input_formats=(settings.DATE_INPUT_FORMATS), ), css_class="col-md-4", ), Div(Field("email"), css_class="col-md-4"), Div(Field("phone"), css_class="col-md-4"), css_class="row", ), ) self.fields["birthday"].required = True self.fields["gender"].choices = Person.MEMBER_GENDER_CHOICES else: nameFieldSet = Fieldset( "Forældres / Værges oplysninger", Div( Div(Field("gender"), css_class="col-md-2"), Div(Field("name"), css_class="col-md-10"), Div( Field( "birthday", input_formats=(settings.DATE_INPUT_FORMATS), ), css_class="col-md-4", ), Div(Field("email"), css_class="col-md-4"), Div(Field("phone"), css_class="col-md-4"), css_class="row", ), ) self.fields["email"].required = True self.fields["phone"].required = True self.fields["gender"].choices = Person.MEMBER_ADULT_GENDER_CHOICES self.fields["birthday"].widget = forms.DateInput(attrs={"type": "date"}) self.fields["streetname"].required = True self.fields["housenumber"].required = True self.fields["zipcode"].required = True self.fields["city"].required = True self.helper.layout = Layout( nameFieldSet, Fieldset( "Adresse oplysninger", Div( Div( Field("search_address", id="search-address"), css_class="col-md-10", ), Div( Field("manual_entry", id="manual-entry"), Field("address_global", id="address-global"), css_class="col-md-2", ), Div( Field( "streetname", readonly=True, css_class="autofilled-address" ), css_class="col-md-9", ), Div( Field( "housenumber", readonly=True, css_class="autofilled-address" ), css_class="col-md-1", ), Div( Field("floor", readonly=True, css_class="autofilled-address"), css_class="col-md-1", ), Div( Field("door", readonly=True, css_class="autofilled-address"), css_class="col-md-1", ), Div( Field("zipcode", readonly=True, css_class="autofilled-address"), css_class="col-md-2", ), Div( Field("city", readonly=True, css_class="autofilled-address"), css_class="col-md-5", ), Div( Field( "placename", readonly=True, css_class="autofilled-address" ), css_class="col-md-5", ), Field("dawa_id", "", id="id_dawa_id"), css_class="row", ), ), Submit( "submit", "Opret" if self.instance.id is None else "Ret", css_class="btn-success", ), HTML( """<a class="btn btn-link" href="{% url 'family_detail' %}">Fortryd</a>""" ), ) self.helper.render_unmentioned_fields = False self.fields["birthday"].input_formats = settings.DATE_INPUT_FORMATS
def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) self.user = kwargs.pop('user', None) self.status = kwargs.pop('status', None) self.local_contacts = kwargs.pop('local_contacts', None) self.proposer = kwargs.pop('proposer', None) super(ProposalsForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.include_media = False self.helper.form_class = 'form-horizontal' self.helper.form_method = 'post' self.helper.field_class = 'col-sm-10' self.helper.label_class = 'col-sm-2' if self.status: cancelbuttoncode = """<a role="button" class="btn btn-default" href="{% url "app_proposals_detail" object.slug %}">Cancel</a>""" else: cancelbuttoncode = """<a role="button" class="btn btn-default" href="{% url "home" %}">Cancel</a>""" self.helper.layout = Layout( Fieldset(None, 'name', 'abstract', 'scientific_bg', 'proposaltype', 'student', 'thesis_topic', 'supervisor', 'grants', 'categories', 'local_contacts', 'coproposers'), ButtonHolder( Submit('submit', 'Save', css_class='button white'), HTML(cancelbuttoncode), )) self.fields[ 'name'].help_text = "Enter the name of the proposal, maximum length is 500 characters, however we recommend shorter." self.fields[ 'abstract'].help_text = "Mandatory abstract, maximum length 5000 characters." self.fields[ 'proposaltype'].help_text = "Select type of proposal. See <a href=" "/how-to/proposal" " target=" "_blank" ">help</a> for description and how to choose the correct one." self.fields['local_contacts'].widget.attrs = { 'data-theme': 'bootstrap4', } self.fields[ 'local_contacts'].help_text = "You need to select at least one local contact. He/she will do feasibility check of your proposal. More local contacts can be added later if needed." self.fields['coproposers'].widget.attrs = { 'data-theme': 'bootstrap4', } self.fields[ 'coproposers'].help_text = "You can (optionally) add coporposers to your team. They will see the proposal and will be able to book measurement for it. If the proposal is connected with any funding, <b>PI of the grant MUST be part of the team</b> (if he/she is not proposer)." self.fields['supervisor'].widget.attrs = { 'data-theme': 'bootstrap4', } self.fields[ 'grants'].help_text = "If the proposal is connected with any funding, add its abbreviation and/or number. In case of more fundings, separate by comma. Example: <i>'GAČR 19-000123S, ERC BoBEK 123456'</i>." self.fields[ 'categories'].help_text = "Optional proposal categories. Please tick all fields which fits for your proposal." self.fields[ 'student'].help_text = "Student proposals needs to mention supervisor and thesis topic." self.fields['student'].widget.attrs[ 'onclick'] = "javascript:toggleDivs();" if not self.user.groups.filter(name='localcontacts').exists(): self.fields["proposaltype"].choices = [ t for t in self.fields["proposaltype"].choices if t[0] != 'T' ] #remove test proposal if self.status and self.status != "P": for f in self.fields.values(): f.disabled = True # user office can change some stuff if self.user.has_perm('app.change_status') and self.status in "SU": self.fields['local_contacts'].disabled = False self.fields['proposaltype'].disabled = False if self.user.has_perm( 'app.approve_technical' ) and self.status == "T" and self.user.contact in self.local_contacts.all( ): self.fields['local_contacts'].disabled = False if self.status == "A": if self.user.contact in self.local_contacts.all(): self.fields['local_contacts'].disabled = False if self.user.pk == self.proposer.pk: self.fields['coproposers'].disabled = False
def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) self.fields["start_date"].widget.attrs["autocomplete"] = "off" self.fields["start_date"].widget.attrs["autocomplete"] = "off" self.fields["start_date"].widget.input_type = "date" self.fields["end_date"].widget.attrs["autocomplete"] = "off" self.fields["end_date"].widget.attrs["autocomplete"] = "off" self.fields["end_date"].widget.input_type = "date" self.fields["slack_channel"].widget.attrs[ "placeholder"] = "#slack-channel" self.fields["note"].widget.attrs[ "placeholder"] = "Description of the Project" # Hide labels for specific fields because ``form_show_labels`` takes priority self.fields["start_date"].label = False self.fields["end_date"].label = False self.fields["note"].label = False self.fields["slack_channel"].label = False self.fields["project_type"].label = False self.fields["client"].label = False self.fields["codename"].label = False # Design form layout with Crispy FormHelper self.helper = FormHelper() # Turn on <form> tags for this parent form self.helper.form_tag = True self.helper.form_class = "form-inline justify-content-center" self.helper.form_method = "post" self.helper.form_class = "newitem" self.helper.layout = Layout( TabHolder( CustomTab( "Project Information", HTML(""" <p class="form-spacer"></p> """), Row( Column("client", ), Column( FieldWithButtons( "codename", HTML(""" <button class="btn btn-secondary js-roll-codename" roll-codename-url="{% url 'rolodex:ajax_roll_codename' %}" type="button" onclick="copyStartDate($(this).closest('div').find('input'))" > <i class="fas fa-dice"></i> </button> """), ), css_class="col-md-6", ), ), Row( Column("start_date", css_class="form-group col-md-6 mb-0"), Column("end_date", css_class="form-group col-md-6 mb-0"), css_class="form-row", ), Row( Column("project_type", css_class="form-group col-md-6 mb-0"), Column("slack_channel", css_class="form-group col-md-6 mb-0"), css_class="form-row", ), "update_checkouts", "note", link_css_class="project-icon", css_id="project", ), CustomTab( "Assignments", HTML(""" <p class="form-spacer"></p> """), Formset("assignments", object_context_name="Assignment"), Button( "add-assignment", "Add Assignment", css_class="btn-block btn-secondary formset-add-assign", ), HTML(""" <p class="form-spacer"></p> """), link_css_class="assignment-icon", css_id="assignments", ), CustomTab( "Objectives", HTML(""" <p class="form-spacer"></p> """), Formset("objectives", object_context_name="Objective"), Button( "add-objective", "Add Objective", css_class="btn-block btn-secondary formset-add-obj", ), HTML(""" <p class="form-spacer"></p> """), link_css_class="objective-icon", css_id="objectives", ), CustomTab( "Scope Lists", HTML(""" <p class="form-spacer"></p> """), Formset("scopes", object_context_name="Scope"), Button( "add-scope", "Add Scope List", css_class="btn-block btn-secondary formset-add-scope", ), HTML(""" <p class="form-spacer"></p> """), link_css_class="tab-icon list-icon", css_id="scopes", ), CustomTab( "Targets", HTML(""" <p class="form-spacer"></p> """), Formset("targets", object_context_name="Target"), Button( "add-target", "Add Target", css_class="btn-block btn-secondary formset-add-target", ), HTML(""" <p class="form-spacer"></p> """), link_css_class="tab-icon list-icon", css_id="targets", ), template="tab.html", css_class="nav-justified", ), ButtonHolder( Submit("submit", "Submit", css_class="btn btn-primary col-md-4"), HTML(""" <button onclick="window.location.href='{{ cancel_link }}'" class="btn btn-outline-secondary col-md-4" type="button">Cancel</button> """), ), )
class Form(CrispyFormMixin, form_class): def get_fieldsets(self): return fieldsets html = render(Form()) assert all(('<legend>Name</legend>' in html, '<legend>Age</legend>' in html)) @pytest.mark.parametrize(argnames='name_field', argvalues=[ 'name', Field('name'), Layout( HTML('My field'), Field('name'), ), ], ids=[ 'A regular string given', 'A Field instance given', 'A set of items (i.e. Layout instance) given', ]) def test_customized_field_render(form_class, name_field): class Form(CrispyFormMixin, form_class): def render_name_field(self): return name_field html = render(Form())
def __init__(self, *args, **kwargs): super(ProjectTargetForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs["autocomplete"] = "off" self.fields["ip_address"].widget.attrs["placeholder"] = "IP Address" self.fields["hostname"].widget.attrs["placeholder"] = "FQDN" self.fields["note"].widget.attrs["rows"] = 5 self.fields["note"].widget.attrs[ "placeholder"] = "Brief Description or Note" self.helper = FormHelper() # Disable the <form> tags because this will be inside an instance of `ProjectForm()` self.helper.form_tag = False # Disable CSRF so `csrfmiddlewaretoken` is not rendered multiple times self.helper.disable_csrf = True # Hide the field labels from the model self.helper.form_show_labels = False # Layout the form for Bootstrap self.helper.layout = Layout( # Wrap form in a div so Django renders form instances in their own element Div( # These Bootstrap alerts begin hidden and function as undo buttons for deleted forms Alert( content=(""" <strong>Target Deleted!</strong> Deletion will be permanent once the form is submitted. Click this alert to undo. """), css_class="alert alert-danger show formset-undo-button", style="display:none; cursor:pointer;", template="alert.html", block=False, dismiss=False, ), Div( HTML(""" <h6>Target #<span class="counter">{{ forloop.counter }}</span></h6> <hr> """), Row( Column("ip_address", css_class="col-md-6"), Column("hostname", css_class="col-md-6"), ), "note", Row( Column( Button( "formset-del-button", "Delete Target", css_class= "btn-sm btn-danger formset-del-button", ), css_class="form-group col-md-4 offset-md-4", ), Column( Field("DELETE", style="display: none;"), css_class="form-group col-md-4 text-center", ), css_class="form-row", ), css_class="formset", ), css_class="formset-container", ))
def __init__(self, *args, **kwargs): super(ProjectObjectiveForm, self).__init__(*args, **kwargs) self.fields["deadline"].widget.attrs["autocomplete"] = "off" self.fields["deadline"].widget.input_type = "date" self.fields["objective"].widget.attrs["rows"] = 5 self.fields["objective"].widget.attrs["autocomplete"] = "off" self.fields["objective"].widget.attrs[ "placeholder"] = "High-Level Objective" self.fields["description"].widget.attrs[ "placeholder"] = "Description, Notes, and Context" self.fields["priority"].empty_label = "-- Prioritize Objective --" self.helper = FormHelper() # Disable the <form> tags because this will be inside an instance of `ProjectForm()` self.helper.form_tag = False # Disable CSRF so `csrfmiddlewaretoken` is not rendered multiple times self.helper.disable_csrf = True # Hide the field labels from the model self.helper.form_show_labels = False # Layout the form for Bootstrap self.helper.layout = Layout( # Wrap form in a div so Django renders form instances in their own element Div( # These Bootstrap alerts begin hidden and function as undo buttons for deleted forms Alert( content=(""" <strong>Objective Deleted!</strong> Deletion will be permanent once the form is submitted. Click this alert to undo. """), css_class="alert alert-danger show formset-undo-button", style="display:none; cursor:pointer;", template="alert.html", block=False, dismiss=False, ), Div( HTML(""" <h6>Objective #<span class="counter">{{ forloop.counter }}</span></h6> <hr> """), Row( Column("objective", css_class="col-md-6"), Column( FieldWithButtons( "deadline", HTML(""" <button class="btn btn-secondary" type="button" onclick="copyEndDate($(this).closest('div').find('input'))" > Copy </button> """), ), css_class="col-md-6", ), ), Row( Column( Field("status", css_class="form-select"), css_class="col-md-6", ), Column( Field("priority", css_class="form-select"), css_class="col-md-6", ), ), "description", Row( Column( SwitchToggle("complete", ), css_class="col-md-4", ), Column( Button( "formset-del-button", "Delete Objective", css_class= "btn-sm btn-danger formset-del-button", ), css_class="form-group col-md-4", ), Column( Field("DELETE", style="display: none;"), css_class="form-group col-md-4 text-center", ), css_class="form-row", ), css_class="formset", ), css_class="formset-container", ))
def __init__(self, *args, **kwargs): super(ProjectAssignmentForm, self).__init__(*args, **kwargs) self.fields["operator"].queryset = self.fields[ "operator"].queryset.order_by("-is_active", "username", "name") self.fields[ "operator"].label_from_instance = lambda obj: obj.get_display_name self.fields["start_date"].widget.attrs["autocomplete"] = "off" self.fields["start_date"].widget.input_type = "date" self.fields["end_date"].widget.attrs["autocomplete"] = "off" self.fields["end_date"].widget.input_type = "date" self.fields["note"].widget.attrs["rows"] = 5 self.fields["note"].widget.attrs[ "placeholder"] = "Additional Information or Notes" self.helper = FormHelper() # Disable the <form> tags because this will be inside an instance of `ProjectForm()` self.helper.form_tag = False # Disable CSRF so `csrfmiddlewaretoken` is not rendered multiple times self.helper.disable_csrf = True # Hide the field labels from the model self.helper.form_show_labels = False # Layout the form for Bootstrap self.helper.layout = Layout( # Wrap form in a div so Django renders form instances in their own element Div( # These Bootstrap alerts begin hidden and function as undo buttons for deleted forms Alert( content=(""" <strong>Assignment Deleted!</strong> Deletion will be permanent once the form is submitted. Click this alert to undo. """), css_class="alert alert-danger show formset-undo-button", style="display:none; cursor:pointer;", template="alert.html", block=False, dismiss=False, ), Div( HTML(""" <h6>Assignment #<span class="counter">{{ forloop.counter }}</span></h6> <hr> """), Row( Column("operator", css_class="form-group col-md-6 mb-0"), Column("role", css_class="form-group col-md-6 mb-0"), css_class="form-row", ), Row( Column( FieldWithButtons( "start_date", HTML(""" <button class="btn btn-secondary" type="button" onclick="copyStartDate($(this).closest('div').find('input'))" > Copy </button> """), ), css_class="form-group col-md-6 mb-0", ), Column( FieldWithButtons( "end_date", HTML(""" <button class="btn btn-secondary" type="button" onclick="copyEndDate($(this).closest('div').find('input'))" > Copy </button> """), ), css_class="form-group col-md-6 mb-0", ), ), "note", Row( Column( Button( "formset-del-button", "Delete Assignment", css_class= "btn-sm btn-danger formset-del-button", ), css_class="form-group col-md-4 offset-md-4", ), Column( Field("DELETE", style="display: none;"), css_class="form-group col-md-4 text-center", ), css_class="form-row", ), css_class="formset", ), css_class="formset-container", ), )
def Label(val): return HTML('<label class="control-label col-sm-3 col-md-2">{}</label>'.format(val))
def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) self.user = kwargs.pop('user', None) self.local_contacts = kwargs.pop('local_contacts', None) super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.form_method = 'post' self.helper.field_class = 'col-sm-10' self.helper.label_class = 'col-sm-2' # help texts: self.fields[ 'proposal'].help_text = "You can only book measurement time for accepted proposals, where you are part of the experimental team." self.fields[ 'instrument'].help_text = "You can only book slot on instruments, where you are trained (see <a href='/profile'>your profile</a> for details)." self.fields[ 'option'].help_text = "Select one or more options which you want to use during measurement." self.fields[ 'shared_options'].help_text = "Select shared resources which you want to use. They will be booked for same time as you select below. You can optionally change it later." self.fields[ 'description'].help_text = "Enter sample(s) you want to measure and all important information about the measurement." self.fields[ 'local_contact'].help_text = "Select local contact who will be your contact person during measurement. Local contact must be claimed in your proposal and must be responsible for selected instrument." self.fields['description'].required = False self.fields['description'].widget.attrs['rows'] = 2 if self.instance and self.instance.pk: self.fields['proposal'].disabled = True self.fields['instrument'].disabled = True self.fields['shared_options'].disabled = True #self.fields['start'].disabled = True #self.fields['end'].disabled = True self.fields['starttime'].initial = self.instance.start.time() self.fields['endtime'].initial = self.instance.end.time() if self.instance and self.instance.pk: self.fields.pop('instrument') self.fields.pop('proposal') else: self.fields['instrument'].queryset = Instruments.objects.filter( group__in=self.user.contact.trained_instrumentgroups.all()) self.fields['proposal'].queryset = Proposals.objects.filter( Q(last_status='A') & (Q(proposer=self.user) | Q(coproposers__uid__exact=self.user) | Q(local_contacts__uid__exact=self.user))).distinct() self.fields['local_contact'].queryset = Contacts.objects.none() if 'instrument' in self.data and 'proposal' in self.data and 'local_contact' in self.data: try: instrument_id = int(self.data.get('instrument')) if self.user.contact.pk == int(self.data.get('local_contact')): self.fields[ 'local_contact'].queryset = Contacts.objects.filter( responsible_for_instrumentgroups__instruments__pk= instrument_id) else: proposal_id = int(self.data.get('proposal')) involved = Proposals.objects.get(pk=proposal_id).people self.fields[ 'local_contact'].queryset = Contacts.objects.filter( pk__in=[x.pk for x in involved], responsible_for_instrumentgroups__instruments__pk= instrument_id) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty elif self.instance.pk: if self.user.contact.pk == self.instance.local_contact.pk: self.fields[ 'local_contact'].queryset = Contacts.objects.filter( responsible_for_instrumentgroups__instruments=self. instance.instrument) else: involved = self.instance.proposal.people self.fields[ 'local_contact'].queryset = Contacts.objects.filter( pk__in=[x.pk for x in involved], responsible_for_instrumentgroups__instruments=self. instance.instrument) if 'local_contact' in self.initial and not self.fields[ 'local_contact'].queryset.filter( pk=self.initial['local_contact']).exists(): # get rid of local contact field - no choice available self.fields['local_contact_fixed'] = forms.CharField( initial=Contacts.objects.get(pk=self.initial['local_contact']), disabled=True, required=False, label="Local contact") self.fields.pop('local_contact') self.fields['option'].queryset = Options.objects.none() if 'instrument' in self.data: try: instrument_id = int(self.data.get('instrument')) self.fields['option'].queryset = Options.objects.filter( instrument=instrument_id).order_by('name') self.fields[ 'shared_options'].queryset = SharedOptions.objects.filter( instruments=instrument_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty elif self.instance.pk: self.fields[ 'option'].queryset = self.instance.instrument.options_set.order_by( 'name') self.fields[ 'shared_options'].queryset = self.instance.instrument.sharedoptions_set.order_by( 'name') self.helper.layout = Layout( Fieldset( None, 'proposal', 'instrument', ), Div(Field('option', wrapper_class='col-md-6', size='7'), Field('shared_options', wrapper_class='col-md-6', size='7'), css_class='form-row'), Fieldset( None, 'description', 'local_contact', ), Fieldset( None, 'local_contact_fixed', ), DateRangeField('Date', 'start', 'end', 'starttime', 'endtime'), ButtonHolder( Submit('submit', 'Save', css_class='button white'), HTML("""<a role="button" class="btn btn-default" href="{% url "app_experiments_calendar" %}">Cancel</a>""" ), ))
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) helper = self.helper = FormHelper() loadData() self.fields['chronics'] = forms.MultipleChoiceField( choices=chronicsData, widget=forms.SelectMultiple(attrs={ 'class': 'form-control', 'id': 'chronics' })) self.fields['allergies'] = forms.MultipleChoiceField( choices=allergiesData, widget=forms.SelectMultiple(attrs={ 'class': 'form-control', 'id': 'allergies' })) self.fields['asignDoctor'] = forms.CharField(widget=forms.Select( attrs={'class': 'asignDoctor'})) self.fields['age'] = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'id': 'age', 'placeholder': 'age *', })) helper.form_method = 'post' # get or post helper.form_action = '' helper.form_id = 'regpatient' helper.form_show_labels = False self.fields['chronics'].label = False self.fields['allergies'].label = False self.fields['hregno'].required = False self.fields['email'].required = False self.fields['chronics'].required = False self.fields['allergies'].required = False self.fields['visitcount'].required = False self.fields['registeredDate'].required = False self.helper.layout = Layout( Div(HTML("<h5 class='pdtitile'>Enter Patient Details:</h5>"), Row(Column('adharid', 'fname', 'bloodgrp', 'visitcount', css_class='form-group col-md-4'), Column('email', 'lname', 'birthdate', 'registeredDate', css_class='form-group col-md-4'), Column('phone', 'gender', 'age', css_class='form-group col-md-4'), Column('asignDoctor', css_class='form-group col-md-5'), css_class='row'), Div(Row(Column(HTML("<h5>Patient Address:</h5>"), css_class='col-md-10'), Column('country', 'city', css_class='form-group col-md-4'), Column('state', 'zipcode', css_class='form-group col-md-4'), Column('district', css_class='form-group col-md-4'), css_class='row address'), Row( Column(HTML("<h5>Select Chronics If Have:</h5>"), InlineCheckboxes('chronics'), css_class='col-md-6'), Column(HTML("<h5>Select Drug Allergies If Have:</h5>"), InlineCheckboxes('allergies'), css_class='col-md-6')), Submit('regPatient', 'Register', css_class='btn-primary', css_id='pregbtn'), css_class='pregisterpop'), css_class='register-form'))
def __init__(self, *args, **kwargs): super(G3WUserForm, self).__init__(*args, **kwargs) #filter fileds by role: self.filterFieldsByRoles(**kwargs) #check for groups in intials data if 'groups' in self.initial and len(self.initial['groups']) > 0: self.initial['groups'] = self.initial['groups'] if 'user_groups' in self.initial and len( self.initial['user_groups']) > 0: self.initial['user_groups'] = self.initial['user_groups'] # change queryset for editor1 if G3W_EDITOR1 in getUserGroups(self.request.user): self._set_editor1_queryset() self.helper = FormHelper(self) self.helper.form_tag = False args = [ Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>". format(_('Anagraphic'))), css_class='box-header with-border'), Div( 'first_name', 'last_name', 'email', css_class='box-body', ), css_class='box box-success'), css_class='col-md-6'), Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-users'></i> {}</h3>" .format(_('ACL/Roles'))), css_class='box-header with-border'), Div(*self.__authrole_fields(), css_class='box-body'), css_class='box box-solid bg-teal-gradient'), css_class='col-md-6 {}'.format( self.checkFieldsVisible('is_superuser', 'is_staff', 'groups'))), css_class='row'), Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-lock'></i> {}</h3>". format(_('Login data'))), css_class='box-header with-border'), Div( PrependedText('username', '<i class="fa fa-user"></i>'), PrependedText('password1', '<i class="fa fa-lock"></i>'), PrependedText('password2', '<i class="fa fa-lock"></i>'), css_class='box-body', ), css_class='box box-danger'), css_class='col-md-6'), Div(Div( Div( HTML( "<h3 class='box-title'><i class='fa fa-gear'></i> {}</h3>" .format(_('User data'))), css_class='box-header with-border'), Div( 'department', 'avatar', HTML( """{% if form.avatar.value %}<img class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.avatar.value }}">{% endif %}""", ), 'form_id', 'upload_url', 'delete_url', css_class='box-body', ), css_class='box box-default'), css_class='col-md-6'), css_class='row') ] # add backed if user id admin01 if self.request.user.is_superuser and self.request.user.is_staff: args.append( Div(Div(Div(Div(HTML( "<h3 class='box-title'><i class='fa fa-gear'></i> {}</h3>". format(_('User backend'))), css_class='box-header with-border'), Div( 'backend', css_class='box-body', ), css_class='box box-default'), css_class='col-md-6'), css_class='row')) self.helper.layout = Layout(*args)
def staff_page(request): user = request.user if not user.is_staff: raise PermissionDenied user_profiles = None file_filter_err = '' is_error = False show_file_alert = False empty_filter = False if request.method == 'POST': show_file_alert = True if 'file_input' not in request.FILES: raise PermissionDenied file_filter = request.FILES['file_input'] if file_filter.size > MAX_FILE_SIZE: file_filter.close() raise PermissionDenied reader = csv.reader(file_filter, delimiter=";") try: fieldnames = reader.next() if len(fieldnames) == 1 and fieldnames[0] in SEARCH_FIELDS: search_values = set(row[0] for row in reader) user_profiles = UserProfile.objects.filter(**{ SEARCH_FIELDS[fieldnames[0]] + '__in': list(search_values) }) if len(user_profiles) != len(search_values): err_search_values = search_values - set( user_profiles.values_list(SEARCH_FIELDS[fieldnames[0]], flat=True)) file_filter_err = u'<strong>{0}</strong><br/>'.format(_(u'dannyye_polzovateli_ne_naydeny')) + \ u', '.join(err_search_values) else: file_filter_err = _(u'nevernyy_format_fayla') is_error = True except Exception as e: logger.error('Error in staff page file filter upload: %s', e) file_filter_err = str(e) is_error = True elif request.method == 'GET' and not request.GET: user_profiles = UserProfile.objects.none() empty_filter = True f = UserProfileFilter(request.GET if request.method == 'GET' else {}, queryset=user_profiles) f.set() f.form.helper = FormHelper(f.form) f.form.helper.form_method = 'get' f.form.helper.layout.append( HTML(u"""<div class="form-group row"> <button id="button_filter" class="btn btn-secondary pull-xs-right" type="submit">{0}</button> </div>""".format(_(u'primenit')))) context = { 'filter': f, 'file_filter_err': file_filter_err, 'is_error': is_error, 'statuses': get_statuses(), 'show_file_alert': show_file_alert, 'empty_filter': empty_filter, } return render_to_response('staff.html', context, context_instance=RequestContext(request))
def landing_page(request, page): content_model = page.get_content_model() edit_resource = page_processors.check_resource_mode(request) if not edit_resource: # get the context from hs_core context = page_processors.get_page_context( page, request.user, request=request, resource_edit=edit_resource, extended_metadata_layout=None) if isinstance(context, HttpResponseRedirect): # sending user to login page return context extended_metadata_exists = False if content_model.metadata.model_output or \ content_model.metadata.executed_by or \ content_model.metadata.study_area or \ content_model.metadata.grid_dimensions or \ content_model.metadata.stress_period or \ content_model.metadata.ground_water_flow or \ content_model.metadata.boundary_condition or \ content_model.metadata.model_calibration or \ content_model.metadata.model_inputs or \ content_model.metadata.general_elements: extended_metadata_exists = True context['extended_metadata_exists'] = extended_metadata_exists context['model_output'] = content_model.metadata.model_output context['executed_by'] = content_model.metadata.executed_by context['study_area'] = content_model.metadata.study_area context['grid_dimensions'] = content_model.metadata.grid_dimensions context['stress_period'] = content_model.metadata.stress_period context['ground_water_flow'] = content_model.metadata.ground_water_flow context[ 'boundary_condition'] = content_model.metadata.boundary_condition context['model_calibration'] = content_model.metadata.model_calibration context['model_inputs'] = content_model.metadata.model_inputs context['general_elements'] = content_model.metadata.general_elements # add MODFLOW Model parameters context else: model_output_form = ModelOutputForm( instance=content_model.metadata.model_output, res_short_id=content_model.short_id, element_id=content_model.metadata.model_output.id if content_model.metadata.model_output else None) executed_by_form = ExecutedByForm( instance=content_model.metadata.executed_by, res_short_id=content_model.short_id, element_id=content_model.metadata.executed_by.id if content_model.metadata.executed_by else None) study_area_form = StudyAreaForm( instance=content_model.metadata.study_area, res_short_id=content_model.short_id, element_id=content_model.metadata.study_area.id if content_model.metadata.study_area else None) grid_dimensions_form = GridDimensionsForm( instance=content_model.metadata.grid_dimensions, res_short_id=content_model.short_id, element_id=content_model.metadata.grid_dimensions.id if content_model.metadata.grid_dimensions else None) stress_period_form = StressPeriodForm( instance=content_model.metadata.stress_period, res_short_id=content_model.short_id, element_id=content_model.metadata.stress_period.id if content_model.metadata.stress_period else None) ground_water_flow_form = GroundWaterFlowForm( instance=content_model.metadata.ground_water_flow, res_short_id=content_model.short_id, element_id=content_model.metadata.ground_water_flow.id if content_model.metadata.ground_water_flow else None) boundary_condition_form = BoundaryConditionForm( instance=content_model.metadata.boundary_condition, res_short_id=content_model.short_id, element_id=content_model.metadata.boundary_condition.id if content_model.metadata.boundary_condition else None) model_calibration_form = ModelCalibrationForm( instance=content_model.metadata.model_calibration, res_short_id=content_model.short_id, element_id=content_model.metadata.model_calibration.id if content_model.metadata.model_calibration else None) ModelInputFormSetEdit = formset_factory(wraps(ModelInputForm)(partial( ModelInputForm, allow_edit=True)), formset=BaseFormSet, extra=0) model_input_formset = ModelInputFormSetEdit(initial=list( content_model.metadata.model_inputs.values()), prefix='modelinput') for model_input_form in model_input_formset.forms: if len(model_input_form.initial) > 0: model_input_form.action = "/hsapi/_internal/%s/modelinput/%s/update-metadata/" % \ (content_model.short_id, model_input_form.initial['id']) model_input_form.delete_modal_form = MetaDataElementDeleteForm( content_model.short_id, 'modelinput', model_input_form.initial['id']) model_input_form.number = model_input_form.initial['id'] else: model_input_form.action = "/hsapi/_internal/%s/modelinput/add-metadata/" % \ content_model.short_id add_modelinput_modal_form = ModelInputForm( allow_edit=False, res_short_id=content_model.short_id) general_elements_form = GeneralElementsForm( instance=content_model.metadata.general_elements, res_short_id=content_model.short_id, element_id=content_model.metadata.general_elements.id if content_model.metadata.general_elements else None) ext_md_layout = Layout( HTML("<div class='col-xs-12 col-sm-6'>" "<div class='form-group' id='modeloutput'> " '{% load crispy_forms_tags %} ' '{% crispy model_output_form %} ' '</div>'), HTML('<div class="form-group" id="executedby"> ' '{% load crispy_forms_tags %} ' '{% crispy executed_by_form %} ' '</div> '), HTML('<div class="form-group" id="boundarycondition"> ' '{% load crispy_forms_tags %} ' '{% crispy boundary_condition_form %} ' '</div>'), HTML('<div class="form-group" id="generalelements"> ' '{% load crispy_forms_tags %} ' '{% crispy general_elements_form %} ' '</div>'), HTML("</div>"), ModelInputLayoutEdit, ModalDialogLayoutAddModelInput, HTML('<div class="col-xs-12 col-sm-6">' '<div class="form-group" id="studyarea"> ' '{% load crispy_forms_tags %} ' '{% crispy study_area_form %} ' '</div> '), HTML('<div class="form-group" id="griddimensions"> ' '{% load crispy_forms_tags %} ' '{% crispy grid_dimensions_form %} ' '</div>'), HTML('<div class="form-group" id="stressperiod"> ' '{% load crispy_forms_tags %} ' '{% crispy stress_period_form %} ' '</div>'), HTML('<div class="form-group" id="groundwaterflow"> ' '{% load crispy_forms_tags %} ' '{% crispy ground_water_flow_form %} ' '</div>'), HTML('<div class="form-group" id="modelcalibration"> ' '{% load crispy_forms_tags %} ' '{% crispy model_calibration_form %} ' '</div></div>')) # get the context from hs_core context = page_processors.get_page_context( page, request.user, resource_edit=edit_resource, extended_metadata_layout=ext_md_layout, request=request) context['resource_type'] = 'MODFLOW Model Instance Resource' context['model_output_form'] = model_output_form context['executed_by_form'] = executed_by_form context['study_area_form'] = study_area_form context['grid_dimensions_form'] = grid_dimensions_form context['stress_period_form'] = stress_period_form context['ground_water_flow_form'] = ground_water_flow_form context['boundary_condition_form'] = boundary_condition_form context['model_calibration_form'] = model_calibration_form context['model_input_formset'] = model_input_formset context['add_modelinput_modal_form'] = add_modelinput_modal_form context['general_elements_form'] = general_elements_form hs_core_context = add_generic_context(request, page) context.update(hs_core_context) return context
def __init__(self, *args, **kwargs): country_list = Country.objects.filter(couactive=True) income_list = Income.objects.all() maritalstatus_list = Marital.objects.filter(maractive=True) ethnicity_list = Ethnicity.objects.filter(ethactive=True) language_list = Language.objects.all() ocupation_list = Occupation.objects.all() height_list = Height.objects.all() weight_list = Weight.objects.all() pet_list = Pet.objects.filter(petactive=True) hobbie_list = Hobbie.objects.filter(hobactive=True) sport_list = Sport.objects.filter(spoactive=True) income_choices = ((x.inccode, str("%i — %i" % (x.incmin, x.incmax))) for x in income_list) super(FullSearchForm, self).__init__(*args, **kwargs) self.fields['seaminage'] = forms.ChoiceField( label="", required=False, choices=((str(x), x) for x in range(min_age, max_age))) self.fields['seaminage'].choices.insert(0, ('', 'From')) self.fields['seamaxage'] = forms.ChoiceField( label="", required=False, choices=((str(x), x) for x in range(min_age, max_age))) self.fields['seamaxage'].choices.insert(0, ('', 'To')) self.fields['seacountry'] = forms.ChoiceField( label="", required=False, choices=((x.coucode, x.couname) for x in country_list)) self.fields['seacountry'].choices.insert(0, ('', 'Country')) self.fields['seaincome'] = forms.ChoiceField(label="", required=False, choices=income_choices) self.fields['seaincome'].choices.insert(0, ('', 'Income')) self.fields['seamstatus'] = forms.ChoiceField( label="", required=False, choices=((x.marcode, x.marname) for x in maritalstatus_list)) self.fields['seamstatus'].choices.insert(0, ('', 'Marital Status')) self.fields['seaethnicity'] = forms.ChoiceField( label="", required=False, choices=((x.ethcode, x.ethname) for x in ethnicity_list)) self.fields['seaethnicity'].choices.insert(0, ('', 'Ethnicity')) self.fields['seafirstlang'] = forms.ChoiceField( label="", required=False, choices=((x.lancode, x.lanname) for x in language_list)) self.fields['seafirstlang'].choices.insert(0, ('', 'First Language')) self.fields['seasecondlang'] = forms.ChoiceField( label="", required=False, choices=((x.lancode, x.lanname) for x in language_list)) self.fields['seasecondlang'].choices.insert(0, ('', 'Second Language')) self.fields['seaocupation'] = forms.ChoiceField( label="", required=False, choices=((x.ocucode, x.ocudescription) for x in ocupation_list)) self.fields['seaocupation'].choices.insert(0, ('', 'Occupation')) self.fields['seaheight'] = forms.ChoiceField( label="", required=False, choices=((x.heicode, x.heidescription) for x in height_list)) self.fields['seaheight'].choices.insert(0, ('', 'Height')) self.fields['seaweight'] = forms.ChoiceField( label="", required=False, choices=((x.weicode, x.weidescription) for x in weight_list)) self.fields['seaweight'].choices.insert(0, ('', 'Weight')) self.fields['seachildren'] = forms.ChoiceField( label="", required=False, choices=((str(x), x) for x in range(11))) self.fields['seachildren'].choices.insert(0, ('', 'Children')) self.fields['seapet'] = forms.ChoiceField(label="", required=False, choices=((x.petcode, x.petname) for x in pet_list)) self.fields['seapet'].choices.insert(0, ('', 'Pet')) self.fields['seasport'] = forms.ChoiceField( label="", required=False, choices=((x.spocode, x.sponame) for x in sport_list)) self.fields['seasport'].choices.insert(0, ('', 'Sport')) self.fields['seahobbie'] = forms.ChoiceField( label="", required=False, choices=((x.hobcode, x.hobname) for x in hobbie_list)) self.fields['seahobbie'].choices.insert(0, ('', 'Hobbie')) self.helper = FormHelper() self.helper.form_show_labels = True self.helper.form_tag = False self.helper.layout = Layout( Div(HTML('<div class="line-age">'), HTML('<label class="title">Age</label>'), Field('seaminage', css_class='input-age'), Field('seamaxage', css_class='input-age'), HTML('</div>'), HTML('<div class="line-country">'), HTML('<label class="title">Country</label>'), Field('seacountry', css_class='input-country'), HTML('</div>'), css_class="simple-search"), Div( css_id='search-error', css_class='search-error', ), ) self.helper.form_id = 'searchForm' self.helper.form_method = 'post'
def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) self.user = kwargs.pop('user', None) if self.request and not self.user: self.user = self.request.user super(ResourceStep1Form, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.attrs = {'novalidate': True} self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.layout = Layout( 'title', 'organisations', 'description', 'image', Row(HTML('<hr>')), 'health_topic', Row(HTML('<hr>')), 'resource_type', Row(HTML('<hr>')), Div( Div(HTML( "<label class='control-label' style='float:right; padding-right:10px;'>{0}</label>" .format(_("Study Time"))), css_class='col-lg-2 '), Div(Field('study_time_number'), css_class='col-lg-2'), Div(Field('study_time_unit'), css_class='col-lg-2'), css_class='row', ), Row(HTML('<hr>')), 'audience', Row(HTML('<hr>')), 'geography', Row(HTML('<hr>')), 'languages', Row(HTML('<hr>')), 'device', Row(HTML('<hr>')), 'license', 'attribution', Row(HTML('<hr>')), 'other_tags', Row(HTML('<hr>')), 'terms', Row(HTML('<hr>')), Div( Submit('submit', _('Continue >>'), css_class='btn btn-default'), css_class='col-lg-offset-2 col-lg-8', ), )
def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(SampleForm, self).__init__(*args, **kwargs) geo_local = self.initial.get("geo_local", None) if isinstance(geo_local, Point): self.initial["lng"], self.initial["lat"] = geo_local.tuple ## define a specific query set self.fields['data_set'].queryset = DataSet.objects.filter( owner__id=self.request.user.id) self.fields[ 'data_set'].empty_label = None ## to remove empty label in combo box self.fields['vaccine_status'].queryset = VaccineStatus.objects.filter( owner__id=self.request.user.id) ##// <input placeholder="dd/mm/yyyy" name="date_of_onset" id="id_date_of_onset"/> self.fields['date_of_onset'].widget.attrs.update({ 'placeholder': 'dd/mm/yyyy', }) self.fields['date_of_receipt_lab'].widget.attrs.update({ 'placeholder': 'dd/mm/yyyy', }) self.fields['date_of_collection'].widget.attrs.update({ 'placeholder': 'dd/mm/yyyy', }) #placeholder="dd/mm/yyyy" ## can exclude explicitly ## exclude = ('md5',) field_text = [ # (field_name, Field title label, Detailed field description, requiered) ('name', 'Name', 'Unique identifier for this sample. Only letters, numbers and underscores are allowed.', True), ('date_of_onset', 'Onset date', 'Date of onset', False), ('date_of_collection', 'Collection date', 'Date of collection', False), ('date_of_receipt_lab', 'Lab reception date', 'Date receipt on the lab.', False), ('vaccine_status', 'Vaccine status', 'Discrimination of vaccination status', False), ('data_set', 'Dataset', 'Specific dataset (useful for grouping sets of samples)', False), ## ('geo_local', 'Global position', 'Geo position where the sample was collected', False), ('lat', 'Latitude', 'Geolocation where the sample was collected. Decimal Degrees (DD) format.', False), ('lng', 'Longitude', 'Geolocation where the sample was collected. Decimal Degrees (DD) format.', False), ('path_name_1', 'Raw fastq.gz (R1)', 'Raw file R1 with fastq gzip file (< 300MB). Files between 50 - 300 MB will be downsized to ~50 MB before analysis', True), ('path_name_2', 'Raw fastq.gz (R2)', 'Raw file R2 with fastq gzip file (< 300MB). Files between 50 - 300 MB will be downsized to ~50 MB before analysis', False), ('like_dates', 'Choose a date', 'Choose the option you want to be used to calculate the calendar week number.', False), ] for x in field_text: self.fields[x[0]].label = x[1] self.fields[x[0]].help_text = x[2] self.fields[x[0]].required = x[3] ### set formats of date self.fields[ 'date_of_onset'].input_formats = settings.DATETIME_INPUT_FORMATS self.fields[ 'date_of_collection'].input_formats = settings.DATETIME_INPUT_FORMATS self.fields[ 'date_of_receipt_lab'].input_formats = settings.DATETIME_INPUT_FORMATS self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.layout = Layout( Fieldset( 'General data', Div(Div('name', css_class="col-sm-4"), Div(HTML( '<a href="#modal_add_data_database" id="id_data_set_add_modal" data-toggle="modal"> <span> <i class="fa fa-plus-square"></i></span> </a>' ), HTML( '<a href="#modal_remove_data_database" id="id_data_set_remove_modal" data-toggle="modal"> <span> <i class="fa fa-minus-square"></i></span> </a>' ), Div('data_set'), css_class="row col-sm-4"), Div(HTML( '<a href="#modal_add_data_database" id="id_vaccine_add_modal" data-toggle="modal"> <span> <i class="fa fa-plus-square"></i></span> </a>' ), HTML( '<a href="#modal_remove_data_database" id="id_vaccine_remove_modal" data-toggle="modal"> <span> <i class="fa fa-minus-square"></i></span> </a>' ), Div('vaccine_status'), css_class="row col-sm-4"), css_class='row'), css_class='article-content'), Fieldset( 'Dates', Div( Div('like_dates', css_class="col-sm-3"), Div('date_of_onset', css_class="col-sm-3"), Div('date_of_collection', css_class="col-sm-3"), Div('date_of_receipt_lab', css_class="col-sm-3"), # HTML('<div id="div_id_date_of_onset" class="form-group col-sm-3"> <label for="id_date_of_onset" class="form-control-label ">Date of onset</label> <input placeholder="dd/mm/yyyy" name="date_of_onset" id="id_date_of_onset"/> <small id="hint_id_date_of_onset" class="text-muted">Date of onset</small> </div>'), # HTML('<div id="div_id_date_of_collection" class="form-group col-sm-3"> <label for="id_date_of_collection" class="form-control-label ">Date of collection</label> <input placeholder="dd/mm/yyyy" name="date_of_collection" id="id_date_of_collection"/> <small id="hint_id_date_of_collection" class="text-muted">Date of collection</small> </div>'), # HTML('<div id="div_id_date_on_lab" class="form-group col-sm-3"> <label for="id_date_on_lab" class="form-control-label ">Date on Lab</label> <input placeholder="dd/mm/yyyy" name="date_on_lab" id="id_date_on_lab"/> <small id="hint_id_date_on_lab" class="text-muted">Date on Lab</small> </div>'), css_class='row '), css_class='article-content'), Fieldset('Global position', Div(Div('lat', css_class="col-sm-4"), Div('lng', css_class="col-sm-4"), css_class='row'), css_class='article-content'), Fieldset('Fastq files', Div(Div('path_name_1', css_class='show-for-sr'), Div('path_name_2', css_class='show-for-sr')), css_class='article-content'), # Div( # Div('geo_local', css_class="col-sm-8"), # css_class = 'row' # ), ButtonHolder( Submit('save', 'Save', css_class='btn-primary'), Button('cancel', 'Cancel', css_class='btn-secondary', onclick='window.location.href="{}"'.format( reverse('samples'))), ), )
def __init__(self, *args, **kwargs): user = kwargs.pop("user") super(TimeReportForm, self).__init__(*args, **kwargs) # Make the Year and Semester fields not required (they will be handled later) self.fields["year"].required = False self.fields["term"].required = False # restrict the dropdown lists to actual teachers teachers = Group.objects.get(name="teachers").user_set.all() self.fields["master_thesis_teacher_in_charge"].queryset = teachers self.fields["semester_project_teacher_in_charge"].queryset = teachers self.fields["other_job_teacher_in_charge"].queryset = teachers # Restrict the list of users to the currently logged in user to improve performances self.fields["created_by"].queryset = Person.objects.filter(id=user.id).all() # Restrict the list of courses to the Hired applications courses_keys = ( Applications.objects.filter(applicant=user, status="Hired") .values_list("course", flat=True) .distinct() ) courses = Course.objects.filter(id__in=courses_keys).all() self.fields["class_teaching_course"].queryset = courses # Layout of the form self.helper = FormHelper() self.helper.layout = Layout( TabHolder( Tab( "Common", HTML( """ <div class="alert alert-info" role="alert"> You should enter a year (under the form of <strong>2 consecutive years - e.g. 2019-2020</strong>), select a term and select an activity type. Based on the activity type you selected, a new tab will be open with further information to provide. </div> """ ), Field("created_at", type="hidden"), Field("created_by", type="hidden"), Row( Column( Field("year", data_tab="Common", data_required="true"), css_class="form-group col-md-6 mb-0", ), Column( Field("term", data_tab="Common", data_required="true"), css_class="form-group col-md-6 mb-0", data_tab="Common", data_required="true", ), css_class="form-row", ), Field("activity_type"), ), Tab( "Class teaching", Field( "class_teaching_course", data_tab="Class teaching", data_required="true", data_autocomplete="true", data_autocomplete_source=reverse("web:autocomplete_my_courses"), ), Row( Column( AppendedText( "class_teaching_preparation_hours", "Hr", active=True, data_tab="Class teaching", data_required="false", ), css_class="form-group col-md-4 mb-0", ), Column( AppendedText( "class_teaching_teaching_hours", "Hr", active=True, data_tab="Class teaching", data_required="false", ), css_class="form-group col-md-4 mb-0", ), css_class="form-row", ), Row( Column( AppendedText( "class_teaching_practical_work_hours", "Hr", active=True, data_tab="Class teaching", data_required="false", ), css_class="form-group col-md-4 mb-0", ), Column( AppendedText( "class_teaching_exam_hours", "Hr", active=True, data_tab="Class teaching", data_required="false", ), css_class="form-group col-md-4 mb-0", ), css_class="form-row", ), ), Tab( "Master thesis", Field( "master_thesis_title", data_tab="Master thesis", data_required="true", ), Field( "master_thesis_student_name", data_tab="Master thesis", data_required="true", data_autocomplete="true", data_autocomplete_source=reverse( "web:autocomplete_all_students" ), ), Field( "master_thesis_teacher_in_charge", data_tab="Master thesis", data_required="true", data_autocomplete="true", data_autocomplete_source=reverse( "web:autocomplete_all_teachers" ), ), AppendedText( "master_thesis_supervision_hours", "Hr", active=True, data_tab="Master thesis", data_required="true", ), Field( "master_thesis_comments", data_tab="Master thesis", data_required="false", ), ), Tab( "Semester project", Field( "semester_project_thesis_title", data_tab="Semester project", data_required="true", ), Field( "semester_project_student_name", data_tab="Semester project", data_required="true", data_autocomplete="true", data_autocomplete_source=reverse( "web:autocomplete_all_students" ), ), Field( "semester_project_teacher_in_charge", data_tab="Semester project", data_required="true", data_autocomplete="true", data_autocomplete_source=reverse( "web:autocomplete_all_teachers" ), ), AppendedText( "semester_project_supervision_hours", "Hr", active=True, data_tab="Semester project", data_required="true", ), Field( "semester_project_comments", data_tab="Semester project", data_required="false", ), ), Tab( "Other job", Field("other_job_name", data_tab="Other job", data_required="true"), Field( "other_job_unit", data_tab="Other job", data_required="true", data_autocomplete="true", data_autocomplete_source=reverse("web:autocomplete_all_units"), ), Field( "other_job_teacher_in_charge", data_tab="Other job", data_required="true", data_autocomplete="true", data_autocomplete_source=reverse( "web:autocomplete_all_teachers" ), ), AppendedText( "other_job_hours", "Hr", active=True, data_tab="Other job", data_required="true", ), Field( "other_job_comments", data_tab="Other job", data_required="false", ), ), Tab( "Nothing to report", Field( "nothing_to_report_comments", data_tab="Nothing to report", data_required="true", ), ), Tab( "Not available", Field( "not_available_comments", data_tab="Not available", data_required="true", ), ), Tab( "MAN", AppendedText( "MAN_hours", "Hr", active=True, data_tab="MAN", data_required="true", ), Field("MAN_comments", data_tab="MAN", data_required="false"), ), Tab( "Exam proctoring and grading", Field( "exam_proctoring_and_grading_course", data_tab="exam proctoring and grading", data_required="true", data_use_select2="true", ), AppendedText( "exam_proctoring_and_grading_hours", "Hr", active=True, data_tab="exam proctoring and grading", data_required="true", ), Field( "exam_proctoring_and_grading_comments", data_tab="exam proctoring and grading", data_required="false", ), ), ), FormActions( Submit("submit", "Submit"), Button("cancel", "Cancel"), Reset("reset", "Reset"), ), )
def __init__(self, *args, **kwargs): """Inicialización del formulario.""" super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['autocomplete'] = 'off' if 'data' in kwargs.keys(): if 'provincia' in kwargs['data'].keys(): provincia = kwargs['data'].get('provincia', None) if provincia: self.fields['distrito'].queryset = Distrito.objects.filter( provincia=provincia) if 'distrito' in kwargs['data'].keys(): distrito = kwargs['data'].get('distrito', None) if distrito: self.fields[ 'localidad'].queryset = Localidad.objects.filter( distrito=distrito) else: if self.instance and self.instance.provincia: self.fields['distrito'].queryset = Distrito.objects.filter( provincia=self.instance.provincia) else: self.fields['distrito'].queryset = Distrito.objects.none() if self.instance and self.instance.distrito: self.fields['localidad'].queryset = Localidad.objects.filter( distrito=self.instance.distrito) else: self.fields['localidad'].queryset = Localidad.objects.none() self.helper = FormHelper() self.helper.layout = Layout( Fieldset( 'Datos generales', Div(Div('razon_social', css_class='col-8'), Div('cuit', css_class='col-4'), css_class='row'), Div(Div('correo', css_class='col-6'), Div('telefono', css_class='col-6'), css_class='row'), HTML("""<legend>Dirección</legend>"""), Div( Div('calle', css_class='col-6'), Div('numero', css_class='col-2'), Div('piso', css_class='col-2'), Div('dpto', css_class='col-2'), css_class='row', ), Div( Div('provincia', css_class='col-4'), Div('distrito', css_class='col-4'), Div('localidad', css_class='col-4'), css_class='row', ), HTML("""<legend>Pagos</legend>"""), Div(Div('cbu', css_class='col-6'), css_class='row'), ), FormActions(Submit('submit', 'Guardar', css_class='float-right'), Reset('reset', 'Limpiar', css_class='float-right')), )
def __init__(self, user, *args, **kwargs): super(CampaignForm, self).__init__(*args, **kwargs) self.user = user self.helper = FormHelper() if self.instance.id: form_action = common_submit_buttons(default_action='update') else: form_action = common_submit_buttons(default_action='add') week_days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ] week_days_html = """<div class="row"><div class="col-md-12 col-xs-6">""" for i in week_days: week_days_html += """ <div class="col-md-3"> <div class="btn-group" data-toggle="buttons"> <label for="{{ form.%s.auto_id }}">{{ form.%s.label }}</label><br/> <div class="make-switch switch-small"> {{ form.%s }} </div> </div> </div> """ % (i, i, i) week_days_html += """</div></div>""" css_class = 'col-md-6' self.helper.layout = Layout( Field('campaign_code'), TabHolder( Tab(_('general').title(), Div(Div(Fieldset(_('general settings').title()), css_class='col-md-12'), Div('name', css_class=css_class), Div('callerid', css_class=css_class), Div('caller_name', css_class=css_class), Div('content_object', css_class=css_class), css_class='row'), Div(Div('extra_data', css_class=css_class), Div('dnc', css_class=css_class), Div('description', css_class=css_class), Div('phonebook', css_class=css_class), css_class='row'), form_action, css_class='well'), Tab('Dialer', Div(Div(Fieldset(_('dialer settings').title()), css_class='col-md-12'), Div('aleg_gateway', css_class=css_class), Div('frequency', css_class=css_class), Div('callmaxduration', css_class=css_class), Div('maxretry', css_class=css_class), Div('intervalretry', css_class=css_class), Div('calltimeout', css_class=css_class), Div(Fieldset(_('dialer completion settings').title()), css_class='col-md-12'), Div('completion_maxretry', css_class=css_class), Div('completion_intervalretry', css_class=css_class), Div('sms_gateway', css_class=css_class), css_class='row'), form_action, css_class='well'), Tab('schedule', Div(Div(Fieldset(_('schedule settings').title()), css_class='col-md-12'), Div(HTML("""<label>%s<label>""" % (_('week days').capitalize())), css_class="col-md-3"), HTML(week_days_html), HTML("""<div> </div>"""), Div('startingdate', css_class=css_class), Div('expirationdate', css_class=css_class), Div('daily_start_time', css_class=css_class), Div('daily_stop_time', css_class=css_class), css_class='row'), form_action, css_class='well'), ), ) if settings.AMD: amd_layot = Tab(_('voicemail').capitalize(), Div(Div(Fieldset(_('voicemail settings').title()), css_class='col-md-12'), Div(HTML(""" <div class="btn-group" data-toggle="buttons"> <label for="{{ form.voicemail.auto_id }}">{{ form.voicemail.label }}</label> <br/> <div class="make-switch switch-small"> {{ form.voicemail }} </div> </div> """), css_class='col-md-12 col-xs-10'), HTML("""<div> </div>"""), Div('amd_behavior', css_class=css_class), Div('voicemail_audiofile', css_class=css_class), css_class='row'), form_action, css_class='well') self.helper.layout[1].insert(2, amd_layot) # hidden var self.helper.layout.append(Field('selected_phonebook')) self.helper.layout.append(Field('selected_content_object')) instance = getattr(self, 'instance', None) self.fields['campaign_code'].initial = get_unique_code(length=5) if user: list_gw = [] dnc_list = [] phonebook_list = get_phonebook_list(user) if not phonebook_list: phonebook_list = [] phonebook_list.append(('', '---')) self.fields['phonebook'].choices = phonebook_list self.fields['phonebook'].initial = str(phonebook_list[0][0]) gateway_list = UserProfile.objects.get( user=user).userprofile_gateway.all() gw_list = ((l.id, l.name) for l in gateway_list) dnc_list.append(('', '---')) dnc_obj_list = DNC.objects.values_list( 'id', 'name').filter(user=user).order_by('id') for l in dnc_obj_list: dnc_list.append((l[0], l[1])) self.fields['dnc'].choices = dnc_list for i in gw_list: list_gw.append((i[0], i[1])) self.fields['aleg_gateway'].choices = UserProfile.objects.get(user=user)\ .userprofile_gateway.all().values_list('id', 'name') if instance.has_been_duplicated: from survey.models import Survey available_objects = Survey.objects.filter(user=user, campaign=instance) object_choices = get_object_choices(available_objects) self.fields['content_object'].widget.attrs['readonly'] = True else: from survey.models import Survey_template available_objects = Survey_template.objects.filter(user=user) object_choices = get_object_choices(available_objects) self.fields['content_object'].choices = object_choices # Voicemail setting is not enabled by default if settings.AMD: from survey.forms import get_audiofile_list self.fields[ 'voicemail_audiofile'].choices = get_audiofile_list(user) # If campaign is running or has been started if instance.status == CAMPAIGN_STATUS.START or instance.has_been_started: self.fields['name'].widget.attrs['readonly'] = True self.fields['caller_name'].widget.attrs['readonly'] = True self.fields['callerid'].widget.attrs['readonly'] = True self.fields['extra_data'].widget.attrs['readonly'] = True self.fields['phonebook'].widget.attrs['readonly'] = True self.fields['lead_disposition'].widget.attrs['readonly'] = True self.fields['dnc'].widget.attrs['readonly'] = True self.fields['aleg_gateway'].widget.attrs['readonly'] = True self.fields['sms_gateway'].widget.attrs['readonly'] = True self.fields['voicemail'].widget.attrs['readonly'] = True self.fields['amd_behavior'].widget.attrs['readonly'] = True self.fields['voicemail_audiofile'].widget.attrs['readonly'] = True selected_phonebook = '' if instance.phonebook.all(): selected_phonebook = ",".join( ["%s" % (i.id) for i in instance.phonebook.all()]) self.fields['selected_phonebook'].initial = selected_phonebook self.fields['content_object'].widget.attrs['disabled'] = 'disabled' self.fields['content_object'].required = False self.fields['selected_content_object'].initial = "type:%s-id:%s" % \ (instance.content_type.id, instance.object_id)
def __init__(self, *args, **kwargs): super(GeneralSuiteDataForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Div( Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>".format(_('Frontend home data'))), css_class='box-header with-border' ), Div( 'title', 'sub_title', Field('home_description', css_class='wys5', style="width:100%;"), 'suite_logo', 'form_id', 'upload_url', 'delete_url', HTML( """{% if form.suite_logo.value %}<img class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.suite_logo.value }}">{% endif %}""", ), PrependedText('url_suite_logo', '<i class="fa fa-link"></i>'), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-user'></i> {}</h3>".format( _('Frontend about data'))), css_class='box-header with-border' ), Div( 'about_title', 'about_name', 'about_tel', 'about_email', 'about_address', Field('about_description', css_class='wys5', style="width:100%;"), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-user'></i> {}</h3>".format( _('Frontend groups map data'))), css_class='box-header with-border' ), Div( 'groups_title', Field('groups_map_description', css_class='wys5', style="width:100%;"), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-user'></i> {}</h3>".format( _('Frontend login data'))), css_class='box-header with-border' ), Div( Field('login_description', css_class='wys5', style="width:100%;"), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-user'></i> {}</h3>".format( _('Frontend social data'))), css_class='box-header with-border' ), Div( PrependedText('facebook_url', '<i class="fa fa-facebook"></i>'), PrependedText('twitter_url', '<i class="fa fa-twitter"></i>'), PrependedText('googleplus_url', '<i class="fa fa-google-plus"></i>'), PrependedText('youtube_url', '<i class="fa fa-youtube"></i>'), PrependedText('instagram_url', '<i class="fa fa-instagram"></i>'), PrependedText('flickr_url', '<i class="fa fa-flickr"></i>'), PrependedText('tripadvisor_url', '<i class="fa fa-tripadvisor"></i>'), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), Div( Div( Div( HTML("<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>".format( _('Map client data'))), css_class='box-header with-border' ), Div( 'main_map_title', Field('credits', css_class='wys5', style="width:100%;"), css_class='box-body', ), css_class='box box-default' ), css_class='col-md-6' ), css_class='row' ) )
def FakeInput(val): return HTML('<p class="form-control-static">{}</p>' .format(val))
class TrekForm(TopologyForm): parking_location = forms.gis.GeometryField(widget=Point2DWidget, required=False) fieldslayout = [ Div( HTML(""" <ul class="nav nav-tabs"> <li id="tab-main" class="active"><a href="#main" data-toggle="tab"><i class="icon-certificate"></i> %s</a></li> <li id="tab-advanced"><a href="#advanced" data-toggle="tab"><i class="icon-tasks"></i> %s</a></li> </ul>""" % (unicode(_("Main")), unicode(_("Advanced")))), Div( Div( 'name', 'published', 'is_park_centered', 'departure', 'arrival', 'duration', 'difficulty', 'route', 'ambiance', 'access', 'description_teaser', 'description', css_id="main", css_class="tab-pane active" ), Div( 'disabled_infrastructure', 'advised_parking', 'parking_location', 'public_transport', 'advice', 'themes', 'networks', 'usages', 'web_links', 'information_desk', Fieldset(_("Related treks"),), css_id="advanced", # used in Javascript for activating tab if error css_class="tab-pane" ), css_class="tab-content" ), css_class="tabbable" ), ] def __init__(self, *args, **kwargs): super(TrekForm, self).__init__(*args, **kwargs) self.fields['topology'].widget = LineTopologyWidget() self.fields['web_links'].widget = SelectMultipleWithPop(choices=self.fields['web_links'].choices, add_url=WebLink.get_add_url()) # Make sure (force) that name is required, in default language only self.fields['name_%s' % settings.LANGUAGE_CODE].required = True class Meta(TopologyForm.Meta): model = Trek fields = TopologyForm.Meta.fields + \ ['name', 'published', 'is_park_centered', 'departure', 'arrival', 'duration', 'difficulty', 'route', 'ambiance', 'access', 'description_teaser', 'description', 'disabled_infrastructure', 'advised_parking', 'parking_location', 'public_transport', 'advice', 'themes', 'networks', 'usages', 'web_links', 'information_desk']
def __init__(self, project=None, *args, **kwargs): super(DomainLinkForm, self).__init__(*args, **kwargs) if project: self.fields[ "static_server"].queryset = ServerHistory.objects.filter( project=project).order_by("activity_type", "server_role") self.fields[ "transient_server"].queryset = TransientServer.objects.filter( project=project).order_by("activity_type", "server_role") for field in self.fields: self.fields[field].widget.attrs["autocomplete"] = "off" self.fields["domain"].queryset = History.objects.filter( project=project).order_by("activity_type") self.fields["domain"].empty_label = "-- Select a Domain [Required] --" self.fields[ "domain"].label_from_instance = lambda obj: f"{obj.domain.name} ({obj.activity_type})" self.fields["static_server"].empty_label = "-- Select Static Server --" self.fields["static_server"].label_from_instance = ( lambda obj: f"{obj.server.ip_address} ({obj.server_role} | {obj.activity_type})" ) self.fields["transient_server"].empty_label = "-- Select VPS --" self.fields["transient_server"].label_from_instance = ( lambda obj: f"{obj.ip_address} ({obj.server_role} | {obj.activity_type})") self.helper = FormHelper() self.helper.form_method = "post" self.helper.form_class = "newitem" self.helper.form_show_errors = False self.helper.form_show_labels = False self.helper.layout = Layout( HTML(""" <p>First, select a domain checked-out for this project:</p> """), "domain", HTML(""" <p>Then set your subdomain (or "*" for a wildcard) and CDN endpoint (if any) used with this link:</p> """), "subdomain", "endpoint", HTML(""" <p>Finally, select either a static server checked-out for this project <em>or</em> a transient server to associate with the selected domain:</p> """), Row( Column("static_server", css_class="form-group col-md-6 mb-0"), Column("transient_server", css_class="form-group col-md-6 mb-0"), css_class="form-row", ), "project", ButtonHolder( Submit("submit", "Submit", css_class="btn btn-primary col-md-4"), HTML(""" <button onclick="window.location.href='{{ cancel_link }}'" class="btn btn-outline-secondary col-md-4" type="button">Cancel</button> """), ), )