Пример #1
0
    def __init__(self, *args, **kwargs):
        super(CommonForm, self).__init__(*args, **kwargs)

        # Check if structure is present, if so, use hidden input
        if 'structure' in self.fields:
            self.fields['structure'].widget = forms.HiddenInput()
            # On entity creation, use user's structure
            if not self.instance or not self.instance.pk:
                structure = default_structure()
                if self.user:
                    structure = self.user.profile.structure
                self.fields['structure'].initial = structure

        for name, field in self.fields.items():
            self.filter_related_field(name, field)

        # allow to modify layout per instance
        self.helper.fieldlayout = deepcopy(self.fieldslayout)
        model = self._meta.model
        codeperm = '%s.publish_%s' % (model._meta.app_label,
                                      model._meta.object_name.lower())
        if 'published' in self.fields and self.user and not self.user.has_perm(
                codeperm):
            self.deep_remove(self.helper.fieldslayout, 'published')
        if 'review' in self.fields and self.instance and self.instance.any_published:
            self.deep_remove(self.helper.fieldslayout, 'review')
Пример #2
0
 class Meta:
     model = Honor
     fields = ['user', 'title', 'received_time']
     widgets = {
         'user': forms.HiddenInput(),
         'received_time': DateInput(),
     }
Пример #3
0
    def __init__(self, *args, **kwargs):
        super(CommonForm, self).__init__(*args, **kwargs)

        # Check if structure is present, if so, use hidden input
        if 'structure' in self.fields:
            self.fields['structure'].widget = forms.HiddenInput()
            # On entity creation, use user's structure
            if not self.instance or not self.instance.pk:
                structure = default_structure()
                if self.user:
                    structure = self.user.profile.structure
                self.fields['structure'].initial = structure

        for name, field in self.fields.items():
            if isinstance(field, django_forms.models.ModelChoiceField):
                try:
                    modelfield = self.instance._meta.get_field(name)
                except FieldDoesNotExist:
                    # be careful but custom form fields, not in model
                    modelfield = None
                if isinstance(modelfield, (ForeignKey, ManyToManyField)):
                    model = modelfield.related.parent_model
                    # Filter structured choice fields according to user's structure
                    if issubclass(model, StructureRelated):
                        field.queryset = StructureRelatedQuerySet.queryset_for_user(
                            field.queryset, self.user)
                    if issubclass(model, NoDeleteMixin):
                        field.queryset = field.queryset.filter(deleted=False)
Пример #4
0
class SettingsForm(forms.ModelForm):
	start = forms.DateField(input_formats=('%d.%m.%Y',), error_messages=RU_ERRORS, widget=forms.DateInput(attrs={'class': 'input-small form-control'}))
	finish = forms.DateField(input_formats=('%d.%m.%Y',), error_messages=RU_ERRORS, widget=forms.DateInput(attrs={'class': 'input-small form-control'}))
	time = forms.TimeField(input_formats=('%H:%M',), error_messages=RU_ERRORS, widget=forms.TimeInput(attrs={'class': 'form-control', 'id': 'alert-time-display', 'value': '12:00'}))
	email = forms.EmailField(required=False, error_messages=RU_ERRORS, widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': u'Укажите email для оповещений'}))
	phone = forms.RegexField(r'^\+79\d{9}$', '^\+79\d{9}$', required=False, error_messages=RU_ERRORS, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': u'+79123456789'}))
	user_time = forms.CharField(widget=forms.HiddenInput())

	class Meta:
		model = Alert
		widgets = {
			'alert_email': forms.CheckboxInput(attrs={'id': 'email-alert'}),
			'alert_sms': forms.CheckboxInput(attrs={'id': 'sms-alert'}),
			'period': forms.Select(attrs={'class': 'form-control'}),
		}
		exclude = ['user', 'alert_server_time']

	def clean(self):
		cleaned_data = super(SettingsForm, self).clean()

		if cleaned_data.get('alert_email') and cleaned_data.get('email') == '':
			raise forms.ValidationError(u'Введите email')

		if cleaned_data.get('alert_sms') and cleaned_data.get('phone') == '':
			raise forms.ValidationError(u'Введите номер телефона')
	
		return cleaned_data
Пример #5
0
 class Meta:
     model = models.Location
     fields = ('label', 'adr1', 'adr2', 'zipcode', 'city', 'point', 'area')
     widgets = {
         'label': forms.TextInput(),
         'point': widgets.LocationPointWidget(),
         'area': forms.HiddenInput(),
     }
 def render(self, name, value, attrs=None):
     # work around floppyforms bug with no attrs:
     if attrs is None:
         attrs = {}
     # If choices is set, use the display label
     displayed = str(dict((o[:2] for o in getattr(self, "choices", []))).get(
         value, value))
     return mark_safe(
         displayed + forms.HiddenInput().render(name, value, attrs))
Пример #7
0
 class Meta:
     model = McUser
     fields = [
         'title',
         'first_name',
         'real_name',
         'last_name',
         'maiden_name',
         'birthday',
         'gender',
         'class_year',
         'hometown',
         'hometown_state',
         'high_school',
         'phone_number',
         'id',
         'pic',
         'staff_title',
         'staff_phone',
         'linkedin',
         'website',
         'facebook',
         'email',
         'dorm_type',
         'dorm_number',
         'mailing_address',
         'mailing_city',
         'mailing_state',
         'mailing_zip',
         'mailing_country',
         'mailing_address_type',
         'in_dfw',
         'current_city',
         'significant_other',
         'children',
         'personal_news',
     ]
     widgets = {
         'id':
         forms.HiddenInput(),
         'pic':
         ImageThumbnailInput,
         'birthday':
         DateInput(),
         'mailing_address_type':
         forms.Select(choices=(('', ''), ('parent', 'parent address'),
                               ('alum', 'current alum address'))),
         'in_dfw':
         forms.Select(choices=(('', ''), ('Yes', 'Yes'), ('No', 'No'))),
         'title':
         forms.Select(choices=TITLE_CHOICES),
         'personal_news':
         forms.Textarea(attrs={
             'rows': 4,
             'cols': 15
         }),
     }
Пример #8
0
 class Meta:
     model = Page
     fields = ('website',
               'parent',
               'title',
               'slug',
               'draft',
               'app_page_type',
               'is_diplayed_in_menu',
               'menu_title',
               'meta_keywords',
               'meta_description',
               'default_template')
     widgets = {
         'meta_description': forms.Textarea(attrs={'cols': 40, 'rows': 5}),
         'website': forms.HiddenInput(),
         'slug': SlugWidget('title'),
         'parent': forms.HiddenInput(attrs={'value': ""}),
     }
Пример #9
0
 def __init__(self,
              attrs=None,
              map_template_name=None,
              google_maps_api_vars=None,
              map_attrs=None):
     widgets = (
         forms.HiddenInput(attrs=attrs),
         forms.HiddenInput(attrs=attrs),
         forms.CheckboxInput(attrs=attrs),
     )
     self.google_maps_api_vars = google_maps_api_vars or \
                                 self.google_maps_api_vars
     self.map_template_name = map_template_name or self.map_template_name
     self.map_attrs = {
         'width': self.map_width,
         'height': self.map_height,
         'zoom': self.map_zoom,
     }
     self.map_attrs.update(map_attrs or {})
     super(MapWidget, self).__init__(widgets, attrs)
Пример #10
0
    class Meta:
        # model = models.Location
        model = get_model('coop_local', 'Location')

        fields = ('label', 'adr1', 'adr2', 'zipcode', 'city', 'x_code',
                  'point', 'area')
        widgets = {
            'label': forms.TextInput(),
            'point': widgets.LocationPointWidget(),
            'area': forms.HiddenInput(),
        }
Пример #11
0
    def __init__(self, *args, **kwargs):
        super(PageWAForm, self).__init__(*args, **kwargs)
        self.fields['app_page_type'].choices = content_type_choices(LIMIT_CHOICES_TO)
        # Need to hide 'default_template' by default
        hide_default_tpl_field = True
        # Only if edition mode
        if hasattr(self.instance, 'pk'):
            if self.instance.pk:
                # Add help_text
                self.fields['app_page_type'].help_text = _(u"Be careful : if you change the app type, "
                                                           u"the current app will be deleted.")
                # Hide the slug field if we edit the homepage
                if self.instance.is_homepage:
                    self.fields['slug'].widget = forms.HiddenInput()

                # Initialization of templates theme
                theme_infos = themes_info(self.instance.website.theme.split('/')[0])[0]
                if 'templates' in theme_infos:
                    # Theme has many templates
                    # we set the choices with those values
                    choices_default_templates = []
                    for template in theme_infos['templates']:
                        if template['file'] == settings.TEMPLATE_THEME_FILE_DEFAULT:
                            file_value = ""
                        else:
                            file_value = template['file']
                        choices_default_templates.append((
                                file_value,
                                ({'title': template['title'], 'preview': template['preview']}),
                                ))
                    self.fields['default_template'].choices = choices_default_templates
                    # We don't hide the field
                    hide_default_tpl_field = False

        if hide_default_tpl_field:
            # The theme defines only one template,
            # so we hide the field and we add the current value of template page
            # in choices to avoid error validation
            self.fields['default_template'].choices = [(self.instance.default_template, '')]
            self.fields['default_template'].widget = forms.HiddenInput()
Пример #12
0
 class Meta:
     model = StudyAbroad
     fields = [
         'user', 'study_abroad_type', 'organization', 'description',
         'primary_location', 'other_locations', 'start_time', 'end_time'
     ]
     widgets = {
         'user': forms.HiddenInput(),
         'description': forms.Textarea(attrs={
             'rows': 4,
             'cols': 15
         }),
         'start_time': DateInput(),
         'end_time': DateInput(),
     }
Пример #13
0
 class Meta:
     model = Experience
     fields = [
         'user', 'exp_type', 'title', 'organization', 'description',
         'location', 'start_time', 'end_time'
     ]
     widgets = {
         'user': forms.HiddenInput(),
         'description': forms.Textarea(attrs={
             'rows': 4,
             'cols': 15
         }),
         'start_time': DateInput(),
         'end_time': DateInput(),
     }
Пример #14
0
    def __init__(self, *args, **kwargs):
        super(CommonForm, self).__init__(*args, **kwargs)

        # Check if structure is present, if so, use hidden input
        if 'structure' in self.fields:
            self.fields['structure'].widget = forms.HiddenInput()
            # On entity creation, use user's structure
            if not self.instance or not self.instance.pk:
                structure = default_structure()
                if self.user:
                    structure = self.user.profile.structure
                self.fields['structure'].initial = structure

        for name, field in self.fields.items():
            self.filter_related_field(name, field)
Пример #15
0
    class Meta:
        model = models.Proposal

        fields = ('confidential_reason', 'type', 'title', 'content', 'tags', 'assigned_to_user',
                  'assigned_to', 'due_by')

        widgets = {
            'type': forms.Select,
            'title': forms.TextInput,
            'content': HTMLArea,
            'assigned_to_user': forms.HiddenInput(),
            'assigned_to': forms.TextInput,
            'due_by': forms.DateInput,
            'confidential_reason': OCProposalRadioButtons
        }
Пример #16
0
 class Meta:
     model = Degree
     fields = [
         'user', 'school', 'degree_type', 'start_time', 'end_time',
         'major1', 'major2', 'minor1', 'minor2'
     ]
     widgets = {
         'user': forms.HiddenInput(),
         'major1': forms.TextInput(),
         'major2': forms.TextInput(),
         'minor1': forms.TextInput(),
         'minor2': forms.TextInput(),
         'start_time': DateInput(),
         'start_time': DateInput(),
         'end_time': DateInput(),
     }
Пример #17
0
 class Meta:
   model = McEvent
   fields = [
   #   'owner',
     'id',
     'subject',
     'start_date',
     'start_time',
     'end_date',
     'end_time',
     'all_day_event',
     'description',
     'location',
     'private',
     #'relevant_years',
   ]
   widgets = {
     'id': forms.HiddenInput(),
     'start_date': DateInput(),
     'start_time': TimeInput(),
     'end_date': DateInput(),
     'end_time': TimeInput(),
     'description': forms.Textarea(attrs={'rows':4}),
   }
Пример #18
0
 def add_fields(self, form, index):
     super(I4pLocationFormSet, self).add_fields(form, index)
     form.fields[DELETION_FIELD_NAME].widget = forms.HiddenInput()
Пример #19
0
class RegistrationForm(FloppyWidgetsMixin, NonFieldErrorsMixin,
                       registration_forms.RegistrationForm):
    username = forms.CharField(
        max_length=30,
        widget=forms.HiddenInput(),
        required=False,
        label=_("Username"),
        error_messages={
            'invalid':
            _("This value must contain only letters, numbers and underscores.")
        })

    email = forms.EmailField(
        max_length=75, label=_("Email address (this will be your username)"))
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    tos = forms.BooleanField(
        widget=forms.CheckboxInput(),
        label=_(u'I have read and agree to the Terms of Service'),
        error_messages={
            'required': _("You must agree to the terms to register")
        })

    is_general_public = forms.BooleanField(required=False,
                                           label=_(u'General Public'))
    is_community_advocate = forms.BooleanField(required=False,
                                               label=_(u'Community Advocate'))
    is_journalist = forms.BooleanField(required=False, label=_(u'Journalist'))
    is_researcher = forms.BooleanField(required=False, label=_(u'Researcher'))
    is_grant_writer = forms.BooleanField(required=False,
                                         label=_(u'Grant Writer'))
    is_city_state_agency_staff = forms.BooleanField(
        required=False, label=_(u'City / State Agency Staff'))
    is_consultant = forms.BooleanField(required=False, label=_(u'Consultant'))
    is_legislator = forms.BooleanField(required=False, label=_(u'Legislator'))
    is_policy_analyst = forms.BooleanField(required=False,
                                           label=_(u'Policy Analyst'))
    is_other = forms.BooleanField(required=False, label=_(u'Other'))
    organization = forms.CharField(max_length=300, required=False)
    org_is_non_profit = forms.BooleanField(required=False,
                                           label=_(u'Non-Profit'))
    org_is_state_city_agency = forms.BooleanField(
        required=False, label=_(u'City / State Agency'))
    org_is_university = forms.BooleanField(required=False,
                                           label=_(u'University'))
    org_is_other = forms.BooleanField(required=False, label=_(u'Other'))
    wants_notifications = forms.BooleanField(
        required=False,
        label=
        _(u"I'd like to receive notifications about trainings, new datasets, and general Profiles news"
          ))

    def clean_email(self):
        """
        Validate that the supplied email address is unique for the
        site.
        
        """
        if User.objects.filter(email__iexact=self.cleaned_data['email']):
            raise forms.ValidationError(
                _("This email address is already in use. Please supply a different email address."
                  ))
        return self.cleaned_data['email']

    def clean(self):
        """
        Verifiy 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 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(
                    _("The two password fields didn't match."))

        # hash the user's email address to use as a username
        m = hashlib.md5()
        m.update(self.cleaned_data['email'])
        self.cleaned_data['username'] = base64.b64encode(m.digest())
        return self.cleaned_data
Пример #20
0
 def __init__(self, attrs=None):
     _widgets = (DataGridWidget(),
                 forms.HiddenInput(attrs={'class': 'gridfield-hidden'}))
     super(DataGridCompound, self).__init__(_widgets, attrs)
Пример #21
0
 class Meta:
     model = MapaCategoria
     widgets = {
         'origen': forms.HiddenInput(),
     }
Пример #22
0
 def __init__(self, *args, **kwargs):
     """Initialize ModelForm. Pull out user kwarg, hide cc_version field."""
     self.user = kwargs.pop("user", None)
     super(MTModelForm, self).__init__(*args, **kwargs)
     self.fields["cc_version"].widget = floppyforms.HiddenInput()
Пример #23
0
 class HiddenForm(forms.Form):
     hide = forms.CharField(widget=forms.HiddenInput())