class EmailForm(forms.Form): nom = forms.CharField( label = _("Votre nom:"), max_length = 255, required = True, ) courriel = forms.CharField( label = _("Votre courriel:"), max_length = 255, required = True, ) def __init__(self, *args, **kwargs): super(EmailForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'emailSubscriptionForm' self.helper.form_class = 'grid-100' self.helper.form_method = 'post' self.helper.form_action = '#emailSubscription_open' self.helper.add_input(Submit(_('Envoyer'), _('Envoyer'),css_class='btn-orange btn-large')) def clean_courriel(self): data = self.cleaned_data['courriel'] try : validate_email(data) except: raise forms.ValidationError("Courriel invalide !")
class ImageFormCrispy(forms.ModelForm): class Meta(object): model = Image exclude = ('user', 'order', 'album', 'status_changed', ) fields = ['content_type', 'object_pk', 'image', 'status'] widgets = { 'status': forms.HiddenInput(), 'content_type': forms.HiddenInput(), 'object_pk': forms.HiddenInput(), } #content_type = forms.CharField(widget=forms.HiddenInput()) #object_pk = forms.CharField(widget=forms.HiddenInput()) def __init__(self, user, content_type=None, object_pk=None, *args, **kwargs): super(ImageFormCrispy, self).__init__(*args, **kwargs) self.fields['status'].initial = 'public' if content_type: self.fields['content_type'].initial = content_type if object_pk: self.fields['object_pk'].initial = object_pk if AUTOCOMPLETE_LIGHT_INSTALLED: self.fields['tags'].widget = autocomplete_light.TextWidget('TagAutocomplete') self.helper = FormHelper() self.helper.form_tag = False self.helper.form_class = 'form-horizontal' self.helper.form_action = 'imagestore:upload' self.helper.add_input(Submit('submit', 'Submit'))
class ActaForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ActaForm, self).__init__(*args, **kwargs) current_subasta = Subasta.objects.get_current() # Mostrar solo las personas inscriptas self.fields['persona'].queryset = current_subasta.personas.all() # Mostrar solo los profesionales de la subasta self.fields['profesionales'].queryset = current_subasta.profesionales.all() self.helper = FormHelper() self.helper.form_method = "POST" self.helper.form_action = reverse("subastas:actas_create") self.helper.add_input(Submit('job_submit', 'Guardar')) self.helper.add_input(Reset('job_reset', 'Limpiar', css_class='btn-default')) self.helper.layout = Layout( Div('lote', 'persona', 'profesionales', 'descripcion') ) class Meta: fields = ['lote', 'persona', 'profesionales', 'descripcion'] model = Acta
class ContactForm(forms.Form): def __init__(self, *args, **kwargs): #call original initializator super(ContactForm, self).__init__(*args, **kwargs) import pdb; pdb.set_trace; #this helper object allows us to customize form self.helper = FormHelper() # form tag attributes self.helper.form_class = 'form-horizontal' self.helper.form_mehtod = 'post' self.helper.form_action = reverse('contact_teacher') #twitter bootstrap styles self.helper.help_text_inline = True self.helper.html5_required = True self.helper.label_class = 'col-sm-2 control-label' self.helper.field_class = 'col-sm-10' #form buttons self.helper.add_input(Submit('send_button',u'Надіслати')) from .teachers import Teacher teacher = forms.ModelChoiceField(queryset = Teacher.objects.all(), empty_label="Обрати викладача",label=u"Викладач", to_field_name='user') subject = forms.CharField(label=u"Заголовок листа", max_length = 128) message = forms.CharField(label=u"Текст повідомлення", max_length=2560, widget = forms.Textarea)
class PasswordForm(PasswordChangeForm): def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.add_input(Submit('submit', 'Submit')) super(PasswordForm, self).__init__(*args, **kwargs)
class BorrarAgenciaForm(forms.Form): agencia_id = forms.IntegerField(widget=forms.widgets.HiddenInput, required=True) username = forms.CharField(required=True, label=_("Confirme su usuario")) password = forms.CharField(widget=forms.widgets.PasswordInput, required=True, label=_("Confirme su clave")) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_class = "uniForm" self.helper.form_method = "post" self.helper.form_action = "iamcast.views.borrar_agencia" self.helper.add_input(Submit("submit", _("Borrar Agencia"))) super(BorrarAgenciaForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(BorrarAgenciaForm, self).clean() agencia_id = cleaned_data.get("agencia_id") username = cleaned_data.get("username") password = cleaned_data.get("password") if agencia_id and password: agencia = Agencia.objects.get(pk=agencia_id) if agencia.borrada(): raise forms.ValidationError(ugettext(u"La agencia %s ya se encuentra borrada") % agencia.nombre) if agencia.user.username != username: raise forms.ValidationError(ugettext(u"El usuario ingresado es inválido")) if not check_password(password, agencia.user.password): raise forms.ValidationError(ugettext(u"El password ingresado es incorrescto")) return cleaned_data
class ExampleForm(forms.Form): nama = forms.CharField( label = "Nama Anda", max_length = 80, required = True, ) email = forms.EmailField( label = "Email Anda", max_length = 80, required = True, ) pesanan = forms.CharField( label = "Pesanan Anda.", required = False, widget = forms.Textarea, ) komentar = forms.CharField( label = "Komentar tambahan untuk kami.", required = False, widget = forms.Textarea, ) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_id = "id-exampleForm" self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = 'submit_survey' self.helper.add_input(Submit('submit', 'Kirimkan pesanan')) super(ExampleForm,self).__init__(*args, **kwargs)
class ContactForm(forms.Form): def __init__(self, *args, **kwargs): # call original initializator super(ContactForm, self).__init__(*args, **kwargs) # this helper object allows us to customize form self.helper = FormHelper() # form tag attributes self.helper.form_class = 'form-horizontal' self.helper.form_method = 'post' self.helper.form_action = reverse('contact_admin') # twitter bootstrap styles self.helper.help_text_inline = True self.helper.html5_required = True self.helper.label_class = 'col-sm-2 control-label' self.helper.field_class = 'col-sm-10' # form buttons self.helper.add_input(Submit('send_button', u'Надіслати')) from_email = forms.EmailField( label=u"Ваша Емейл Адреса") subject = forms.CharField( label=u"Заголовок листа", max_length=128) message = forms.CharField( label=u"Текст повідомлення", widget=forms.Textarea)
class EditForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(EditForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.html5_required = True self.helper.layout = Layout( 'name', 'date_of_birth', 'card_id', 'tel', 'address') self.helper.add_input(Submit('submit', 'Sửa lí lịch')) self.helper.add_input(Reset('reset', 'Reset')) self.fields['name'].error_message = Message.REQUIRED class Meta: model = CustomUser fields = { 'name', 'address', 'card_id', 'tel', 'date_of_birth' } widgets = { 'date_of_birth': forms.DateInput( attrs={'class': 'datepicker'} ), }
class ProviderForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProviderForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.fields["start_date"].help_text = "The date your company started." self.fields["tos"].help_text = \ "A link to your terms of service that will be displayed at the bottom of each offer." self.helper.layout = Layout( Fieldset( 'General', 'name', 'website', 'start_date' ), Fieldset( 'Legal', 'tos', 'aup', 'sla', 'billing_agreement' ), Fieldset( 'Other', 'logo' ) ) self.helper.add_input(Submit('save', 'Save Profile')) class Meta: model = Provider fields = ('name', 'start_date', 'website', 'tos', 'aup', 'sla', 'billing_agreement', 'logo')
class ContactFormRus(forms.Form): """docstring for ContactFormRus""" def __init__(self, *args, **kwargs): # call original initializator super(ContactFormRus, self).__init__(*args, **kwargs) # this helper object allows us to us to customize form self.helper = FormHelper() # form tag attributes self.helper.form_class = 'form-horizontal' self.helper.form_method = 'post' self.helper.form_action = reverse('contact_admin') # twitter bootstrap styles self.helper.help_text_inline = True self.helper.html5_required = True self.helper.label_class = 'col-sm-2 control label' self.helper.field_class = 'col-sm-10' # from buttons self.helper.add_input(Submit('send_button', u"Отправить")) from_email = forms.EmailField(label=u"Ваш емайл адресс") subject = forms.CharField( label=u"Заголовок", max_length=128) message = forms.CharField( label=u"Текст сообщения", widget=forms.Textarea) files = forms.FileField(required=False)
class PageFour(forms.ModelForm): strenuous_activity_type = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_EXERCISE_TYPE) moderate_activity_type = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_EXERCISE_TYPE) strength_activity_type = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_EXERCISE_TYPE) strenuous_activity_days = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_DAYS) moderate_activity_days = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_DAYS) strength_activity_days = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_DAYS) def __init__(self, *args, **kwargs): super(PageFour, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.add_input(Submit('submit', 'Next Page')) self.helper.layout = Layout('', InlineRadios('strenuous_activity_type'), InlineRadios('moderate_activity_type'), InlineRadios('strength_activity_type'), InlineRadios('strenuous_activity_days'), InlineRadios('moderate_activity_days'), InlineRadios('strength_activity_days'),) class Meta: model = Survey fields = ('strenuous_activity_type', 'moderate_activity_type', 'strength_activity_type', 'strenuous_activity_days', 'moderate_activity_days', 'strength_activity_days',)
class HostCreateForm(forms.ModelForm): """ Quick Host creation form. """ def __init__(self, *args, **kwargs): super(HostCreateForm, self).__init__(*args, **kwargs) # Custom Crispiness self.helper = FormHelper(self) self.helper.form_class = 'form-inline' self.helper.layout = Layout( Div('first_name', 'last_name'), Div('email'), Div('phone'), Div('address_1'), Div('address_2'), ) self.helper.add_input(Submit('save', 'Save')) class Meta: model = models.Host fields = [ 'first_name', 'last_name', 'email', 'phone', 'address_1', 'address_2', ]
class ConciergeUserAddExistingProductForm(forms.Form): input_formats = ['%Y-%m-%dT%H:%M'] def __init__(self, *args, **kwargs): super(ConciergeUserAddExistingProductForm, self).__init__(*args, **kwargs) self.fields['provider'] = forms.ModelChoiceField(queryset=Provider.objects, widget=forms.Select( attrs={'data-url': reverse('engine_get_products_from_provider')}), required=True) self.fields['product'] = forms.IntegerField(widget=forms.Select(), required=True) self.fields['balance'] = forms.DecimalField(max_digits=19, decimal_places=3, required=True) self.fields['maturity_date'] = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), required=False, help_text='Only for fixed term product') self.fields['rate'] = forms.DecimalField(max_digits=19, decimal_places=3, required=False, help_text='Only for fixed term product') self.fields['term'] = forms.IntegerField(required=False, help_text='Only for fixed term product', label='Term (months)') self.fields['fee_exempt'] = forms.BooleanField(initial=False, required=False, help_text='Only for fixed term product') self.fields['user'] = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=User.objects, required=True) self.helper = FormHelper() self.helper.form_class = 'form-horizontal js-add-existing-products-form' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-10' self.helper.form_method = "POST" self.helper.form_action = reverse('engine_add_existing_product') self.helper.add_input( Button('Add Existing Product', 'Add Existing Product', css_class="btn btn-success js-add-existing-product", data_url=reverse('engine_add_existing_product')) )
class PageThree(forms.ModelForm): exercise_stay_health = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET) exercise_lose_weight = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET) exercise_improve_appearance = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET) exercise_energize = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET) exercise_sport = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET) exercise_fun = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET) exercise_muscle = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET) exercise_not = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET) def __init__(self, *args, **kwargs): super(PageThree, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.add_input(Submit('submit', 'Next Page')) self.helper.layout = Layout('', InlineRadios('exercise_stay_health'), InlineRadios('exercise_lose_weight'), InlineRadios('exercise_improve_appearance'), InlineRadios('exercise_energize'), InlineRadios('exercise_sport'), InlineRadios('exercise_fun'), InlineRadios('exercise_muscle'), InlineRadios('exercise_not'),) class Meta: model = Survey fields = ('exercise_stay_health', 'exercise_lose_weight', 'exercise_improve_appearance', 'exercise_energize', 'exercise_sport', 'exercise_fun', 'exercise_muscle', 'exercise_not',)
class DateFilterForm(forms.Form): start = forms.DateField(widget=forms.DateInput(attrs={'class':'datepicker'}, format='%d/%m/%Y'), input_formats=('%d/%m/%Y',)) end = forms.DateField(widget=forms.DateInput(attrs={'class':'datepicker'}, format='%d/%m/%Y'), input_formats=('%d/%m/%Y',)) def __init__(self, user, *args, **kwargs): super(DateFilterForm, self).__init__(*args, **kwargs) self.user = user self.helper = FormHelper() self.helper.form_id = 'date-range-selector' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = '#' self.helper.add_input(Submit('submit', 'Filter')) def clean_start(self): start = self.cleaned_data['start'] if not self.user.is_authenticated() and datetime.combine(start, time()) > (datetime.now() - timedelta(days=3)): raise forms.ValidationError("Last 72 hours are restricted.") return start def clean_end(self): end = self.cleaned_data['end'] if not self.user.is_authenticated() and datetime.combine(end, time()) > (datetime.now() - timedelta(days=3)): raise forms.ValidationError("Last 72 hours are restricted.") return end
class TransactionForm(ModelForm): class Meta: model = Transaction exclude = ('user',) def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(TransactionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'transaction-formId' self.helper.form_class = 'form-horizontal' self.helper.form_method = 'post' self.helper.form_action = '.' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-7' self.helper.add_input(Submit('submit', 'Создать', css_class="col-lg-offset-2")) self.instance.user = user self.fields['account_from'] = forms.ModelChoiceField(queryset=Account.objects.filter(user=user), required=False, label=_('Со счёта')) self.fields['account_to'] = forms.ModelChoiceField(queryset=Account.objects.filter(user=user), required=False, label=_('На счёт')) self.fields['place'] = forms.ModelChoiceField(queryset=Place.objects.filter(user=user), required=False, label=_('Место')) self.fields['category'] = forms.ModelChoiceField(queryset=Category.objects.filter(user=user), required=False, label=_('Категория'))
class ContactForm(forms.Form): def __init__(self, *args, **kwargs): # call initializator super(ContactForm, self).__init__(*args, **kwargs) # helper customs form self.helper = FormHelper() # form tag attr self.helper.form_action = reverse("contact_admin") self.helper.form_method = "POST" self.helper.form_class = "form-horizontal" # twitter bootstrap styles self.helper.help_text_inline = True self.helper.html5required = True self.helper.label_class = "col-sm-3 control-label" self.helper.field_class = "col-sm-5" # buttons self.helper.add_input(Submit("send_button", _(u"Send"))) from_email = forms.EmailField(label=_(u"Your email")) subject = forms.CharField(label=_(u"Title message"), max_length=128) message = forms.CharField(label=_(u"Your text"), max_length=2560, widget=forms.Textarea)
class AgoraAdminForm(django_forms.ModelForm): def __init__(self, request, *args, **kwargs): super(AgoraAdminForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.request = request self.helper.layout = Layout(Fieldset(_('General settings'), 'pretty_name', 'short_description', 'biography', 'delegation_policy', 'is_vote_secret', 'membership_policy', 'comments_policy')) self.helper.add_input(Submit('submit', _('Save settings'), css_class='btn btn-success btn-large')) def clean_short_description(self): return clean_html(self.cleaned_data['short_description']) def clean_pretty_name(self): return clean_html(self.cleaned_data['pretty_name'], True) def clean_biography(self): return clean_html(self.cleaned_data['biography']) class Meta: model = Agora fields = ('pretty_name', 'short_description', 'is_vote_secret', 'delegation_policy', 'biography', 'membership_policy', 'comments_policy') widgets = { 'membership_policy': django_forms.RadioSelect, 'comments_policy': django_forms.RadioSelect }
class OutcomeStatusForm(OwnedModelForm): class Meta: model = Outcome fields = [ 'owner', 'name', 'status', 'scope', ] def __init__(self, *args, **kwargs): request = kwargs.pop('request', None) self.owner = kwargs.pop('owner', None) super().__init__(*args, **kwargs) self.helper = FormHelper() outcome = self.instance self.helper.form_action = outcome.update_url + '?next={}'.format(request.path) self.helper.layout = Layout( Field('owner', type="hidden"), Field('name', type="hidden"), Field('scope', type="hidden"), Field('status', autofocus=True), ) self.helper.add_input(Submit('update', _('Update'))) self.helper.add_input(Submit('close', _('Close'), data_dismiss="modal", css_class='btn btn-secondary'))
class StudentUpdateForm(ModelForm): class Meta: model = Student fields = {'first_name', 'last_name', 'middle_name', 'student_group', 'birthday', 'photo', 'ticket', 'notes'} def __init__(self, *args, **kwargs): super(StudentUpdateForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) # set form tag attributes self.helper.form_action = reverse('students_edit', kwargs={'pk': kwargs['instance'].id}) self.helper.form_method = 'POST' self.helper.form_class = 'form-horizontal' # set form field properties self.helper.help_text_inline = True self.helper.html5_required = True self.helper.label_class = 'col-sm-2 control-label' self.helper.field_class = 'col-sm-10' self.helper.add_input(Submit('submit', u'Зберегти')) self.helper.add_input(Submit('cancel_button', u'Скасувати', css_class='btn btn-link')) # add buttons self.helper.layout[-1] = Layout(FormActions())
class CloseMeetingForm(forms.ModelForm): send_to_options = list(SendToOption.choices[2:]) # On QA servers, allow users to prevent sending of protocols if settings.QA_SERVER: send_to_options.insert(0, SendToOption.choices[0]) send_to = forms.TypedChoiceField(label=_("Send to"), coerce=int, choices=send_to_options, widget=forms.RadioSelect) class Meta: model = Meeting fields = ( 'held_at', ) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', _('Close Meeting'))) super(CloseMeetingForm, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): super(KnoWhereLoginForm, self).__init__(*args, **kwargs) self.fields['password'].widget = forms.PasswordInput() helper = FormHelper() helper.add_input(Submit('submit', 'Login')) self.helper = helper
class PhpbbPasswordResetForm(PasswordResetForm): def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_class = 'well form-horizontal' self.helper.form_method = 'post' self.helper.add_input(Submit('submit', _(u'Reset Password'), css_class='btn btn-inverse')) super(PhpbbPasswordResetForm, self).__init__(*args, **kwargs) def clean_email(self): email = self.cleaned_data["email"] self.phpbb_users_cache = PhpbbUsers.objects.filter(user_email__iexact=email, user_active=1) if not len(self.phpbb_users_cache): raise forms.ValidationError(self.error_messages['unknown']) user_link = PhpbbDjangoUserLink.objects.filter(phpbb_user=self.phpbb_users_cache[0]) if not len(user_link): user = User(username = self.phpbb_users_cache.username, password = "") user.is_staff = False user.is_superuser = False user.email = self.phpbb_users_cache.user_email user.save() PhpbbDjangoUserLink(user=user, phpbb_user=phpbb_user).save() # ugly stuff self.users_cache = User.objects.filter(email__iexact=email, is_active=True) return email
class PhpbbSetPasswordForm(SetPasswordForm): def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_class = 'well form-horizontal' self.helper.form_method = 'post' self.helper.add_input(Submit('submit', _(u'Change password'), css_class='btn btn-danger')) super(PhpbbSetPasswordForm, self).__init__(*args, **kwargs) def save(self): new_user = super(PhpbbSetPasswordForm, self).save(commit=False) password = self.cleaned_data['new_password1'] phpbb_user = new_user.get_profile().phpbb_user pass_md5 = hashlib.md5(password).hexdigest() phpbb_user.user_password = pass_md5 # is this nessesary ? phpbb_user.save() # commit again new_user.save() return new_user
class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['name', 'area', 'description', 'end_date', 'id'] widgets = { 'description': forms.Textarea(), 'end_date': forms.DateInput( format="%m/%d/%Y", attrs={'class': 'datepicker'} ), } def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_id = 'projectform' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Submit')) super(ProjectForm, self).__init__(*args, **kwargs) def save(self, commit=True): instance = super(ProjectForm, self).save(commit=False) if self.instance.slug: return super(ProjectForm, self).save() instance.slug = orig = slugify(instance.name) for x in itertools.count(1): if not Project.objects.filter(slug=instance.slug).exists(): break instance.slug = '%s-%d' % (orig, x) instance.save() return instance
class ReportingFilterForm(forms.Form): author = forms.CharField(max_length=255, label=_('Auteur'), required=False) journal = forms.CharField(max_length=255, label=_('Code revue'), required=False) type = forms.MultipleChoiceField( label=_('Type'), required=False, choices=[ ('Article', _('Article')), ('Culturel', _('Culturel')), ('Actes', _('Actes')), ('Thèses', _('Thèses')), ('Livres', _('Livres')), ('Depot', _('Depot')), ]) year = forms.MultipleChoiceField(label=_('Année'), required=False,) collection = forms.MultipleChoiceField( label=_('Type'), required=False, choices=[ ('Érudit', _('Érudit')), ('UNB', _('UNB')), ('Persée', _('Persée')), ]) def __init__(self, *args, **kwargs): super(ReportingFilterForm, self).__init__(*args, **kwargs) now_dt = dt.datetime.now() # Update some fields self.fields['year'].choices = [(y, y) for y in range(now_dt.year-50, now_dt.year)] # TODO: remove crispy-forms self.helper = FormHelper() self.helper.form_method = 'GET' self.helper.add_input(Submit('submit', _('Filtrer')))
class EventsForm(ModelForm): class Meta: model = NsaEvents fields='__all__' def __init__(self, *args, **kwargs): super(EventsForm,self).__init__(*args, **kwargs) self.fields['eventLeader'].queryset = User.objects.filter(Q(groups__name='AVC')|Q(groups__name='VolunteerManager')) self.fields['daysOfWeek'].widget = forms.CheckboxSelectMultiple() self.helper = FormHelper(self) self.helper.form_class='form-horizontal' self.helper.form_class='volunteerProfile' self.helper.form_id='volunteerProfileForm' #self.helper.label_class='col-md-2' #self.helper.field_class='col-md-5' self.helper.layout = Layout( 'eventName', Field('eventDate', css_class='datepicker',placeholder='Select Date'), 'eventLeader', 'location', 'autoApprove', 'description', 'internalComments', 'recurring', 'daysOfWeek', 'allowView', HTML('<div class="form-group"><div class="col-lg-5"></div>'), ButtonHolder( self.helper.add_input(Submit('save', 'Save', css_class="btn btnnavy")), self.helper.add_input(Submit('saveAndAdd', 'Save & Add Another', css_class="btn btnnavy")), self.helper.add_input(Button('cancel', 'Cancel', css_class='btn-default', onclick="window.history.back()")) ))
class FacilityRegistryForm(forms.Form): """Form to create or update a FacilityRegistry document.""" name = forms.CharField( label="Name/description", required=True) url = forms.URLField( label="Endpoint URL (including version)", required=True) version = forms.ChoiceField( label="Facility Registry API version", choices=VERSION_CHOICES, initial=(1, 0)) username = forms.CharField( label="API username") password = forms.CharField( label="API password") def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.add_input(Submit('submit', 'Submit')) forms.Form.__init__(self, *args, **kwargs)
class UserProfileRegistrationForm(RegistrationFormUniqueEmail): website = forms.CharField( required=False) picture = forms.ImageField( required=False) def clean(self): cleaned_data = super(UserProfileRegistrationForm, self).clean() website = cleaned_data.get('website') #If URLS is not empty and doesn't starts with http://, prepend http:// if website and not website.startswith('http://'): website = 'http://' + website cleaned_data['website'] = website return cleaned_data def __init__(self, *args, **kwargs): super(UserProfileRegistrationForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'registration_form' self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.form_method = 'post' self.helper.form_action = '.' self.helper.add_input(Submit('submit', 'Register'))
class UserRegisterForm(forms.Form): title_choices = ( ('Mr.', 'Mr'), ( 'Ms', 'Ms', ), ( 'Mrs.', 'Mrs.', ), ( 'Dr.', 'Dr.', ), ( 'Prof.', 'Prof.', ), ) # optional schema fields during registration if "Personal Data" in settings.LDAP_USER_DATA: gender = forms.TypedChoiceField(choices=( (0, "Male"), (1, "Female"), ), coerce=lambda x: bool(int(x)), widget=forms.RadioSelect, initial='0', required=True) title = forms.ChoiceField(required=True, choices=title_choices) designation = forms.CharField(max_length=200) department = forms.CharField(required=True, max_length=255) phone = forms.CharField(required=True, max_length=200) if "Organization" in settings.LDAP_USER_DATA: organization = forms.ModelChoiceField( required=False, queryset=Institution.objects.all(), empty_label='Select an organization', to_field_name='name') if "Address" in settings.LDAP_USER_DATA: address = forms.CharField(max_length=1000, widget=forms.Textarea()) country = CountryField().formfield() # mandatory schema fields during registration first_name = forms.CharField(required=True, max_length=255) last_name = forms.CharField(required=True, max_length=255) username = forms.CharField(required=True, min_length=3, max_length=30, help_text='Choose a memorable name e.g jdoe', validators=[UnicodeUsernameValidator()]) email = forms.EmailField(required=True) password = forms.CharField(widget=forms.PasswordInput, min_length=6) password1 = forms.CharField(widget=forms.PasswordInput, min_length=6, label='Confirm Password') # hide captcha field during unit tests if not settings.TESTING: captcha = ReCaptchaField() def __init__(self, *args, **kwargs): super(UserRegisterForm, self).__init__(*args, **kwargs) self.ldap_ops = LDAPOperations() self.helper = FormHelper() self.helper.form_id = 'id-user-data-form' self.helper.form_method = 'post' # self.helper.form_action = 'register' self.helper.add_input( Submit('submit', 'Submit', css_class='btn-success')) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-2' self.helper.field_class = 'col-md-8' self.helper.error_text_inline = False self.helper.layout = Layout( Fieldset( 'Basic Data', Field('first_name', placeholder='Your first name', css_class="some-class"), Div('last_name', title="Your last name"), 'email'), Fieldset('Login Details', 'username', 'password', 'password1'), ) if "Personal Data" in settings.LDAP_USER_DATA: self.helper.layout.append( Fieldset('Personal Data', 'gender', 'title', 'designation', 'department', 'phone')) if "Organization" in settings.LDAP_USER_DATA: self.helper.layout.append(Fieldset('Organization', 'organization')) if "Address" in settings.LDAP_USER_DATA: self.helper.layout.append(Fieldset('Address', 'address', 'country')) if settings.RECAPTCHA_PUBLIC_KEY and settings.RECAPTCHA_PRIVATE_KEY is not None: self.helper.layout.append(Fieldset('Spam control', 'captcha')) def clean_username(self): username = self.cleaned_data['username'] # check username existence in local storage DB query_set = User.objects.filter(username=username) # check username existence in LDAP result = self.ldap_ops.check_attribute('uid', username) if result or query_set: raise forms.ValidationError("Username " + username + " is not available (in use)", code='username_exists_ldap') return username def clean_email(self): mail = self.cleaned_data['email'] # check for email existence in local storage DB query_set = User.objects.filter(email=mail) # check email existence in LDAP result = self.ldap_ops.check_attribute('mail', mail) if result or query_set: raise forms.ValidationError("Email " + mail + " is not available (in use)", code='email_exists_ldap') return mail def clean(self): # Check for password matching password = self.cleaned_data.get('password') password1 = self.cleaned_data.get('password1') if password != password1: self._errors["password"] = self.error_class( ["Passwords do not match"]) return self.cleaned_data
class ProjectAdvancedForm(HideProtectedLevelMixin, ProjectTriggerBuildMixin, ProjectForm): """Advanced project option form.""" class Meta: model = Project per_project_settings = ( 'default_version', 'default_branch', 'privacy_level', 'analytics_code', 'show_version_warning', 'single_version', ) # These that can be set per-version using a config file. per_version_settings = ( 'documentation_type', 'requirements_file', 'python_interpreter', 'install_project', 'use_system_packages', 'conf_py_file', 'enable_pdf_build', 'enable_epub_build', ) fields = ( *per_project_settings, *per_version_settings, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() help_text = render_to_string( 'projects/project_advanced_settings_helptext.html' ) self.helper.layout = Layout( Fieldset( _("Global settings"), *self.Meta.per_project_settings, ), Fieldset( _("Default settings"), HTML(help_text), *self.Meta.per_version_settings, ), ) self.helper.add_input(Submit('save', _('Save'))) default_choice = (None, '-' * 9) versions_choices = self.instance.versions(manager=INTERNAL).filter( machine=False).values_list('verbose_name', flat=True) self.fields['default_branch'].widget = forms.Select( choices=[default_choice] + list( zip(versions_choices, versions_choices) ), ) active_versions = self.get_all_active_versions() if active_versions: self.fields['default_version'].widget = forms.Select( choices=active_versions, ) else: self.fields['default_version'].widget.attrs['readonly'] = True def clean_conf_py_file(self): filename = self.cleaned_data.get('conf_py_file', '').strip() if filename and 'conf.py' not in filename: raise forms.ValidationError( _( 'Your configuration file is invalid, make sure it contains ' 'conf.py in it.', ), ) # yapf: disable return filename def get_all_active_versions(self): """ Returns all active versions. Returns a smartly sorted list of tuples. First item of each tuple is the version's slug, and the second item is version's verbose_name. """ version_qs = self.instance.all_active_versions() if version_qs.exists(): version_qs = sort_version_aware(version_qs) all_versions = [(version.slug, version.verbose_name) for version in version_qs] return all_versions return None
class SpectrumForm(forms.ModelForm): lookup = { Spectrum.DYE: ("owner_dye", "Dye"), Spectrum.PROTEIN: ("owner_state", "State"), Spectrum.FILTER: ("owner_filter", "Filter"), Spectrum.CAMERA: ("owner_camera", "Camera"), Spectrum.LIGHT: ("owner_light", "Light"), } owner_state = forms.ModelChoiceField( required=False, label=mark_safe('Protein<span class="asteriskField">*</span>'), queryset=State.objects.select_related("protein"), widget=autocomplete.ModelSelect2( url="proteins:state-autocomplete", attrs={ "data-theme": "bootstrap", "data-width": "100%" }, ), ) owner = forms.CharField( max_length=100, label=mark_safe( '<span class="owner-type">Owner</span> Name<span class="asteriskField">*</span>' ), required=False, help_text="Name of protein, dye, filter, etc...", ) data = SpectrumFormField(required=False, label="Data") file = forms.FileField( required=False, label="File Upload", help_text= "2 column CSV/TSV file with wavelengths in first column and data in second column", ) confirmation = forms.BooleanField( required=True, label=mark_safe( "<span class='small'>I understand that I am adding a spectrum to the <em>public</em> " "FPbase spectra database, and confirm that I have verified the validity of the data</span>" ), ) def __init__(self, *args, **kwargs): self.user = kwargs.pop("user", None) self.helper = FormHelper() self.helper.attrs = { "id": "spectrum-submit-form", "data-validate-owner-url": reverse("proteins:validate_spectrumownername"), } self.helper.add_input(Submit("submit", "Submit")) self.helper.layout = Layout( Div("category"), Div( Div("owner_state", css_class="col-sm-6 col-xs-12 protein-owner hidden"), Div("owner", css_class="col-sm-6 col-xs-12 non-protein-owner"), Div("subtype", css_class="col-sm-6 col-xs-12"), css_class="row", ), Div("file", "data"), Div( Div("ph", css_class="col-md-6 col-sm-12"), Div("solvent", css_class="col-md-6 col-sm-12"), css_class="row", ), Field("confirmation", css_class="custom-checkbox"), ) super().__init__(*args, **kwargs) class Meta: model = Spectrum fields = ( "category", "subtype", "file", "data", "ph", "source", "solvent", "owner_state", "owner", ) widgets = { "data": forms.Textarea(attrs={ "class": "vLargeTextField", "rows": 2 }) } def clean(self): cleaned_data = super().clean() if not (cleaned_data.get("data") or self.files): self.add_error( "data", "Please either fill in the data field or " "select a file to upload.", ) self.add_error( "file", "Please either fill in the data field or " "select a file to upload.", ) def save(self, commit=True): cat = self.cleaned_data.get("category") if cat != Spectrum.PROTEIN: owner_model = apps.get_model("proteins", self.lookup[cat][1]) owner_name = self.cleaned_data.get("owner") owner_obj, c = owner_model.objects.get_or_create( name=owner_name, defaults={"created_by": self.user}) if not c: owner_obj.update_by = self.user owner_obj.save() setattr(self.instance, self.lookup[cat][0], owner_obj) self.instance.created_by = self.user return super().save(commit=commit) def clean_file(self): if self.files: filetext = "" try: for chunk in self.files["file"].chunks(): try: filetext += chunk.decode("utf-8") except AttributeError: filetext += chunk x, y, headers = text_to_spectra(filetext) if not len(y): self.add_error( "file", "Did not find a data column in the provided file") if not len(x): self.add_error( "file", "Could not parse wavelengths from first column") except Exception: self.add_error( "file", "Sorry, could not parse spectrum from this file. " "Is it it two column csv with (wavelength, spectrum)?", ) if not self.errors: self.cleaned_data["data"] = zip_wave_data(x, y[0]) self.data = self.data.copy() self.data["data"] = self.cleaned_data["data"] def clean_owner_state(self): owner_state = self.cleaned_data.get("owner_state") stype = self.cleaned_data.get("subtype") if self.cleaned_data.get("category") == Spectrum.PROTEIN: if owner_state.spectra.filter(subtype=stype).exists(): self.add_error( "owner_state", forms.ValidationError( "%(owner)s already has a{} %(stype)s spectrum".format( "n" if stype != Spectrum.TWOP else ""), params={ "owner": owner_state, "stype": owner_state.spectra.filter(subtype=stype).first(). get_subtype_display().lower(), }, code="owner_exists", ), ) return owner_state def clean_owner(self): # make sure an owner with the same category and name doesn't already exist owner = self.cleaned_data.get("owner") cat = self.cleaned_data.get("category") stype = self.cleaned_data.get("subtype") if cat == Spectrum.PROTEIN: return owner try: mod = apps.get_model("proteins", self.lookup[cat][1]) obj = mod.objects.get(slug=slugify(owner)) except ObjectDoesNotExist: return owner except KeyError: # this might be repetitive... since a missing category will already # throw an error prior to this point if not cat: raise forms.ValidationError("Category not provided") else: raise forms.ValidationError("Category not recognized") else: # object exists... check if it has this type of spectrum exists = False if isinstance(obj, Fluorophore): if obj.spectra.filter(subtype=stype).exists(): exists = True stype = (obj.spectra.filter( subtype=stype).first().get_subtype_display()) elif hasattr(obj, "spectrum") and obj.spectrum: exists = True stype = obj.spectrum.get_subtype_display() if exists: self.add_error( "owner", forms.ValidationError( "A %(model)s with the name %(name)s already has a %(stype)s spectrum", params={ "model": self.lookup[cat][1].lower(), "name": obj.name, "stype": stype, }, code="owner_exists", ), ) # raise forms.ValidationError( # "A %(model)s with the slug %(slug)s already has a spectrum of type %(stype)s.", # params={'model': self.lookup[cat][1].lower(), 'slug': slugify(owner), 'stype': stype}, # code='owner_exists') else: return owner
class CrispyAuthenticationForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(CrispyAuthenticationForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.add_input(Submit('submit', 'Login'))
class amenitiesForm(forms.Form): pet = forms.BooleanField(label="Pets in the house", required=False) parking = forms.BooleanField(label="Parking", required=False) lift = forms.BooleanField(label="Lift", required=False) gym = forms.BooleanField(label="Gym", required=False) wifi = forms.BooleanField(label="Wifi", required=False) fireplace = forms.BooleanField(label="Fireplace", required=False) hot_tub = forms.BooleanField(label="Hot tub", required=False) pool = forms.BooleanField(label="Pool", required=False) kitchen = forms.BooleanField(label="Kitchen", required=False) breakfast = forms.BooleanField(label="Breakfast,coffee,tea", required=False) air_conditioning = forms.BooleanField(label="Air conditioning", required=False) desk = forms.BooleanField(label="Desk/workspace", required=False) hairdryer = forms.BooleanField(label="Hair dryer", required=False) laundry_dryer = forms.BooleanField(label="Laundry – dryer", required=False) closet = forms.BooleanField(label="Closet/drawers", required=False) shampoo = forms.BooleanField(label="Shampoo", required=False) laundry_washer = forms.BooleanField(label="Laundry – washer", required=False) essentials = forms.BooleanField(label="Essentials", required=False) heat = forms.BooleanField(label="Heat", required=False) smoke_detector = forms.BooleanField(label="Smoke detector", required=False) carbon_monoxide_detector = forms.BooleanField( label="Carbon monoxide detector", required=False) first_aid_kit = forms.BooleanField(label="First aid kit", required=False) safety_card = forms.BooleanField(label="Safety card", required=False) fire_extinguisher = forms.BooleanField(label="Fire extinguisher", required=False) lock_on_bedroom_door = forms.BooleanField(label="Lock on bedroom door", required=False) def __init__(self, *args, **kwargs): super(amenitiesForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-description-data-form' self.helper.form_method = 'post' self.helper.form_action = 'amenitiesListor' self.helper.add_input(Submit('Next', 'Next', css_class='btn-info')) self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( Fieldset( 'What amenities do you offer?', Div('pet', css_class="checkbox"), Div('parking', css_class="checkbox"), Div('lift', css_class="checkbox"), Div('gym', css_class="checkbox"), Div('wifi', css_class="checkbox"), Div('fireplace', css_class="checkbox"), Div('hot_tub', css_class="checkbox"), Div('pool', css_class="checkbox"), Div('breakfast', css_class="checkbox"), Div('air_conditioning', css_class="checkbox"), Div('desk', css_class="checkbox"), Div('hairdryer', css_class="checkbox"), Div('laundry_dryer', css_class="checkbox"), Div('closet', css_class="checkbox"), Div('shampoo', css_class="checkbox"), Div('laundry_washer', css_class="checkbox"), Div('essentials', css_class="checkbox"), Div('heat', css_class="checkbox"), ), HTML("<br><br><br>"), Fieldset( 'Safety amenities', Div('smoke_detector', css_class="checkbox"), Div('carbon_monoxide_detector', css_class="checkbox"), Div('first_aid_kit', css_class="checkbox"), Div('safety_card', css_class="checkbox"), Div('fire_extinguisher', css_class="checkbox"), Div('lock_on_bedroom_door', css_class="checkbox"), ), )
class ListingForm(forms.Form): lodge_choice = ( ('A', 'Apartment'), ('H', 'House'), ('S', 'Secondary unit'), ('U', 'Unique space'), ) room_option = ( ('E', 'Entire place'), ('P', 'Private room'), ('S', 'Shared room'), ) property_type = forms.ChoiceField( label="First, let’s narrow things down", choices=lodge_choice, widget=forms.Select(attrs={'style': 'width:30%'}), required=True) room_type = forms.ChoiceField( label="What will guests have?", choices=room_option, widget=forms.Select(attrs={'style': 'width:30%'}), required=True) numberOfGuest = forms.IntegerField( label="How many guests can your place accommodate?", widget=forms.NumberInput(attrs={'style': 'width:30%'}), required=True, initial=1) numberOfBedroom = forms.IntegerField( label="How many bedrooms can guests use?", widget=forms.NumberInput(attrs={'style': 'width:30%'}), required=True, initial=1) numberOfBed = forms.IntegerField( label="How many beds can guests use?", widget=forms.NumberInput(attrs={'style': 'width:30%'}), required=True, initial=1) numberOfBathroom = forms.FloatField( label="How many bathrooms can guests use?", widget=forms.NumberInput(attrs={'style': 'width:30%'}), required=True, initial=1) def __init__(self, *args, **kwargs): super(ListingForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-Listing-data-form' self.helper.form_method = 'post' self.helper.form_action = 'listingEntry' self.helper.add_input(Submit('Next', 'Next', css_class='btn-info')) self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( Fieldset( 'Specify the type of your lodging', Field('property_type', css_class="form-control"), Field('room_type', title="What will guests have", css_class="form-control"), ), HTML("<br><br>"), Fieldset('Guest accommodation', Field('numberOfGuest', css_class="form-control"), Field('numberOfBedroom', css_class="form-control"), Field('numberOfBed', css_class="form-control"), Field('numberOfBathroom', css_class="form-control")))
class RegisterForm(UserCreationForm): team_token = forms.CharField( max_length=32, required=True, help_text=('Your team leader has received ' 'this by email prior to the ' 'competition'), validators=[team_exists] ) email = forms.EmailField( max_length=75, required=True, label="Email address", ) first_name = forms.CharField( max_length=64, required=True, ) last_name = forms.CharField( max_length=64, required=True, ) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.add_input(Submit('submit', 'Register')) self.fields['username'].widget.attrs.update({ 'autocapitalize': 'none' }) def save(self, commit=True): super(RegisterForm, self).save(commit=commit) username = self.cleaned_data['username'] team_token = self.cleaned_data['team_token'] user = User.objects.get_by_natural_key(username) team = Team.objects.filter(token=team_token)[0] player = Player.objects.create( user=user, team=team, first_name=user.first_name, last_name=user.last_name, display_name=user.username, ) if commit: player.save()
class PostCommentForm(CommentSecurityForm): comment = django_forms.CharField(label='', max_length=COMMENT_MAX_LENGTH, widget=django_forms.Textarea( attrs=dict(placeholder=_('Post a comment here...')))) def __init__(self, request, instance=None, files=None, save=None, *args, **kwargs): super(PostCommentForm, self).__init__(*args, **kwargs) self.request = request self.helper = FormHelper() self.helper.form_id = "post-comment" self.helper.form_class = "form-inline" self.helper.add_input(Submit('submit', _('Send'), css_class='btn btn-success btn-large')) def save(self): obj = self.get_comment_object() obj.save() return obj def get_comment_object(self): """ Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``). """ if not self.is_valid(): raise ValueError("get_comment_object may only be called on valid forms") CommentModel = self.get_comment_model() new = CommentModel(**self.get_comment_create_data()) new = self.check_for_duplicate_comment(new) return new def get_comment_model(self): """ Get the comment model to create with this form. Subclasses in custom comment apps should override this, get_comment_create_data, and perhaps check_for_duplicate_comment to provide custom comment models. """ return Comment def get_comment_create_data(self): return dict( content_type = ContentType.objects.get_for_model(self.target_object), object_pk = force_unicode(self.target_object._get_pk_val()), user = self.request.user, comment = self.cleaned_data["comment"], submit_date = datetime.datetime.now(), site_id = settings.SITE_ID, is_public = True, is_removed = False, ) def check_for_duplicate_comment(self, new): """ Check that a submitted comment isn't a duplicate. This might be caused by someone posting a comment twice. If it is a dup, silently return the *previous* comment. """ possible_duplicates = self.get_comment_model()._default_manager.using( self.target_object._state.db ).filter( content_type = new.content_type, object_pk = new.object_pk, user = new.user, ) for old in possible_duplicates: if old.submit_date.date() == new.submit_date.date() and old.comment == new.comment: return old return new def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ if not self.request.user.is_authenticated(): raise forms.ValidationError(ungettext("You must be authenticated to post a comment")) comment = self.cleaned_data["comment"] if settings.COMMENTS_ALLOW_PROFANITIES == False: bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()] if bad_words: plural = len(bad_words) > 1 raise forms.ValidationError(ungettext( "Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", plural) % \ get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], 'and')) # Check security information if self.security_errors(): raise forms.ValidationError(ungettext( "The comment form failed security verification: %s" % \ escape(str(self.security_errors())))) return comment
class ElectionEditForm(django_forms.ModelForm): question = django_forms.CharField(_("Question"), required=True) answers = django_forms.CharField(_("Answers"), required=True, help_text=_("Each choice on separate lines"), widget=django_forms.Textarea) from_date = django_forms.DateTimeField(label=_('Start voting'), required=False, help_text=_("Not required, you can choose to start the voting period manually"), widget=django_forms.TextInput(attrs={'class': 'datetimepicker'}), input_formats=('%m/%d/%Y %H:%M',)) to_date = django_forms.DateTimeField(label=_('End voting'), required=False, help_text=_("Not required, you can choose to end the voting period manually"), widget=django_forms.TextInput(attrs={'class': 'datetimepicker'}), input_formats=('%m/%d/%Y %H:%M',)) def __init__(self, request, *args, **kwargs): super(ElectionEditForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.request = request instance = kwargs['instance'] self.fields['question'].initial = instance.questions[0]['question'] self.fields['answers'].initial = "\n".join(answer['value'] for answer in instance.questions[0]['answers']) if instance.voting_starts_at_date and instance.voting_ends_at_date: self.fields['from_date'].initial = instance.voting_starts_at_date.strftime('%m/%d/%Y %H:%M') self.fields['to_date'].initial = instance.voting_ends_at_date.strftime('%m/%d/%Y %H:%M') self.helper.layout = Layout(Fieldset(_('General settings'), 'pretty_name', 'description', 'question', 'answers', 'is_vote_secret', 'comments_policy')) self.helper.add_input(Submit('submit', _('Save settings'), css_class='btn btn-success btn-large')) def clean(self, *args, **kwargs): cleaned_data = super(ElectionEditForm, self).clean() from_date = cleaned_data.get("from_date", None) to_date = cleaned_data.get("to_date", None) if not from_date and not to_date: return cleaned_data if (not from_date and to_date) or (from_date and not to_date): raise django_forms.ValidationError(_('You need to either provide ' 'none or both start and end voting dates')) if from_date < datetime.datetime.now(): raise django_forms.ValidationError(_('Invalid start date, must be ' 'in the future')) if to_date - from_date < datetime.timedelta(hours=1): raise django_forms.ValidationError(_('Voting time must be at least 1 hour')) return cleaned_data def save(self, *args, **kwargs): election = super(ElectionEditForm, self).save(*args, **kwargs) # Questions/answers have a special formatting answers = [] for answer_value in self.cleaned_data["answers"].splitlines(): if answer_value.strip(): answers += [{ "a": "ballot/answer", "value": answer_value.strip(), "url": "", "details": "", }] election.questions = [{ "a": "ballot/question", "answers": answers, "max": 1, "min": 0, "question": self.cleaned_data["question"], "randomize_answer_order": True, "tally_type": "simple" },] election.last_modified_at_date = datetime.datetime.now() election.save() if ("from_date" in self.cleaned_data) and ("to_date" in self.cleaned_data): from_date = self.cleaned_data["from_date"] to_date = self.cleaned_data["to_date"] election.voting_starts_at_date = from_date election.voting_extended_until_date = election.voting_ends_at_date = to_date election.save() transaction.commit() kwargs=dict( election_id=election.id, is_secure=self.request.is_secure(), site_id=Site.objects.get_current().id, remote_addr=self.request.META.get('REMOTE_ADDR') ) start_election.apply_async(kwargs=kwargs, task_id=election.task_id(start_election), eta=election.voting_starts_at_date) kwargs["user_id"] = self.request.user.id end_election.apply_async(kwargs=kwargs, task_id=election.task_id(end_election), eta=election.voting_ends_at_date) return election class Meta: model = Election fields = ('pretty_name', 'description', 'is_vote_secret', 'comments_policy') widgets = { 'comments_policy': django_forms.RadioSelect }
class UserSettingsForm(django_forms.ModelForm): avatar = django_forms.ImageField(_('Avatar'), help_text=_("Upload an image to use as avatar instead of gravatar service")) delete_avatar = django_forms.BooleanField(label=_("Remove this avatar"), required=False) short_description = django_forms.CharField(_('Short Description'), help_text=_("Say something about yourself (140 chars max)"), required=False) biography = django_forms.CharField(_('Biography'), help_text=_("Tell us about you, use as much text as needed"), widget=django_forms.Textarea, required=False) email = django_forms.EmailField(widget=django_forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u"Email"), required=False) email_updates = django_forms.BooleanField(label=_("Receive email updates"), required=False) old_password = django_forms.CharField(widget=django_forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Current password"), help_text=_("Provide your current password for security, required field"), required=True) password1 = django_forms.CharField(widget=django_forms.PasswordInput(attrs=attrs_dict, render_value=False),label=_("New password"), required=False, help_text=_("Specify your new password if you want to change it, or leave it blank")) password2 = django_forms.CharField(widget=django_forms.PasswordInput(attrs=attrs_dict, render_value=False), required=False, label=_("Repeat new password")) def __init__(self, request, *args, **kwargs): super(UserSettingsForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.request = request self.user = kwargs['instance'] self.fields['short_description'].initial = self.user.get_profile().short_description self.fields['biography'].initial = self.user.get_profile().biography self.fields['email'].initial = self.user.email self.fields['email_updates'].initial = self.user.get_profile().email_updates self.fields['avatar'].required = False # Users who login via twitter or other means do not have a password if self.user.password == '!': del self.fields['old_password'] self.helper.layout = Layout( Fieldset(_('Profile'), 'avatar', 'delete_avatar', 'first_name', 'last_name', 'short_description', 'biography', 'email_updates'), Fieldset(_('Change email'), 'email'), Fieldset(_('Change password'), 'password1', 'password2') ) else: self.helper.layout = Layout( Fieldset(_('Security'), 'old_password'), Fieldset(_('Profile'), 'avatar', 'delete_avatar', 'first_name', 'last_name', 'short_description', 'biography', 'email_updates'), Fieldset(_('Change email'), 'email'), Fieldset(_('Change password'), 'password1', 'password2') ) self.helper.add_input(Submit('submit', _('Save settings'), css_class='btn btn-success btn-large')) def save(self, *args, **kwargs): old_email = self.user.email user = super(UserSettingsForm, self).save(commit=False) profile = user.get_profile() profile.short_description = self.cleaned_data['short_description'] profile.biography = self.cleaned_data['biography'] profile.email_updates = self.cleaned_data['email_updates'] avatar = self.cleaned_data['avatar'] if avatar: if profile.mugshot: profile.mugshot.delete() profile.mugshot = avatar if self.cleaned_data['delete_avatar']: profile.mugshot.delete() profile.mugshot = None user.email = self.cleaned_data['email'] if len(self.cleaned_data['password1']) > 0: user.set_password(self.cleaned_data['password1']) profile.save() user.save() return user def clean_email(self): """ Validate that the email is not already registered with another user """ if User.objects.filter(email__iexact=self.cleaned_data['email']).exclude(email__iexact=self.user.email): raise django_forms.ValidationError(_(u'This email is already in use. Please supply a different email.')) return self.cleaned_data['email'] def clean_old_password(self): """ Validate that the email is not already registered with another user """ if not self.user.check_password(self.cleaned_data['old_password']): raise django_forms.ValidationError(_(u'Invalid password.')) return self.cleaned_data['old_password'] def clean(self): """ Validates that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ if 'password' in self.cleaned_data and 'password2' in self.cleaned_data and\ self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError(_('The two password fields didn\'t match.')) return self.cleaned_data class Meta: model = User fields = ('first_name', 'last_name')
class CreateUserForm(UserCreationForm): def __init__(self, *args, **kwargs): super(CreateUserForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.fields['username'].widget = forms.TextInput( attrs={ _('placeholder'): _('User name'), _('class'): _('form-control') }) self.fields['password1'].widget = forms.PasswordInput( attrs={ _('placeholder'): _('Password'), _('class'): _('form-control') }) self.fields['password2'].widget = forms.PasswordInput( attrs={ _('placeholder'): _('Type in your password again'), _('class'): _('form-control') }) self.fields['first_name'].widget = forms.TextInput( attrs={ _('placeholder'): _('First Name'), _('class'): _('form-control') }) self.fields['first_name'].label = "first name is optional" self.fields['last_name'].widget = forms.TextInput( attrs={ _('placeholder'): _('Last Name'), _('class'): _('form-control') }) self.fields['last_name'].label = "last name is optional" self.fields['email'].widget = forms.TextInput( attrs={ _('placeholder'): _('Email Address'), _('class'): _('form-control') }) self.fields['email'].required = False self.fields['email'].label = "Email is optional" self.fields['seat_location'] = forms.ChoiceField( label='Which side of the lecture are you sitting on?', choices=[(0, 'left'), (1, 'middle'), (2, 'right')], required=False, widget=forms.RadioSelect, ) self.helper.layout.append(Fieldset(None, Field('seat_location'))) self.helper.add_input(Submit(_('submit'), _('Submit'))) class Meta: # Provide an assoication between the ModelForm and a model model = User fields = ("username", "password1", "password2", "first_name", "last_name", "email") def clean_username(self): username = self.cleaned_data.get('username') return username.lower() def clean_seat_location(self): seat_location = self.cleaned_data.get('seat_location') if seat_location == '': seat_location = 1 return seat_location def save(self, *args, **kwargs): user = super(CreateUserForm, self).save(commit=False, *args, **kwargs) user._seat_location = self.cleaned_data.get('seat_location') user.save() return user
class VoteForm(django_forms.ModelForm): ''' Given an election, creates a form that lets the user choose the options he want to vote ''' def __init__(self, request, election, *args, **kwargs): super(VoteForm, self).__init__(*args, **kwargs) self.election = election self.helper = FormHelper() self.helper.form_action = reverse('election-vote', kwargs=dict(username=self.election.agora.creator.username, agoraname=self.election.agora.name, electionname=self.election.name)) self.request = request i = 0 for question in election.questions: answers = [(answer['value'], answer['value']) for answer in question['answers']] random.shuffle(answers) self.fields.insert(0, 'question%d' % i, django_forms.ChoiceField( label=question['question'], choices=answers, required=True, widget=django_forms.RadioSelect(attrs={'class': 'question'}))) i += 1 if election.is_vote_secret: if self.request.user in self.election.agora.members.all() or\ self.election.agora.has_perms('join', self.request.user): self.helper.add_input(Submit('submit-secret', _('Vote secretly'), css_class='btn btn-success btn-large')) self.helper.add_input(Submit('submit', _('Vote in public as a delegate'), css_class='btn btn-info btn-large separated-button')) else: self.helper.add_input(Submit('submit', _('Vote in public as a non-member delegate'), css_class='btn btn-info btn-large')) else: if self.request.user in self.election.agora.members.all() or\ self.election.agora.has_perms('join', self.request.user): self.helper.add_input(Submit('submit', _('Vote'), css_class='btn btn-success btn-large')) else: self.helper.add_input(Submit('submit', _('Vote in public as a non-member delegate'), css_class='btn btn-info btn-large')) def clean(self): cleaned_data = super(VoteForm, self).clean() if not self.election.ballot_is_open(): raise forms.ValidationError("Sorry, you cannot vote in this election.") return cleaned_data def save(self, *args, **kwargs): # invalidate older votes from the same voter to the same election old_votes = self.election.cast_votes.filter(is_direct=True, invalidated_at_date=None, voter=self.request.user) for old_vote in old_votes: old_vote.invalidated_at_date = datetime.datetime.now() old_vote.is_counted = False old_vote.save() vote = super(VoteForm, self).save(commit=False) data = { "a": "vote", "answers": [], "election_hash": {"a": "hash/sha256/value", "value": self.election.hash}, "election_uuid": self.election.uuid } i = 0 for question in self.election.questions: data["answers"] += [{ "a": "plaintext-answer", "choices": [self.cleaned_data['question%d' % i]], }] i += 1 if self.request.user not in self.election.agora.members.all(): if self.election.agora.has_perms('join', self.request.user): # Join agora if possible from agora_site.agora_core.views import AgoraActionJoinView AgoraActionJoinView().post(self.request, self.election.agora.creator.username, self.election.agora.name) vote.voter = self.request.user vote.election = self.election vote.is_counted = self.request.user in self.election.agora.members.all() vote.is_direct = True if 'submit-secret' in self.request.POST: vote.is_public = False vote.reason = None else: vote.reason = self.cleaned_data['reason'] vote.is_public = True vote.data = data vote.casted_at_date = datetime.datetime.now() vote.create_hash() actstream_action.send(self.request.user, verb='voted', action_object=self.election, target=self.election.agora, geolocation=json.dumps(geolocate_ip(self.request.META.get('REMOTE_ADDR')))) vote.action_id = Action.objects.filter(actor_object_id=self.request.user.id, verb='voted', action_object_object_id=self.election.id, target_object_id=self.election.agora.id).order_by('-timestamp').all()[0].id vote.save() return vote class Meta: model = CastVote fields = ('reason',) widgets = { 'reason': django_forms.TextInput( attrs={ 'placeholder': _('Explain your public position on ' 'the vote if you want and if your vote is public'), 'maxlength': 140 }) }
class ExpressionStudyCreateForm(forms.ModelForm): ome = autocomplete.Select2ListCreateChoiceField( required=False, widget=autocomplete.TagSelect2(url='/studies/ome-autocomplete', attrs={"data-tags":"true", "data-html":True}) ) experimental_design = autocomplete.Select2ListCreateChoiceField( required=False, widget=autocomplete.TagSelect2(url='/studies/experimental-design-autocomplete', attrs={"data-tags":"true", "data-html":True}) ) topics = autocomplete.Select2ListCreateChoiceField( required=False, widget=autocomplete.TagSelect2(url='/studies/topic-autocomplete', attrs={"data-tags":"true", "data-html":True}) ) tissues = autocomplete.Select2ListCreateChoiceField( required=False, widget=autocomplete.TagSelect2(url='/studies/tissue-autocomplete', attrs={"data-tags":"true", "data-html":True}) ) age = SimpleArrayField(forms.CharField(), required=False) sex = autocomplete.Select2ListCreateChoiceField( required=False, widget=autocomplete.TagSelect2(url='/studies/sex-autocomplete', attrs={"data-tags":"true", "data-html":True}) ) dev_stage = autocomplete.Select2ListCreateChoiceField( required=False, widget=autocomplete.TagSelect2(url='/studies/dev-stage-autocomplete', attrs={"data-tags":"true", "data-html":True}) ) antibody = autocomplete.Select2ListCreateChoiceField( required=False, widget=autocomplete.TagSelect2(url='/studies/antibody-autocomplete', attrs={"data-tags":"true", "data-html":True}) ) mutant = autocomplete.Select2ListCreateChoiceField( required=False, widget=autocomplete.TagSelect2(url='/studies/mutant-autocomplete', attrs={"data-tags":"true", "data-html":True}) ) cell_sorted = autocomplete.Select2ListCreateChoiceField( required=False, widget=autocomplete.TagSelect2(url='/studies/cell-sorted-autocomplete', attrs={"data-tags":"true", "data-html":True}) ) keywords = SimpleArrayField(forms.CharField(), required=False) class Meta: model = ExpressionStudy fields = ["article", "pmid", "samples_count", "read_groups", "edit_groups"] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ExpressionStudyCreateForm, self).__init__(*args, **kwargs) self.fields['read_groups'].help_text = "Groups with viewing permission on project and subentities. Will be ignored if the visibility is set to public. Use 'ctrl' to select multiple/unselect." self.fields['edit_groups'].help_text = "Groups with editing permission on project and subentities. Use 'ctrl' to select multiple/unselect." # TODO : Give link to group creation interface? groups = self.user.groups.all() self.fields['read_groups'].queryset = groups self.fields['edit_groups'].queryset = groups self.fields.keyOrder = [ 'article', 'pmid', 'samples_count', 'species' 'ome', 'technology', 'experimental_design', 'topics', 'tissues', 'age', 'sex', 'dev_stage', 'antibody' 'mutant', 'cell_sorted', 'edit_groups', 'read_groups'] self.helper = FormHelper(self) self.helper.form_method = 'POST' self.helper.add_input(Submit('save', 'Save'))
class CreateElectionForm(django_forms.ModelForm): question = django_forms.CharField(_("Question"), required=True) answers = django_forms.CharField(_("Answers"), required=True, help_text=_("Each choice on separate lines"), widget=django_forms.Textarea) from_date = django_forms.DateTimeField(label=_('Start voting'), required=False, help_text=_("Not required, you can choose to start the voting period manually"), widget=django_forms.TextInput(attrs={'class': 'datetimepicker'}), input_formats=('%m/%d/%Y %H:%M',)) to_date = django_forms.DateTimeField(label=_('End voting'), required=False, help_text=_("Not required, you can choose to end the voting period manually"), widget=django_forms.TextInput(attrs={'class': 'datetimepicker'}), input_formats=('%m/%d/%Y %H:%M',)) def __init__(self, request, agora, *args, **kwargs): super(CreateElectionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.request = request self.agora = agora self.fields['is_vote_secret'].initial = agora.is_vote_secret self.helper.layout = Layout(Fieldset(_('Create election'), 'pretty_name', 'description', 'question', 'answers', 'is_vote_secret', 'from_date', 'to_date')) self.helper.add_input(Submit('submit', _('Create Election'), css_class='btn btn-success btn-large')) def clean(self, *args, **kwargs): cleaned_data = super(CreateElectionForm, self).clean() from_date = cleaned_data.get("from_date", None) to_date = cleaned_data.get("to_date", None) if not from_date and not to_date: return cleaned_data if (not from_date and to_date) or (from_date and not to_date): raise django_forms.ValidationError(_('You need to either provide ' 'none or both start and end voting dates')) if from_date < datetime.datetime.now(): raise django_forms.ValidationError(_('Invalid start date, must be ' 'in the future')) if to_date - from_date < datetime.timedelta(hours=1): raise django_forms.ValidationError(_('Voting time must be at least 1 hour')) return cleaned_data def clean_answers(self, *args, **kwargs): data = self.cleaned_data["answers"] answers = [answer_value.strip() for answer_value in self.cleaned_data["answers"].splitlines() if answer_value.strip()] if len(answers) < 2: raise django_forms.ValidationError(_('You need to provide at least two ' 'possible answers')) return data def save(self, *args, **kwargs): election = super(CreateElectionForm, self).save(commit=False) election.agora = self.agora election.create_name() election.uuid = str(uuid.uuid4()) election.created_at_date = datetime.datetime.now() election.creator = self.request.user election.short_description = election.description[:140] election.url = self.request.build_absolute_uri(reverse('election-view', kwargs=dict(username=election.agora.creator.username, agoraname=election.agora.name, electionname=election.name))) election.election_type = Agora.ELECTION_TYPES[0][0] # ONE CHOICE election.comments_policy = self.agora.comments_policy if ("from_date" in self.cleaned_data) and ("to_date" in self.cleaned_data): from_date = self.cleaned_data["from_date"] to_date = self.cleaned_data["to_date"] election.voting_starts_at_date = from_date election.voting_extended_until_date = election.voting_ends_at_date = to_date # Anyone can create a voting for a given agora, but if you're not the # admin, it must be approved if election.creator in election.agora.admins.all(): election.is_approved = True else: election.is_approved = False # Questions/answers have a special formatting answers = [] for answer_value in self.cleaned_data["answers"].splitlines(): if answer_value.strip(): answers += [{ "a": "ballot/answer", "value": answer_value.strip(), "url": "", "details": "", }] election.questions = [{ "a": "ballot/question", "answers": answers, "max": 1, "min": 0, "question": self.cleaned_data["question"], "randomize_answer_order": True, "tally_type": "simple" },] election.save() if from_date and to_date: kwargs=dict( election_id=election.id, is_secure=self.request.is_secure(), site_id=Site.objects.get_current().id, remote_addr=self.request.META.get('REMOTE_ADDR') ) start_election.apply_async(kwargs=kwargs, task_id=election.task_id(start_election), eta=election.voting_starts_at_date) kwargs["user_id"] = self.request.user.id end_election.apply_async(kwargs=kwargs, task_id=election.task_id(end_election), eta=election.voting_ends_at_date) return election class Meta: model = Election fields = ('pretty_name', 'description', 'is_vote_secret')
class BaseMandatForm(forms.ModelForm): default_date_range = None membre_reseau_elus = forms.ChoiceField( label="Souhaitez-vous faire partie du réseau des élu⋅es ?", choices=( (Person.MEMBRE_RESEAU_SOUHAITE, "Oui"), (Person.MEMBRE_RESEAU_NON, "Non"), ), required=True, ) dates = DateRangeField( label="Dates de votre mandat", required=True, help_text= "Indiquez la date de votre entrée au conseil, et la date approximative à laquelle votre" " mandat devrait se finir (à moins que vous n'ayiez déjà démissionné).", ) delegations = forms.MultipleChoiceField( label= "Si vous êtes vice-président⋅e, indiquez dans quels domains rentrent vos" " délégations.", choices=DELEGATIONS_CHOICES, widget=forms.CheckboxSelectMultiple, required=False, ) def __init__(self, *args, person, **kwargs): super().__init__(*args, **kwargs) self.instance.person = person self.fields["mandat"].choices = [ (None, "Indiquez votre situation au conseil") ] + self.fields["mandat"].choices[1:] if person.membre_reseau_elus == Person.MEMBRE_RESEAU_NON: self.fields[ "membre_reseau_elus"].initial = Person.MEMBRE_RESEAU_NON elif person.membre_reseau_elus != Person.MEMBRE_RESEAU_INCONNU: del self.fields["membre_reseau_elus"] self.fields["dates"].initial = self.default_date_range self.helper = FormHelper() self.helper.add_input(Submit("valider", "Valider")) self.helper.layout = Layout("mandat", "dates", "delegations") if "membre_reseau_elus" in self.fields: self.helper.layout.fields.insert(0, "membre_reseau_elus") def save(self, commit=True): if self.instance.statut in [ STATUT_A_VERIFIER_ADMIN, STATUT_A_VERIFIER_IMPORT ]: self.instance.statut = STATUT_A_VERIFIER_INSCRIPTION if "membre_reseau_elus" in self.fields: self.instance.person.membre_reseau_elus = self.cleaned_data[ "membre_reseau_elus"] self.instance.person.save(update_fields=["membre_reseau_elus"]) return super().save(commit=commit) class Meta: fields = ("dates", "mandat") error_messages = { NON_FIELD_ERRORS: { "dates_overlap": "Vous avez déjà indiqué un autre mandat pour ce conseil à des dates qui se" " chevauchent. Modifiez plutôt cet autre mandat." } }
class QuizSelectionForm(forms.Form): class Meta: fields = () def __init__(self, user, quiz, *args, **kwargs): ################ data initialisation ################### super(QuizSelectionForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout() queryset = filter_quizchoice_list(Quiz=quiz) #iterate through list to create field for each choice quiz_choice_list = [] for quiz_choice in queryset: #place in tuples for radio buttons to display quiz_choice_list.append((quiz_choice.id, quiz_choice.choice)) # switch on quiz_type ################### FREEFORM ################### # form is a textfield # response cannot be checked, display answer for user to compare if quiz.quiz_type == QuizType.FREEFORM: quiz_answer = QuizChoiceSelected.objects.filter(User=user, Quiz=quiz) if quiz_answer.exists(): # Quiz answered, prepare form to display result # filter returns a list, get first, also assume list length is 1 quiz_answer = quiz_answer[0] label = "Compare your answer to the correct answer" if quiz.answer == '': label = "Your answer has been submitted" self.fields['answer'] = forms.CharField( label=label, initial=quiz_answer.answer, widget=forms.Textarea( attrs={_('class'): _('form-control')})) if not quiz.answer == '': self.fields['correct_answer'] = forms.CharField( initial=quiz.answer, widget=forms.Textarea( attrs={_('class'): _('form-control')})) # add hidden values into form self.fields['user'] = forms.CharField(widget=forms.HiddenInput( attrs={_('value'): user.id})) self.fields['quiz'] = forms.CharField(widget=forms.HiddenInput( attrs={_('value'): quiz.id})) # determining whether to display code is handled in the view and passed in as context # since crispy form displays code all in one line if quiz.answer == '': self.helper.layout.append( Fieldset( quiz.question, Field('answer', disabled=_('true')), Field('user'), Field('quiz'), )) else: self.helper.layout.append( Fieldset( quiz.question, Field('answer', disabled=_('true')), Field('correct_answer', disabled=_('true')), Field('user'), Field('quiz'), )) elif not quiz_answer.exists() and not quiz.visible: # Quiz not answered yet, but finished, disable fields self.fields['answer'] = forms.CharField( label="You did not answer the quiz in time", widget=forms.Textarea( attrs={_('class'): _('form-control')})) if not quiz.answer == '': self.fields['correct_answer'] = forms.CharField( initial=quiz.answer, widget=forms.Textarea( attrs={_('class'): _('form-control')})) # add hidden values into form self.fields['user'] = forms.CharField(widget=forms.HiddenInput( attrs={_('value'): user.id})) self.fields['quiz'] = forms.CharField(widget=forms.HiddenInput( attrs={_('value'): quiz.id})) # determining whether to display code is handled in the view and passed in as context # since crispy form displays code all in one line if quiz.answer == '': self.helper.layout.append( Fieldset( quiz.question, Field('answer', disabled=_('true')), Field('user'), Field('quiz'), )) else: self.helper.layout.append( Fieldset( quiz.question, Field('answer', disabled=_('true')), Field('correct_answer', disabled=_('true')), Field('user'), Field('quiz'), )) else: # Quiz not answered yet, prepare form to collect self.fields['answer'] = forms.CharField(widget=forms.Textarea( attrs={_('class'): _('form-control')})) # add hidden values into form self.fields['user'] = forms.CharField(widget=forms.HiddenInput( attrs={_('value'): user.id})) self.fields['quiz'] = forms.CharField(widget=forms.HiddenInput( attrs={_('value'): quiz.id})) # determining whether to display code is handled in the view and passed in as context # since crispy form displays code all in one line self.helper.layout.append( Fieldset( quiz.question, Field('answer'), Field('user'), Field('quiz'), )) # form is to have a submit button since it needs to collect data self.helper.add_input(Submit(_('submit'), _('Submit'))) ################### SINGLEMCQ ################### # forms are radio buttons, have only one correct answer # response is either correct or wrong if quiz.quiz_type == QuizType.SINGLEMCQ: # if quiz not answered yet, filter will return an empty list quiz_choice_selected = QuizChoiceSelected.objects.select_related( ).filter(User=user, QuizChoice__Quiz=quiz.id) if len(quiz_choice_selected) == 0 and quiz.visible: # Quiz not answered yet, prepare form to collect self.fields['choices'] = forms.ChoiceField( choices=quiz_choice_list, required=True, widget=forms.RadioSelect) # add hidden values into form self.fields['user'] = forms.CharField(widget=forms.HiddenInput( attrs={_('value'): user.id})) self.helper.layout.append( Fieldset(quiz.question, Field('choices'), Field('user'))) # form is to have a submit button since it needs to collect data self.helper.add_input(Submit(_('submit'), _('Submit'))) elif len(quiz_choice_selected) == 0 and not quiz.visible: # Quiz not answered yet, but finished, disable fields self.fields['choices'] = forms.ChoiceField( label="You did not answer the quiz in time", choices=quiz_choice_list, required=True, widget=forms.RadioSelect) self.helper.layout.append( Fieldset(quiz.question, Field('choices', disabled=_('true')))) elif len(quiz_choice_selected) != 0: # Quiz answered, prepare form to display result # SINGLEMCQ only allows one choice to be selected initial_value = quiz_choice_selected.first().QuizChoice.id self.fields['choices'] = forms.ChoiceField( choices=quiz_choice_list, required=True, initial=initial_value, widget=forms.RadioSelect) self.helper.layout.append( Fieldset(quiz.question, Field('choices', disabled=_('true')))) # depending on the chosen choice, display the result in place of the submit button if quiz_choice_selected.first().QuizChoice.correct: self.helper.add_input( Button(name="", value="CORRECT", css_class="btn-success")) else: self.helper.add_input( Button(name="", value="WRONG", css_class="btn-danger")) ################### MULTIMCQ ################### # forms are checkboxes, can have multiple correct answers, but at least one correct # response can be correct, partially correct or wrong if quiz.quiz_type == QuizType.MULTIMCQ: # if quiz not answered yet, filter will return an empty list quiz_choice_selected = QuizChoiceSelected.objects.select_related( ).filter(User=user, QuizChoice__Quiz=quiz.id) if len(quiz_choice_selected) == 0: # Quiz not answered yet, prepare form to collect self.fields['choices'] = forms.MultipleChoiceField( choices=quiz_choice_list, required=True, widget=forms.CheckboxSelectMultiple, help_text=_("Select all that apply")) # add hidden values into form self.fields['user'] = forms.CharField(widget=forms.HiddenInput( attrs={_('value'): user.id})) self.helper.layout.append( Fieldset(quiz.question, Field('choices'), Field('user'))) # form is to have a submit button since it needs to collect data self.helper.add_input(Submit(_('submit'), _('Submit'))) elif len(quiz_choice_selected) == 0 and not quiz.visible: self.fields['choices'] = forms.MultipleChoiceField( choices=quiz_choice_list, required=True, widget=forms.CheckboxSelectMultiple, ) self.helper.layout.append( Fieldset(quiz.question, Field('choices', disabled=_('true')))) elif len(quiz_choice_selected) != 0: # Quiz answered, prepare form to display result # MULTIMCQ will have many choices selected initial_value = [ qcs.QuizChoice.id for qcs in quiz_choice_selected ] self.fields['choices'] = forms.MultipleChoiceField( choices=quiz_choice_list, required=True, initial=initial_value, widget=forms.CheckboxSelectMultiple) self.helper.layout.append( Fieldset(quiz.question, Field('choices', disabled=_('true')))) # depending on the chosen choice, display the result in place of the submit button list_of_corrects = filter_quizchoice_list_for_correct( Quiz=quiz, correct=True) overlapping_choices = set( [qcs.QuizChoice for qcs in quiz_choice_selected]) & set(list_of_corrects) if len(overlapping_choices) == 0: # completely wrong self.helper.add_input( Button(name=_(""), value="WRONG", css_class='btn-danger')) elif len(overlapping_choices) == len(list_of_corrects): # all correct self.helper.add_input( Button(name=_(""), value="CORRECT", css_class='btn-success')) else: # somewhere in between, partially correct self.helper.add_input( Button(name=_(""), value="PARTIALLY CORRECT", css_class='btn-warning')) ################### ZEROMCQ ################### # forms are checkboxes, can have multiple correct answers, but at least one correct # response can be correct, partially correct or wrong if quiz.quiz_type == QuizType.ZEROMCQ: # if quiz not answered yet, filter will return an empty list quiz_choice_selected = QuizChoiceSelected.objects.select_related( ).filter(User=user, QuizChoice__Quiz=quiz.id) if len(quiz_choice_selected) == 0 and quiz.visible: self.fields['choices'] = forms.ChoiceField( choices=quiz_choice_list, required=True, widget=forms.RadioSelect) # add hidden values into form self.fields['user'] = forms.CharField(widget=forms.HiddenInput( attrs={_('value'): user.id})) self.helper.layout.append( Fieldset(quiz.question, Field('choices'), Field('user'))) # form is to have a submit button since it needs to collect data self.helper.add_input(Submit(_('submit'), _('Submit'))) elif len(quiz_choice_selected) == 0 and not quiz.visible: # Quiz not answered yet, but finished, disable fields self.fields['choices'] = forms.ChoiceField( label="You did not answer the quiz in time", choices=quiz_choice_list, required=True, widget=forms.RadioSelect) self.helper.layout.append( Fieldset(quiz.question, Field('choices', disabled=_('true')))) elif len(quiz_choice_selected) != 0: # Quiz answered, prepare form to display result initial_value = quiz_choice_selected.first().QuizChoice.id self.fields['choices'] = forms.ChoiceField( choices=quiz_choice_list, required=True, initial=initial_value, widget=forms.RadioSelect) self.helper.layout.append( Fieldset(quiz.question, Field('choices', disabled=_('true')))) # to prevent default form messages from being displayed, answer selection can never be wrong #self.helper.form_show_labels = False def is_valid(self): return super(QuizSelectionForm, self).is_valid() def clean_user(self): user = self.cleaned_data.get('user') return get_user_object(id=user) def clean_quiz(self): quiz = self.cleaned_data.get('quiz') return get_quiz_object(id=quiz) def save(self, *args, **kwargs): data = self.cleaned_data if not data.get('answer') == None: return QuizChoiceSelected.objects.create(User=data.get('user'), Quiz=data.get('quiz'), answer=data.get('answer')) else: # change a single choice into an array of single choice so that it will work in the query selected_choices = data.get('choices') if type( data.get('choices')) == type([]) else [data.get('choices')] # need user and choices to create object user_object = get_user_object(id=data.get('user').id) return [ QuizChoiceSelected.objects.create(User=user_object, QuizChoice=selection) for selection in QuizChoice.objects.filter( id__in=selected_choices) ]
class OcorrenciaForm(ModelForm): tb_categoria_ID = forms.ModelChoiceField( label=('Tipo de Ocorrência'), required=True, queryset=Categoria.objects.all(), empty_label='Selecione') emergencia = forms.ChoiceField( label='Emergência?', choices=YES_NO_CHOICES, widget=forms.Select( attrs={'class': 'selector'})) vitimado = forms.ChoiceField( label='Tem alguma vítima?', choices=YES_NO_CHOICES, widget=forms.Select( attrs={'class': 'selector'})) foto = forms.ImageField(label='Fotografia', required=False, widget=forms.FileInput ) descricao = forms.CharField( widget=forms.Textarea( attrs={'rows': 10, 'cols': 48, 'placeholder': 'Escreva aqui a descricao da ocorrencia'})) class Meta: model = Ocorrencia fields = ['emergencia', 'tb_categoria_ID', 'vitimado', 'validade', 'atendida', 'vigilante_ID', 'usuario_ID', 'hora', 'foto', 'data', 'latitude', 'longitude', 'descricao'] widgets = {'atendida': forms.HiddenInput(), 'vigilante_ID': forms.HiddenInput(), 'usuario_ID': forms.HiddenInput(), 'validade': forms.HiddenInput()} def clean(self): cleaned_data = self.cleaned_data return cleaned_data def __init__(self, *args, **kwargs): super(OcorrenciaForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-exampleForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = 'submit_survey' self.helper.add_input(Submit('submit', 'Submit'))
class JobForm(forms.ModelForm): """A PyAr Jobs form.""" description = forms.CharField(widget=SummernoteInplaceWidget()) def __init__(self, *args, **kwargs): super(JobForm, self).__init__(*args, **kwargs) company_help_text = ''.join( ('Opcionalmente elija la empresa que ofrece el puesto. ', 'Si la empresa no aparece en el listado, puede registrarla ', 'haciendo click {0}'.format('<a href="{0}">aquí</a>').format( reverse('companies:add')))) title_help_text = ''.join( ('Título del empleo, por ejemplo: {0}'.format( choice([ 'Backend Developer', 'Django Developer', 'Frontend Developer', 'Senior Django Developer', 'Full Stack Python Developer', ])))) tags_help_text = ''.join( ('Agregue algunos tags / etiquetas ', 'que esten relacionadas con el puesto de trabajo. ' 'Los tags deben estar separados por comas, por ejemplo: ', 'Django, Python, MySQL, Linux')) seniority_help_text = ''.join( ('Opcionalmente puede especificar la experiencia requerida ', 'para el puesto.')) remote_work_help_text = ''.join( ('Se permite la modalidad de trabajo desde casa (homeworking).')) self.fields['title'].label = 'Título de la oferta' self.fields['tags'].label = 'Etiquetas / Tags / Tecnologías' self.fields['title'].help_text = title_help_text self.fields['tags'].help_text = tags_help_text self.fields['seniority'].help_text = seniority_help_text self.fields['company'].help_text = company_help_text self.fields['remote_work'].help_text = remote_work_help_text self.fields['description'].label = 'Descripción' self.helper = FormHelper() self.helper.layout = Layout( 'title', 'company', 'location', 'email', 'seniority', 'remote_work', 'tags', 'description', ) self.helper.add_input(Submit('job_submit', _('Guardar'))) self.helper.add_input( Reset('job_reset', _('Limpiar'), css_class='btn-default')) class Meta: model = Job exclude = ('owner', 'is_active')
class RevenueReportingForm(forms.ModelForm): associateWith = forms.ChoiceField( widget=forms.RadioSelect, choices=REVENUE_ASSOCIATION_CHOICES, label=_('This revenue is associated with:'), initial=1) currentlyHeldBy = forms.ModelChoiceField( queryset=User.objects.filter( Q(is_staff=True) | Q(staffmember__isnull=False)), label=_('Cash currently in possession of'), required=False, widget=autocomplete.ModelSelect2( url='autocompleteUser', attrs={ # This will set the input placeholder attribute: 'data-placeholder': _('Enter a user name'), # This will set the yourlabs.Autocomplete.minimumCharacters # options, the naming conversion is handled by jQuery 'data-minimum-input-length': 2, 'data-max-results': 4, 'class': 'modern-style', })) paymentMethod = autocomplete.Select2ListCreateChoiceField( choice_list=get_method_list, required=False, widget=autocomplete.ListSelect2(url='paymentMethod-list-autocomplete'), label=_('Payment method'), ) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', _('Submit'))) user = kwargs.pop('user', None) if hasattr(user, 'id'): kwargs.update(initial={'submissionUser': user.id}) super(RevenueReportingForm, self).__init__(*args, **kwargs) self.fields['submissionUser'].widget = forms.HiddenInput() self.fields['invoiceNumber'].widget = forms.HiddenInput() self.fields["invoiceItem"] = InvoiceItemChoiceField( queryset=InvoiceItem.objects.none(), required=False) # re-order fields to put the associateWith RadioSelect first. newFields = OrderedDict() newFields['associateWith'] = self.fields['associateWith'] for key, field in self.fields.items(): if key not in ['associateWith']: newFields[key] = field self.fields = newFields def clean_description(self): ''' Avoid empty descriptions ''' return self.cleaned_data['description'] or _('Form Submitted Revenue') def clean_invoiceNumber(self): ''' Create a unique invoice number ''' return 'SUBMITTED_%s_%s' % (getattr( self.cleaned_data['submissionUser'], 'id', 'None'), timezone.now().strftime('%Y%m%d%H%M%S')) def clean(self): # Custom cleaning ensures that revenues are not attributed # to both a series and to an event. super(RevenueReportingForm, self).clean() associateWith = self.cleaned_data.get('associateWith') event = self.cleaned_data.get('event') if associateWith in ['1', '3'] and event: self.cleaned_data.pop('event', None) self.cleaned_data.pop('invoiceItem', None) return self.cleaned_data class Meta: model = RevenueItem fields = [ 'submissionUser', 'invoiceNumber', 'category', 'description', 'event', 'invoiceItem', 'receivedFromName', 'paymentMethod', 'currentlyHeldBy', 'total', 'attachment' ] class Media: js = ('js/revenue_reporting.js', )
class OpeningForm(forms.ModelForm): class Meta: model = Opening fields = [ "title", "subject", "level", "description", "salary_range", "negotiable", "region", # "private", "group_tuition", # "job_active" ] labels = { 'salary_range': 'Your offering Rate/Hour', 'negotiable': 'Negotiable', 'description': 'Please state other requirements', 'region': 'Your region', # 'private': 'Hide this job from public', 'group_tuition': 'Group tuition', } help_texts = { 'title': 'Please state what you are looking for, i.e Looking for a results driven math tutor', # 'job_active': 'Please choose active to activate this opening.', # 'negotiable': 'Is the salary negotiable.', } def __init__(self, *args, **kwargs): super(OpeningForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input( Submit('submit', value='Save Details', css_class='buttonspace btn-success')) self.helper.layout = Layout( HTML("""<br><br>"""), Fieldset( 'Job Details', Div(Field('title'), css_class='col-xs-12 col-sm-10 col-md-8'), HTML("""<div class="row"></div>"""), Div(Field('subject'), css_class='col-xs-12 col-sm-10 col-md-8'), HTML("""<div class="row"></div>"""), Div(InlineRadios('level'), css_class='col-xs-12'), HTML("""<div class="col-sm-12"><br></div>"""), Div(Field('description'), css_class='col-xs-12'), ), HTML("""<br>"""), Fieldset( 'Other Details', Div(Field('salary_range'), css_class='col-xs-6 col-sm-4'), HTML("""<div class="col-xs-6 col-md-6 col-lg-6"><br></div>"""), Div(Field('negotiable'), css_class='col-xs-6'), HTML("""<div class="row"></div>"""), Div(InlineRadios('region'), css_class='col-xs-12'), HTML("""<div class="row"></div>"""), Div(Field('group_tuition'), css_class='col-xs-12'), # HTML("""<div class="row"></div>"""), # Div(Field('job_active'), css_class='col-xs-12'), ), ) salary_range = forms.ChoiceField(required=False, choices=pay_choices, label="Offering Rate/Hour")
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) helper = FormHelper() self.helper = helper helper.add_input(Submit('submit', 'Submit'))
class FoundationFormMixin(object): """ Mixin to implement the layout helper that will automatically build a form layout Generally, you will prefer to use ``FoundationForm`` or ``FoundationModelForm`` instead. If you still want to directly use this mixin you'll just have to execute ``FoundationFormMixin.init_helper()`` in your form init. """ title = None #: If set, defines the form's title layout = None #: If set, override the default layout for the form error_title = "Errors :" #: Defines the error title for non field errors form_id = None #: Defines the id of the form classes = "foundation-form" #: Defines the classes used on the form action = "" #: Defines the action of the form. ``reverse`` will be called on the value. On failure the value will be assigned as is method = "post" #: Defines the method used for the action attrs = {} #: Defines the attributes of the form switches = True #: If True, will replace all fields checkboxes with switches submit = True #: Adds a submit button on the form. Can be set to a Submit object or a string which will be used as the value of the submit button title_templatestring = u"<h3 class=\"subheader\">{0}</h3>" #: Template string used to display form title (if any) def init_helper(self): # Put required HTML attribute on required fields so they are managed by Abide (if enabled) if "data_abide" in self.attrs: for field in self.fields.values(): if field.required: field.widget.attrs["required"] = "" field.abide_msg = "This field is required." if not self.layout: # Start with an empty layout self.helper = FormHelper(self) else: # Start from the given layout self.helper = FormHelper() self.helper.layout = deepcopy(self.layout) # Try to reverse form_action url, else fallback to use it as a simple string try: self.helper.form_action = reverse(self.action) except NoReverseMatch: self.helper.form_action = self.action if self.title: self.helper.layout.insert( 0, HTML(self.title_templatestring.format(self.title))) if self.form_id is not None: self.helper.form_id = self.form_id self.helper.form_class = self.classes self.helper.form_method = self.method self.helper.form_error_title = self.error_title self.helper.attrs = self.attrs if self.switches: # Get a list of all fields with their location within the layout layout_field_names = self.helper.layout.get_field_names() # Transform checkbox fields to switches element for pointer in layout_field_names: if isinstance(self.fields[pointer[1]].widget, forms.CheckboxInput): self.replace_layout_object( pointer[0], InlineSwitchField(pointer[1], switch_class="inline")) if self.submit: if isinstance(self.submit, Submit): self.helper.add_input(self.submit) elif isinstance(self.submit, str): self.helper.add_input(Submit('submit', self.submit)) else: self.helper.add_input(Submit('submit', "Submit")) def replace_layout_object(self, position, instead): previous_layout_object = None layout_object = self.helper.layout.fields[position[0]] for i in position[1:]: previous_layout_object = layout_object layout_object = layout_object.fields[i] if previous_layout_object: previous_layout_object[-1] = instead else: self.helper.layout.fields[position[0]] = instead
class GeocodingBaseForm(forms.ModelForm): geocoding_task = None messages = {"use_geocoding": None, "coordinates_updated": None} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["coordinates"].widget = OSMWidget() self.helper = FormHelper() self.helper.form_method = "POST" self.helper.add_input(Submit("submit", "Sauvegarder")) form_elements = [] form_elements += [ Row(FullCol(Div("coordinates"))), Row( FullCol( HTML( format_html( ugettext( "<strong>Type de coordonnées actuelles</strong> : {}" ), self.instance.get_coordinates_type_display(), )))), ] if self.instance.has_manual_location(): self.fields["use_geocoding"] = forms.BooleanField( required=False, label= "Revenir à la localisation automatique à partir de l'adresse", help_text= _("Cochez cette case pour annuler la localisation manuelle de votre groupe d'action." ), ) form_elements.append(Row(FullCol("use_geocoding"))) self.helper.layout = Layout(*form_elements) def save(self, commit=True): if self.cleaned_data.get("use_geocoding"): self.instance.coordinates_type = None self.instance.coordinates = None super().save(commit=commit) self.geocoding_task.delay(self.instance.pk) else: if "coordinates" in self.changed_data: self.instance.coordinates_type = self.instance.COORDINATES_MANUAL super().save(commit=commit) return self.instance def get_message(self): if self.cleaned_data.get("use_geocoding"): return self.messages["use_geocoding"] elif "coordinates" in self.changed_data: return self.messages["coordinates_updated"] return None
class BaseApplicationForm(forms.Form): """ Given a dict of parameters describing the required fields for this application, constructs a suitable application form. Expected dict format: { 'user': [list, of, required, user, data, fields], 'partner_1': [list, of, required, fields, for, partner, 1], 'partner_2': [list, of, required, fields, for, partner, 2], (additional partners as needed) } 'user' is mandatory. 'partner_1' is mandatory. Additional partners are optional. See https://django-crispy-forms.readthedocs.org/ for information on form layout. """ def __init__(self, *args, **kwargs): self._validate_parameters(**kwargs) self.field_params = kwargs.pop('field_params') super(BaseApplicationForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self._initialize_form_helper() self.helper.layout = Layout() user_data = self.field_params.pop('user') self._add_user_data_subform(user_data) # For each partner, build a partner data section of the form. for partner in self.field_params: self._add_partner_data_subform(partner) # Make sure to align any checkbox inputs with other field types self.helper.filter_by_widget(forms.CheckboxInput).wrap( Div, css_class= "col-sm-8 col-sm-offset-4 col-md-9 col-md-offset-3 apply-tos") self.helper.add_input( Submit( 'submit', # Translators: Labels the button users click to apply for a partner's resources. _('Apply'), css_class='center-block')) def _get_partner_object(self, partner): # Extract the number component of (e.g.) 'partner_1'. try: partner_id = partner[8:] # Verify that it is the ID number of a real partner. partner = Partner.objects.get(id=partner_id) return partner except Partner.DoesNotExist: logger.exception('BaseApplicationForm received a partner ID that ' 'did not match any partner in the database') raise def _validate_parameters(self, **kwargs): """ Ensure that parameters have been passed in and match the format specified in the docstring. """ try: field_params = kwargs['field_params'] except KeyError: logger.exception('Tried to instantiate a BaseApplicationForm but ' 'did not have field_params') raise try: assert 'user' in field_params except AssertionError: logger.exception('Tried to instantiate a BaseApplicationForm but ' 'there was no user parameter in field_params') raise try: # We should have 'user' plus at least one partner in the keys. assert len(field_params.keys()) >= 2 except AssertionError: logger.exception( 'Tried to instantiate a BaseApplicationForm but ' 'there was not enough information in field_params') raise expected = re.compile(r'partner_\d+') for key in field_params.keys(): # All keys which are not the user data should be partner data. if key != 'user': try: assert expected.match(key) except AssertionError: logger.exception( 'Tried to instantiate a BaseApplicationForm but ' 'there was a key that did not match any expected values' ) def _validate_user_data(self, user_data): try: assert (set(user_data) <= set(USER_FORM_FIELDS)) except AssertionError: logger.exception('BaseApplicationForm received invalid user data') raise def _validate_partner_data(self, partner_data): try: assert (set(partner_data) <= set(PARTNER_FORM_OPTIONAL_FIELDS)) except AssertionError: logger.exception( 'BaseApplicationForm received invalid partner data') raise def _initialize_form_helper(self): # Add basic styling to the form. self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-xs-12 col-sm-4 col-md-3' self.helper.field_class = 'col-xs-12 col-sm-8 col-md-9' def _add_user_data_subform(self, user_data): self._validate_user_data(user_data) if user_data: # Translators: This labels a section of a form where we ask users to enter personal information (such as their country of residence) when making an application. user_data_layout = Fieldset(_('About you')) for datum in user_data: self.fields[datum] = FIELD_TYPES[datum] self.fields[datum].label = FIELD_LABELS[datum] # Show which partner wants which personal data if applying # for more than one. if len(self.field_params) > 1: # Translators: This text is shown in the application form under each piece of personal information requested. {partner_list} will be a list of 2 or more organisations that require this personal data, and should not be translated. self.fields[datum].help_text = _( "Requested by: {partner_list}".format( partner_list=", ".join(user_data[datum])).decode( 'utf-8')) user_data_layout.append(datum) self.helper.layout.append(user_data_layout) # Translators: This this note appears in a section of a form where we ask users to enter info (like country of residence) when applying for resource access. self.helper.layout.append( HTML( _('<p><small><i>Your personal data ' 'will be processed according to our <a href="{terms_url}">' 'privacy policy</a>.</i></small></p>'.format( terms_url=reverse('terms'))))) def _add_partner_data_subform(self, partner): partner_data = self.field_params[partner] partner_object = self._get_partner_object(partner) partner_layout = Fieldset( # Translators: This is the title of the application form page, where users enter information required for the application. It lets the user know which partner application they are entering data for. {partner} _('Your application to {partner}').format(partner=partner_object)) self._validate_partner_data(partner_data) # partner_data lists the optional fields required by that partner; # base fields should be in the form for all partners. all_partner_data = partner_data + PARTNER_FORM_BASE_FIELDS if all_partner_data: for datum in all_partner_data: # This will yield fields with names like 'partner_1_occupation'. # This will let us tell during form processing which fields # belong to which partners. field_name = '{partner}_{datum}'.format(partner=partner, datum=datum) self.fields[field_name] = FIELD_TYPES[datum] self.fields[field_name].label = FIELD_LABELS[datum] if datum == AGREEMENT_WITH_TERMS_OF_USE: # Make sure that, if the partner requires agreement with # terms of use, that link is provided inline. help_text = '<a href="{url}">{url}</a>'.format( url=partner_object.terms_of_use) self.fields[field_name].help_text = help_text if datum == SPECIFIC_STREAM: # Only show streams for this partner partner_id = int(partner[8:]) specific_stream = forms.ModelChoiceField( queryset=Stream.objects.filter(partner_id=partner_id)) self.fields[field_name] = specific_stream self.fields[field_name].label = FIELD_LABELS[datum] if datum == ACCOUNT_EMAIL: # If partner requires pre-registration, make sure users # get a link where they can sign up. # Translators: For some applications, users must register at another website before finishing the application form, and must then enter their email address used when registering. help_text = _( 'You must register at <a href="{url}">{url}</a> ' 'before applying.').format( url=partner_object.registration_url) self.fields[field_name].help_text = help_text partner_layout.append(field_name) self.helper.layout.append(partner_layout)
class BursaryRefereeAddForm(forms.Form): csv = forms.CharField( label='CSV input', help_text='Format: attendee_login,referee1_login,referee2_login', widget=forms.Textarea(attrs={'rows': 3}), required=True, ) def __init__(self, *args, **kwargs): super(BursaryRefereeAddForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.include_media = False self.helper.add_input(Submit('submit', 'Create Referees')) def clean(self): cleaned_data = super(BursaryRefereeAddForm, self).clean() r = csv.reader(cleaned_data['csv'].splitlines()) lines = {line[0]: set(line[1:]) for line in r} usernames = set(lines) referee_usernames = set().union(*lines.values()) bursaries = {} missing_users = [] referees = {} missing_referees = [] for username in usernames: try: bursary = Bursary.objects.get(user__username=username) except Bursary.DoesNotExist: missing_users.append(username) else: bursaries[username] = bursary for username in referee_usernames: try: referee = User.objects.get(username=username) except User.DoesNotExist: missing_referees.append(username) else: if referee.has_perm('bursary.change_bursaryreferee'): referees[username] = referee else: missing_referees.append(username) errors = [] if missing_users: errors.append( forms.ValidationError('no bursary request for users %s' % ', '.join(sorted(missing_users)))) if missing_referees: errors.append( forms.ValidationError('users %s are not referees' % ', '.join(sorted(missing_referees)))) if errors: raise forms.ValidationError(errors) cleaned_data['to_add'] = lines cleaned_data['bursaries'] = bursaries cleaned_data['referees'] = referees return cleaned_data
class PostCommentForm(django_forms.Form): ''' Base comment. This is inherited by others ''' comment = django_forms.CharField( label='', max_length=COMMENT_MAX_LENGTH, widget=django_forms.Textarea(attrs=dict( placeholder=_('Post a comment here...')))) def __init__(self, request, target_object, *args, **kwargs): # removing instance from kwargs because it isn't a ModelForm kwargs.pop("instance", None) super(PostCommentForm, self).__init__(*args, **kwargs) self.request = request self.target_object = target_object self.helper = FormHelper() self.helper.form_id = "post-comment" self.helper.form_class = "form-inline" self.helper.add_input( Submit('submit', _('Send'), css_class='btn btn-success btn-large')) def save(self): obj = self.get_comment_object() obj.save() action.send(self.request.user, verb='commented', target=self.target_object, action_object=obj, ipaddr=self.request.META.get('REMOTE_ADDR'), geolocation=json.dumps( geolocate_ip(self.request.META.get('REMOTE_ADDR')))) return obj def get_comment_object(self): """ Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``). """ if not self.is_valid(): raise ValueError( "get_comment_object may only be called on valid forms") CommentModel = self.get_comment_model() new = CommentModel(**self.get_comment_create_data()) new = self.check_for_duplicate_comment(new) return new def get_comment_model(self): """ Get the comment model to create with this form. Subclasses in custom comment apps should override this, get_comment_create_data, and perhaps check_for_duplicate_comment to provide custom comment models. """ return Comment def get_comment_create_data(self): return dict( content_type=ContentType.objects.get_for_model(self.target_object), object_pk=force_unicode(self.target_object._get_pk_val()), user=self.request.user, comment=self.cleaned_data["comment"], submit_date=timezone.now(), site_id=settings.SITE_ID, is_public=True, is_removed=False, ) def check_for_duplicate_comment(self, new): """ Check that a submitted comment isn't a duplicate. This might be caused by someone posting a comment twice. If it is a dup, silently return the *previous* comment. """ possible_duplicates = self.get_comment_model()._default_manager.using( self.target_object._state.db).filter( content_type=new.content_type, object_pk=new.object_pk, user=new.user, ) for old in possible_duplicates: if old.submit_date.date() == new.submit_date.date( ) and old.comment == new.comment: return old return new def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ if not self.request.user.is_authenticated(): raise django_forms.ValidationError( _("You must be authenticated to post a comment")) comment = self.cleaned_data["comment"] if settings.COMMENTS_ALLOW_PROFANITIES == False: bad_words = [ w for w in settings.PROFANITIES_LIST if w in comment.lower() ] if bad_words: plural = len(bad_words) > 1 raise django_forms.ValidationError(ungettext( "Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", plural) % \ get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], 'and')) return comment @staticmethod def static_get_form_kwargs(request, data, *args, **kwargs): ''' Returns the parameters that will be sent to the constructor ''' ret_kwargs = dict(request=request, data=data) if 'user' in kwargs: ret_kwargs['target_object'] = User.objects.get( username=kwargs["user"]) elif 'agora' in kwargs: ret_kwargs['target_object'] = Agora.objects.get(pk=kwargs["agora"]) elif 'election' in kwargs: ret_kwargs['target_object'] = Election.objects.get( pk=kwargs["election"]) return ret_kwargs
def get_crispy_helper(self): helper = FormHelper() helper.add_input(Submit(self.button_name, self.button_name)) helper.render_required_fields = False helper.html5_required = True return helper
class BursaryMassUpdateForm(forms.Form): csv = forms.CharField( label='CSV input', help_text='add a header line', widget=forms.Textarea(attrs={'rows': 3}), required=True, ) def __init__(self, *args, **kwargs): super(BursaryMassUpdateForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.include_media = False self.helper.add_input(Submit('submit', 'Update bursary requests')) def clean(self): cleaned_data = super(BursaryMassUpdateForm, self).clean() data = {} keys = set() r = csv.DictReader(cleaned_data['csv'].splitlines()) for line in r: if 'user.username' not in line: raise forms.ValidationError( 'CSV data needs a `user.username` key') data[line['user.username']] = line keys.update(line.keys()) keys.remove('user.username') errors = [] model_fields = {} for field in keys: try: model_fields[field] = Bursary._meta.get_field(field) except FieldDoesNotExist: errors.append( forms.ValidationError('Burary model has no %s field' % field)) if errors: raise forms.ValidationError(errors) bursaries = [] notifies = [] errors = [] missing_users = [] for username, updated_fields in data.items(): try: bursary = Bursary.objects.get(user__username=username) except Bursary.DoesNotExist: missing_users.append(username) continue old_statuses = { 'accommodation': bursary.accommodation_status, 'food': bursary.food_status, 'travel': bursary.travel_status, } for field, value in updated_fields.items(): if field == 'user.username': continue model_field = model_fields[field] if not value and model_field.null: value = None try: value = model_field.clean(value, bursary) except ValidationError as e: errors.append(e) else: setattr(bursary, field, value) try: bursary.full_clean() except ValidationError as e: errors.append(e) continue statuses = { 'accommodation': bursary.accommodation_status, 'food': bursary.food_status, 'travel': bursary.travel_status, } if statuses != old_statuses: notifies.append(bursary) bursaries.append(bursary) if missing_users: errors.append( forms.ValidationError('no bursary request for users %s' % ', '.join(sorted(missing_users)))) if errors: raise forms.ValidationError(errors) cleaned_data['bursaries'] = bursaries cleaned_data['notifies'] = notifies return cleaned_data
class StopImpersonatingForm(forms.Form): def __init__(self, *args, **kwargs): self.helper = FormHelper() super(StopImpersonatingForm, self).__init__(*args, **kwargs) self.helper.add_input(Submit("submit", _("Stop impersonating")))
class BootstrapForm(forms.Form): def __init__(self, *args, **kwargs): super(BootstrapForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.add_input(Submit('submit', 'Save'))