Exemple #1
0
class ProductForm(forms.ModelForm):
    """Add product to a vendor."""

    name = forms.CharField(widget=autocomplete_light.TextWidget(
        'ProductAutocomplete',
        attrs={"placeholder": _("select your product if we already know it")}),
                           required=True,
                           label=_("Name"))
    category = HierarchicalField(queryset=models.Category.objects.all(),
                                 label=_("Category"))
    manufacturer = ModelChoiceCreationField(
        label=_("Manufacturer"),
        queryset=models.Manufacturer.objects.all(),
        to_field_name="name",
        required=False,
        widget=autocomplete_light.TextWidget(
            'ManufacturerAutocomplete',
            attrs={
                "placeholder":
                _("select the manufacturer if we already know them")
            }))

    class Meta:
        model = models.Product
        fields = ("name", "category", "description", "manufacturer", "photo",
                  "expedition_days", "tax")
        widgets = {
            'description': forms.Textarea,
            'extra': forms.Textarea,
            "photo": ClearableImageInput,
        }
Exemple #2
0
 def __init__(self, user, *args, **kwargs):
     super(ImageForm, self).__init__(*args, **kwargs)
     self.fields['album'].queryset = Album.objects.filter(user=user)
     self.fields['album'].required = True
     if AUTOCOMPLETE_LIGHT_INSTALLED:
         self.fields['tags'].widget = autocomplete_light.TextWidget(
             'TagAutocomplete')
Exemple #3
0
class HostDisableForm(forms.ModelForm):
    host_mac = forms.CharField(
        max_length="255",
        label="Host or Mac",
        widget=al.TextWidget("HostAutocomplete", widget_attrs={"placeholder": "HO"}),
    )

    def __init__(self, *args, **kwargs):
        super(HostDisableForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields["host_mac"] = forms.CharField(max_length=255, label="Mac")
            self.fields["host_mac"].widget.attrs["readonly"] = "readonly"
            self.fields["host_mac"].initial = str(self.instance.pk)
            if self.instance.host:
                self.fields["host_mac"].label = "%s (%s)" % ("Mac", self.instance.host)

    def clean(self):
        cleaned_data = super(HostDisableForm, self).clean()
        try:
            cleaned_data["mac"] = EUI(cleaned_data["host_mac"], dialect=mac_unix_common)
        except (AddrFormatError, TypeError):
            cleaned_data["mac"] = (
                Host.objects.filter(hostname=cleaned_data["host_mac"]).first().mac
            )

    class Meta:
        Model = Disabled
        fields = ("host_mac", "reason")
Exemple #4
0
class RequestForm(forms.Form):
    """This form creates new, single MuckRock requests"""

    JURISDICTION_CHOICES = [('f', 'Federal'), ('s', 'State'), ('l', 'Local')]

    title = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': 'Add a subject'}),
        max_length=255,
    )
    document_placeholder = (
        'Write one sentence describing what you\'re looking for. '
        'The more specific you can be, the better.')
    document = forms.CharField(widget=forms.Textarea(
        attrs={'placeholder': document_placeholder}))
    jurisdiction = forms.ChoiceField(choices=JURISDICTION_CHOICES,
                                     widget=forms.RadioSelect)
    state = autocomplete_light.ModelChoiceField(
        'StateAutocomplete',
        queryset=Jurisdiction.objects.filter(level='s', hidden=False),
        required=False)
    local = autocomplete_light.ModelChoiceField(
        'JurisdictionLocalAutocomplete', required=False)
    agency = forms.CharField(
        label='Agency',
        widget=autocomplete_light.TextWidget(
            'AgencySimpleAgencyAutocomplete',
            attrs={'placeholder': 'Type the agency\'s name'}),
        max_length=255)
    full_name = forms.CharField()
    email = forms.EmailField(max_length=75)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(RequestForm, self).__init__(*args, **kwargs)
        if self.request and self.request.user.is_authenticated():
            del self.fields['full_name']
            del self.fields['email']

    def clean(self):
        data = self.cleaned_data
        jurisdiction = data.get('jurisdiction')
        state = data.get('state')
        local = data.get('local')
        if jurisdiction == 's' and not state:
            error_msg = 'No state was selected.'
            self._errors['state'] = self.error_class([error_msg])
        if jurisdiction == 'l' and not local:
            error_msg = 'No locality was selected.'
            self._errors['local'] = self.error_class([error_msg])
        return self.cleaned_data

    def clean_email(self):
        """Do a case insensitive uniqueness check"""
        email = self.cleaned_data['email']
        if User.objects.filter(email__iexact=email):
            raise forms.ValidationError(
                "User with this email already exists.  Please login first.")
        return email
Exemple #5
0
class RegisterParticipantsForm(forms.Form):
    required_css_class = 'required'

    experiment_pk = forms.IntegerField(widget=widgets.HiddenInput)
    start_date = forms.DateField(
        required=False,
        help_text=_('''Date this experiment should activate and start.
                                 Used for multi-day experiments with daily rounds'''
                    ))
    experiment_password = forms.CharField(
        required=False,
        min_length=3,
        help_text=
        _('Participant login password. If blank, a unique password will be generated for each participant.'
          ))
    institution_name = forms.CharField(
        min_length=3,
        label="Institution name",
        required=False,
        initial='Arizona State University',
        widget=autocomplete_light.TextWidget(InstitutionAutocomplete),
        help_text=_('Institution to associate with these participants.'))
    registration_email_from_address = forms.EmailField(
        widget=EmailInput(),
        label=_('Sender email'),
        help_text=_(
            "Email address to use in the from field of the registration email")
    )
    sender = forms.CharField(
        required=False,
        label='Sender name',
        initial="The vcweb development team",
        help_text=_('Name to use when signing off the registration email'),
    )
    registration_email_subject = forms.CharField(
        min_length=3,
        label="Email subject",
        help_text=_('Subject line for the registration email'))
    registration_email_text = forms.CharField(
        required=False,
        widget=forms.Textarea,
        label="Email body",
        help_text=
        _('Custom text placed at the start of the message before generated registration text.'
          ))

    def clean_institution(self):
        institution_name = self.cleaned_data.get('institution_name').strip()
        if institution_name is None:
            self.institution = None
        else:
            (institution, created) = Institution.objects.get_or_create(
                name=institution_name)
            logger.debug("get or create institution %s - created? %s",
                         institution_name, created)
            self.institution = institution
        return self.institution
Exemple #6
0
class LabelForm(al.ModelForm):
    isoCode = forms.CharField(required=True,
                              widget=al.TextWidget('LabelAutocomplete'),
                              label="ISO 639-3")
    label_type = forms.CharField(required=False,
                                 widget=al.TextWidget('LabelTypeAutocomplete'),
                                 label="Type of the Label")
    label = forms.CharField(required=True,
                            help_text="The entities label or name.")

    class Meta:
        model = Label
        fields = ['label', 'label_type', 'isoCode']

    def __init__(self, *args, **kwargs):
        super(LabelForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = True
        self.helper.add_input(Submit('submit', 'Speichern'))
Exemple #7
0
class AccountForm(forms.ModelForm):
    required_css_class = 'required'

    first_name = forms.CharField(widget=widgets.TextInput)
    last_name = forms.CharField(widget=widgets.TextInput)
    email = forms.EmailField(widget=widgets.TextInput,
                             help_text=_('We will never share your email.'))
    institution = forms.CharField(
        widget=autocomplete_light.TextWidget(InstitutionAutocomplete),
        required=False,
        help_text=_(
            'The primary institution, if any, you are affiliated with.'))

    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance')
        super(AccountForm, self).__init__(*args, **kwargs)
        if instance is not None:
            for attr in ('first_name', 'last_name', 'email', 'institution'):
                self.fields[attr].initial = getattr(instance, attr)

    def clean(self):
        data = super(AccountForm, self).clean()
        email_address = data.get('email')
        validate_email(email_address)

        if not email_address:
            raise forms.ValidationError(
                _("Please enter a valid email address"))

        if self.instance.email != email_address:
            if User.objects.filter(email=email_address).exists():
                raise forms.ValidationError(
                    _("This email is already registered with our system, please try another.'"
                      ))
        return data

    def save(self, commit=True):
        profile = super(AccountForm, self).save(commit=False)
        institution_name = self.cleaned_data.get('institution')
        if institution_name:
            institution, created = Institution.objects.get_or_create(
                name=institution_name)
            profile.institution = institution
        else:
            profile.institution = None
            logger.debug('Institution is empty')

        for attr in ('first_name', 'last_name', 'email'):
            setattr(profile.user, attr, self.cleaned_data.get(attr))

        if commit:
            profile.save()
            profile.user.save()
        return profile
Exemple #8
0
 class Meta:
     model = Participant
     fields = [
         'first_name', 'last_name', 'email', 'gender', 'class_status',
         'major', 'favorite_sport', 'favorite_food', 'favorite_color',
         'favorite_movie_genre'
     ]
     widgets = {
         'major':
         autocomplete_light.TextWidget(ParticipantMajorAutocomplete)
     }
Exemple #9
0
class SessionInviteForm(forms.Form):
    GENDER_CHOICES = (('A', 'All'), ('M', 'Male'), ('F', 'Female'),)

    number_of_people = forms.IntegerField(
        help_text=_("Number of participants to invite to the selected experiment session(s)"),
        widget=NumberInput(attrs={'value': 0, 'class': 'input-mini'}))
    only_undergrad = forms.BooleanField(
        help_text=_("Limit to self-reported undergraduate students"),
        widget=CheckboxInput(attrs={'checked': True}), required=False)
    gender = forms.ChoiceField(choices=GENDER_CHOICES)
    affiliated_institution = forms.CharField(required=False, widget=autocomplete_light.TextWidget(
        InstitutionAutocomplete, attrs={'value': 'Arizona State University'}))
    invitation_subject = forms.CharField(widget=widgets.TextInput())
    invitation_text = forms.CharField(widget=widgets.Textarea(attrs={'rows': '4'}))
Exemple #10
0
 class Meta:
     model = Participant
     fields = [
         'gender', 'can_receive_invitations', 'class_status', 'major',
         'favorite_sport', 'favorite_food', 'favorite_color',
         'favorite_movie_genre'
     ]
     labels = {
         'can_receive_invitations':
         _('Receive invitations for experiments?')
     }
     widgets = {
         'major':
         autocomplete_light.TextWidget(ParticipantMajorAutocomplete),
     }
Exemple #11
0
class ReviewAgencyTaskForm(forms.Form):
    """Simple form to allow selecting an email address or fax number"""
    email_or_fax = forms.CharField(
        label='Update email or fax on checked requests:',
        widget=autocomplete_light.TextWidget('EmailOrFaxAutocomplete'),
        required=False,
    )
    update_agency_info = forms.BooleanField(
        label='Update agency\'s main contact info?',
        required=False,
    )
    snail_mail = forms.BooleanField(
        label='Make snail mail the prefered communication method',
        required=False,
    )
    resolve = forms.BooleanField(
        label='Resolve after updating',
        required=False,
    )
    reply = forms.CharField(
        label='Reply:',
        required=False,
        widget=forms.Textarea(attrs={
            'rows': 5,
        }),
    )

    def clean_email_or_fax(self):
        """Validate the email_or_fax field"""
        if self.cleaned_data['email_or_fax']:
            return get_email_or_fax(self.cleaned_data['email_or_fax'])
        else:
            return None

    def clean(self):
        """Make email_or_fax required if snail mail is not checked"""
        cleaned_data = super(ReviewAgencyTaskForm, self).clean()
        email_or_fax = cleaned_data.get('email_or_fax')
        snail_mail = cleaned_data.get('snail_mail')

        if not email_or_fax and not snail_mail:
            self.add_error(
                'email_or_fax',
                'Required if snail mail is not checked',
            )
Exemple #12
0
class FOIAAdminFixForm(forms.Form):
    """Form with extra options for staff to follow up to requests"""

    from_user = forms.ModelChoiceField(
            label='From',
            queryset=User.objects.none(),
            )
    email_or_fax = forms.CharField(
            label='To',
            required=False,
            widget=autocomplete_light.TextWidget('EmailOrFaxAutocomplete'),
            )
    other_emails = forms.CharField(
            label='CC',
            required=False,
            help_text='For emails only, comma seperated',
            widget=TaggitWidget('EmailAddressAutocomplete'),
            )
    subject = forms.CharField(max_length=255)
    comm = forms.CharField(label='Body', widget=forms.Textarea())
    snail_mail = forms.BooleanField(required=False, label='Snail Mail Only')

    def __init__(self, *args, **kwargs):
        request = kwargs.pop('request')
        foia = kwargs.pop('foia')
        super(FOIAAdminFixForm, self).__init__(*args, **kwargs)
        muckrock_staff = User.objects.get(username='******')
        self.fields['from_user'].queryset = User.objects.filter(
                pk__in=[
                    muckrock_staff.pk,
                    request.user.pk,
                    foia.user.pk,
                    ])
        self.fields['from_user'].initial = request.user.pk

    def clean_email_or_fax(self):
        """Validate the email_or_fax field"""
        return get_email_or_fax(self.cleaned_data['email_or_fax'])

    def clean_other_emails(self):
        """Validate the other_emails field"""
        return EmailAddress.objects.fetch_many(
                self.cleaned_data['other_emails'],
                ignore_errors=False,
                )