class Meta: model = McUser fields = [ 'title', 'first_name', 'real_name', 'last_name', 'maiden_name', 'birthday', 'gender', 'class_year', 'hometown', 'hometown_state', 'high_school', 'phone_number', 'id', 'pic', 'staff_title', 'staff_phone', 'linkedin', 'website', 'facebook', 'email', 'dorm_type', 'dorm_number', 'mailing_address', 'mailing_city', 'mailing_state', 'mailing_zip', 'mailing_country', 'mailing_address_type', 'in_dfw', 'current_city', 'significant_other', 'children', 'personal_news', ] widgets = { 'id': forms.HiddenInput(), 'pic': ImageThumbnailInput, 'birthday': DateInput(), 'mailing_address_type': forms.Select(choices=(('', ''), ('parent', 'parent address'), ('alum', 'current alum address'))), 'in_dfw': forms.Select(choices=(('', ''), ('Yes', 'Yes'), ('No', 'No'))), 'title': forms.Select(choices=TITLE_CHOICES), 'personal_news': forms.Textarea(attrs={ 'rows': 4, 'cols': 15 }), }
class GradebookFilterForm(forms.Form): cohort = forms.ModelChoiceField( queryset=None, widget=forms.Select( attrs={'onchange': 'submit_filter_form(this.form)'}), required=False) marking_period = forms.ModelChoiceField( queryset=None, widget=forms.Select( attrs={'onchange': 'submit_filter_form(this.form)'}), required=False) benchmark = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=forms.SelectMultiple(attrs={'class': 'simple_multiselect'})) category = forms.ModelChoiceField( queryset=None, widget=forms.Select( attrs={'onchange': 'submit_filter_form(this.form)'}), required=False) assignment_type = forms.ModelChoiceField( queryset=None, widget=forms.Select( attrs={'onchange': 'submit_filter_form(this.form)'}), required=False) name = forms.CharField(required=False) date_begin = forms.DateField( required=False, widget=forms.DateInput(attrs={'placeholder': 'Later than'}), validators=settings.DATE_VALIDATORS) date_end = forms.DateField( required=False, widget=forms.DateInput(attrs={'placeholder': 'Earlier than'}), validators=settings.DATE_VALIDATORS) def update_querysets(self, course_section): self.fields['cohort'].queryset = Cohort.objects.filter( Q(percoursesectioncohort=None, student__coursesection=course_section) | Q(percoursesectioncohort__coursesection=course_section) ).distinct().order_by('name') self.fields['marking_period'].queryset = MarkingPeriod.objects.filter( coursesection=course_section).distinct() self.fields['benchmark'].queryset = Benchmark.objects.filter( item__course_section=course_section).distinct() self.fields[ 'assignment_type'].queryset = AssignmentType.objects.filter( item__course_section=course_section).distinct() self.fields['category'].queryset = Category.objects.filter( item__course_section=course_section).distinct()
class Meta: widgets = { 'sender': forms.TextInput(), 'email': forms.TextInput(), 'subject': forms.Select(), 'message': forms.Textarea(), }
class AlbaranSalidaForms(forms.ModelForm): class Meta: model = Albaran exclude = ('user', 'fechaalta') def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Fieldset( Field('id'), Div(Div('tpdoc', css_class=s4), Div(Field('referencia')), css_class=s12), Div(Field('proveedor', css_class=s12), css_class=s12), Div(Field('fecha', template=fecha), css_class=s12), Div(Field('observaciones', template=editor), css_class=s12)), #FormActions( Submit( "Update","Guardar"), Button( "cancel","Cancelar")) ) super(AlbaranSalidaForms, self).__init__(*args, **kwargs) self.fields['fecha'].widget.attrs['placeholder'] = 'dd/mm/aaaa' self.fields['tpdoc'].widget.attrs['readonly'] = 'readonly' self.fields['proveedor'].required = False self.fields['proveedor'].label = "Cliente" tpdoc = forms.ModelChoiceField( widget=forms.Select(), queryset=TiposDocumentos.objects.filter(abrv="ALBOUT"), initial=0) proveedor = autocomplete_light.ModelChoiceField( 'TercerosAutocompleteClientesTerceros')
def render(self, name, value=None, attrs=None, choices=()): pb, pb_desc = None, None juris_widget = None jurisdictions = Jurisdiction.objects.get_visible() if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass if len(jurisdictions) > 1: attrs = { "id": "id_juris_%s" % name, "class": "search-public_bodies-jurisdiction" } choices = [(j.name, j.name) for j in jurisdictions] juris_widget = forms.Select(choices=choices, attrs=attrs) if pb is None: juris_widget = juris_widget.render('jurisdiction', self.initial_jurisdiction) else: juris_widget = juris_widget.render('jurisdiction', pb.jurisdiction.name) juris_widget = mark_safe(juris_widget) return render_to_string( 'publicbody/_chooser.html', { 'name': name, 'value': value, "value_label": pb_desc, 'juris_widget': juris_widget, 'STATIC_URL': settings.STATIC_URL })
class ShippingAddressForm(checkout_forms.ShippingAddressForm): state = us_forms.USStateField( widget=floppyforms.Select(choices=STATE_CHOICES_WITH_EMPTY), required=False) def __init__(self, *args, **kwargs): super(ShippingAddressForm, self).__init__(*args, **kwargs) self.fields['country'].empty_label = ""
class Meta: model = Alert widgets = { 'alert_email': forms.CheckboxInput(attrs={'id': 'email-alert'}), 'alert_sms': forms.CheckboxInput(attrs={'id': 'sms-alert'}), 'period': forms.Select(attrs={'class': 'form-control'}), } exclude = ['user', 'alert_server_time']
class BaseCaseForm(mtforms.NonFieldErrorsClassFormMixin, forms.Form): """ Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin. """ status = forms.CharField( widget=forms.Select(choices=model.CaseVersion.STATUS), initial=model.CaseVersion._meta.get_field("status").default, ) add_tags = forms.CharField(widget=mtforms.AutocompleteInput( url=lambda: reverse("manage_tags_autocomplete")), required=False) idprefix = forms.CharField(max_length=200, required=False) priority = mtforms.MTChoiceField(choices=Choices("------", 1, 2, 3, 4), required=False) def __init__(self, *args, **kwargs): """Initialize form; pull out user from kwargs, set up data-allow-new.""" self.user = kwargs.pop("user", None) super(BaseCaseForm, self).__init__(*args, **kwargs) self.fields["add_tags"].widget.attrs["data-allow-new"] = ("true" if ( self.user and self.user.has_perm("tags.manage_tags")) else "false") def clean(self): """Can't create new tags without appropriate permissions.""" if (self.data.get("tag-newtag") and not (self.user and self.user.has_perm("tags.manage_tags"))): raise forms.ValidationError( "You do not have permission to create new tags.") return self.cleaned_data def save_new_tags(self, product=None): """Save new tags and add them to the list of tags to assign.""" tags = self.cleaned_data.setdefault("tags", set()) tags.update([int(tid) for tid in self.data.getlist("tag-tag")]) new_tags = self.data.getlist("tag-newtag") for name in new_tags: # @@@ should pass in user here, need MTQuerySet.get_or_create t, created = model.Tag.objects.get_or_create(name=name, product=product) tags.add(t.id) def save_tags(self, caseversion): """Update set of tags assigned to ``caseversion``.""" tags = self.cleaned_data.get("tags", set()) current_tags = set([t.id for t in caseversion.tags.all()]) caseversion.tags.add(*tags.difference(current_tags)) caseversion.tags.remove(*current_tags.difference(tags))
def __init__(self, foirequest, *args, **kwargs): super(FoiRequestStatusForm, self).__init__(*args, **kwargs) self.foirequest = foirequest self.fields['refusal_reason'] = forms.ChoiceField( label=_("Refusal Reason"), choices=[('', _('No or other reason given'))] + (foirequest.law.get_refusal_reason_choices()), required=False, widget=forms.Select(attrs={'class': 'form-control'}), help_text= _('When you are (partially) denied access to information, the Public Body should always state the reason.' ))
class NewAuditeurForm(forms.Form): auditeur = forms.NullBooleanField( label= u"Voullez vous faire une demande de préinscription en tant qu'auditeur libre", widget=forms.Select(choices=(("", "-----"), ("True", "Oui"), ("False", "Non")), attrs={'class': 'required auto'})) def clean_auditeur(self): if self.cleaned_data.get('auditeur', None) is None: raise forms.ValidationError(u'Vous devez choisir') return self.cleaned_data.get('auditeur', None)
class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) subject = forms.CharField(required=forms.Textarea) # http://stackoverflow.com/questions/1694447/how-to-set-an-event-handler-in-a-django-form-input-field # https://chriskief.com/2012/12/16/override-django-form-is_valid/ # http://stackoverflow.com/questions/30424394/django-forms-how-to-override-field-validation # overriding field validation # Creating drop-down list sales = "Sales" marketing = "Marketing" hr = "Recruitment" customer = "customers" it = "IT" other = "Other/Not Specified" dep_choices = {(sales, 'Sales'), (marketing, 'Marketing'), (hr, 'Recruitment'), (it, 'IT'), (customer, 'Customers'), (other, 'Other/Not Specified')} # choice field would be tracked # http://stackoverflow.com/questions/1694447/how-to-set-an-event-handler-in-a-django-form-input-field # http://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed # triggering changes inside current contact form instance # from experiments I found that 'attrs' below executes pure javascript # so I just used javascript to update image department = forms.ChoiceField( choices=dep_choices, # widget=forms.Select(attrs={'onchange': "alert(this.value)"})) widget=forms.Select(attrs={'onchange': 'changepic(this.value)'})) # set initial state department.initial = {'other', 'Other/Not Specified'} # http://stackoverflow.com/questions/16076420/django-dropdownlist-onchange-submission message = forms.CharField(widget=forms.Textarea( attrs={'style': 'resize:allow;'})) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) # self.initial['department'] = ... # possible variant here # http://herself.movielady.net/2012/12/15/initial-value-in-djangos-admin-for-a-choice-field/ super(ContactForm, self).__init__(*args, **kwargs)
class ArtistInfoForm(forms.ModelForm): state = USStateField(widget=floppyforms.Select(choices=STATE_CHOICES_WITH_EMPTY), required=False) country = floppyforms.ChoiceField(choices=COUNTRIES_WITH_EMPTY) payout_method = forms.ChoiceField( choices=User.PAYOUT_CHOICES, widget=forms.RadioSelect() ) paypal_email_again = floppyforms.EmailField(required=False) class Meta: fields = ('first_name', 'last_name', 'address_1', 'address_2', 'city', 'zip', 'state', 'country', 'payout_method', 'paypal_email', 'paypal_email_again', 'taxpayer_id') model = User def __init__(self, *args, **kwargs): super(ArtistInfoForm, self).__init__(*args, **kwargs) for field in self.Meta.fields: self.fields[field].widget.attrs['class'] = 'form-control' self.fields['state'].widget.attrs['class'] = 'form-control selectpicker' self.fields['country'].widget.attrs['class'] = 'form-control selectpicker' # default to US if nothing is set, initial not working as the form is bound if not self.initial['country']: self.initial['country'] = 'US' def clean(self): cleaned_data = super(ArtistInfoForm, self).clean() if cleaned_data.get('payout_method') == User.PAYOUT_CHOICES.PayPal: msg = u"This field is required." if not cleaned_data.get('paypal_email'): self.add_error('paypal_email', msg) if not cleaned_data.get('paypal_email_again'): self.add_error('paypal_email_again', msg) if cleaned_data.get('paypal_email') != cleaned_data.get('paypal_email_again'): raise forms.ValidationError(u'The two email addresses must match.') if cleaned_data.get('country') == 'US': state = cleaned_data.get('state') if not state: self.add_error('state', 'You must select a valid US state or territory.') taxpayer_id = cleaned_data.get('taxpayer_id') if not taxpayer_id: self.add_error('taxpayer_id', 'You must enter a valid taxpayer ID as a US citizen.') self.fields['state'].clean(state) self.fields['taxpayer_id'].clean(state) else: cleaned_data['state'] = '' cleaned_data['taxpayer_id'] = '' return cleaned_data
class BillingAddressForm(payment_forms.BillingAddressForm): """ Extended version of the core billing address form that adds a field so customers can choose to re-use their shipping address. """ SAME_AS_SHIPPING, NEW_ADDRESS = 'same-address', 'different-address' CHOICES = ( (SAME_AS_SHIPPING, 'Use shipping address'), (NEW_ADDRESS, 'Enter a new address'), ) billing_option = forms.ChoiceField( widget=forms.RadioSelect, choices=CHOICES, initial=SAME_AS_SHIPPING) state = us_forms.USStateField(widget=floppyforms.Select(choices=STATE_CHOICES_WITH_EMPTY), required=False) class Meta(payment_forms.BillingAddressForm): model = UserAddress exclude = ('search_text', 'user', 'num_orders', 'hash', 'is_default_for_billing', 'is_default_for_shipping') def __init__(self, shipping_address, user, data=None, *args, **kwargs): # Store a reference to the shipping address self.shipping_address = shipping_address super(BillingAddressForm, self).__init__(data, *args, **kwargs) self.instance.user = user # If no shipping address (eg a download), then force the # 'same_as_shipping' field to have a certain value. if shipping_address is None: self.fields['billing_option'].choices = ( (self.NEW_ADDRESS, 'Enter a new address'),) self.fields['billing_option'].initial = self.NEW_ADDRESS # If using same address as shipping, we don't need require any of the # required billing address fields. if data and data.get('billing_option', None) == self.SAME_AS_SHIPPING: for field in self.fields: if field != 'billing_option': self.fields[field].required = False def _post_clean(self): # Don't run model validation if using shipping address if self.cleaned_data.get('billing_option') == self.SAME_AS_SHIPPING: return super(BillingAddressForm, self)._post_clean() def save(self, commit=True): if self.cleaned_data.get('billing_option') == self.SAME_AS_SHIPPING: # Convert shipping address into billing address billing_addr = BillingAddress() self.shipping_address.populate_alternative_model(billing_addr) if commit: billing_addr.save() return billing_addr else: address = super(BillingAddressForm, self).save(commit=False) try: address = UserAddress.objects.get( user=self.instance.user, hash=address.generate_hash()) last_address = UserAddress.objects.get(user=self.instance.user, is_default_for_billing=True) last_address.is_default_for_billing = False address.is_default_for_billing = True address.save() except UserAddress.DoesNotExist: address.is_default_for_billing = True address.save() return address def validate_unique(self): pass
class FoiRequestStatusForm(forms.Form): def __init__(self, foirequest, *args, **kwargs): super(FoiRequestStatusForm, self).__init__(*args, **kwargs) self.foirequest = foirequest self.fields['refusal_reason'] = forms.ChoiceField( label=_("Refusal Reason"), choices=[('', _('No or other reason given'))] + (foirequest.law.get_refusal_reason_choices()), required=False, widget=forms.Select(attrs={'class': 'form-control'}), help_text= _('When you are (partially) denied access to information, the Public Body should always state the reason.' )) status = forms.ChoiceField( label=_("Status"), widget=forms.RadioSelect, choices=[ ('awaiting_response', _('This request is still ongoing.')), ('resolved', _('This request is finished.')), # ('request_redirected', _('This request has been redirected to a different public body.')) ]) resolution = forms.ChoiceField( label=_('Resolution'), choices=[('', _('No outcome yet'))] + FoiRequest.RESOLUTION_FIELD_CHOICES, required=False, widget=forms.Select(attrs={'class': 'form-control'}), help_text=_( 'How would you describe the current outcome of this request?')) redirected = forms.IntegerField( label=_("Redirected to"), required=False, widget=PublicBodySelect, help_text= _('If your message is redirected to a different Public Body, please specify the new Public Body' )) if payment_possible: costs = forms.FloatField( label=_("Costs"), required=False, min_value=0.0, localize=True, widget=PriceInput, help_text= _('Please specify what the Public Body charges for the information.' )) def clean_costs(self): costs = self.cleaned_data['costs'] if costs is None: return 0.0 return costs def clean(self): pk = self.cleaned_data.get('redirected', None) status = self.cleaned_data.get('status', None) if status == "request_redirected": if pk is None: raise forms.ValidationError( _("Provide the redirected public body!")) try: self._redirected_public_body = PublicBody.objects.get(id=pk) except PublicBody.DoesNotExist: raise forms.ValidationError(_("Invalid value")) if status == 'resolved': if not self.cleaned_data.get('resolution', ''): raise forms.ValidationError( _('Please give a resolution to this request')) # if resolution is successful or partially_successful, set status to resolved if self.cleaned_data.get('resolution', '') in ('successful', 'partially_successful'): self.cleaned_data['status'] = 'resolved' return self.cleaned_data def set_status(self): data = self.cleaned_data status = data['status'] resolution = data['resolution'] foirequest = self.foirequest message = foirequest.message_needs_status() if message: message.status = status message.save() if status == "request_redirected": foirequest.due_date = foirequest.law.calculate_due_date() foirequest.public_body = self._redirected_public_body status = 'awaiting_response' foirequest.status = status foirequest.resolution = resolution foirequest.costs = data['costs'] if resolution == "refused" or resolution == "partially_successful": foirequest.refusal_reason = data['refusal_reason'] else: foirequest.refusal_reason = u"" foirequest.save() status = data.pop("status") if status == 'resolved': foirequest.status_changed.send(sender=foirequest, status=resolution, data=data)
def __init__(self, path, user, *args, **kwargs): super(DynForm, self).__init__(*args, **kwargs) pathComplete = str(path) elements = pathComplete.split("/") studyName = elements[2] stageName = elements[3] for study in Study.objects.filter(studyName=str(studyName)): tempEntity = [] for entity in Patient.objects.filter( studyId__idStudy=study.idStudy, userOwner=user): tempLabel = str(entity).split(" ") patientLabel = tempLabel[0] + ". ID: " + tempLabel[1] tempEntity.append((patientLabel, patientLabel)) choiceEnt = tuple(tempEntity) self.fields['Paciente'] = ChoiceField( tempEntity, initial=tempEntity[len(tempEntity) - 1]) self.fields['Paciente'].widget.attrs['class'] = 'form-control' for stage in Stage.objects.filter(studyId=study.idStudy): if stage.stageType == str(stageName): questionList = [] for questionGroups in Question_Groups.objects.filter( groupStage__idStage=stage.idStage).order_by( 'order'): for question in questionGroups.idQuestions.all(): questionList.append(question) for question in questionList: if question.questionsType == 'Char': self.fields['%s' % question] = CharField( max_length=255, required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' if question.questionsType == 'Int': self.fields['%s' % question] = IntegerField( widget=forms.NumberInput(), required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' self.fields['%s' % question].widget.attrs[ 'min'] = question.questionMin self.fields['%s' % question].widget.attrs[ 'max'] = question.questionMax self.fields['%s' % question].widget.attrs['step'] = 1 if question.questionsType == 'Real': self.fields['%s' % question] = FloatField( widget=forms.NumberInput(), required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' self.fields['%s' % question].widget.attrs[ 'min'] = question.questionMin self.fields['%s' % question].widget.attrs[ 'max'] = question.questionMax self.fields[ '%s' % question].widget.attrs['step'] = 0.1 if question.questionsType == 'Date': self.fields['%s' % question] = DateField( widget=forms.DateInput(), required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' if question.questionsType == 'Time': self.fields['%s' % question] = TimeField( widget=forms.TimeInput(), required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' if question.questionsType == 'Bool': self.fields[ '%s' % question] = NullBooleanField( widget=forms.NullBooleanSelect(), required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs.update({ 'onclick': "toggle_id_%s()" % question, }) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' if question.questionsType == 'Img': self.fields['%s' % question] = FileField( required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control' if question.questionsType == 'Enum': choices = Choices.objects.filter( questionId__questionsId=question. questionsId) list_of_choices = [] for choice in choices: list_of_choices.append((choice, choice)) tuple_of_choices = tuple(list_of_choices) self.fields['%s' % question] = ChoiceField( widget=forms.Select(), choices=tuple_of_choices, required=False) self.fields['%s' % question].label = str( question.questionsLabel) self.fields['%s' % question].help_text = str( question.questionHelp) self.fields['%s' % question].widget.attrs.update({ 'onchange': "toggle_id_%s()" % question, }) self.fields['%s' % question].widget.attrs[ 'class'] = 'form-control'
class SelectForm(forms.Form): foo = forms.CharField(widget=forms.Select(choices=choices), required=False)
class SelectForm(forms.Form): foo = forms.CharField(widget=forms.Select(choices=choices))