예제 #1
0
def loan_add(request, item_id):
    item = get_object_or_404(Item, pk=item_id)
    peoples = People.objects.all().order_by('-last_name')
    loan = Loan()
    loan.start_date = date.today()
    end_date_widget = SelectDateWidget()
    end_date_render = end_date_widget.render('end_date',
                                             loan.start_date)
    context = {
        'item': item,
        'loan': loan,
        'peoples': peoples,
        'end_date_widget': end_date_render,
    }
    return render(request, 'loan_add.html', context)
예제 #2
0
def loan_save(request, item_id):
    error = False
    error_message = []

    try:
        loan = Loan()
        loan.item = get_object_or_404(Item, pk=item_id)
        loan.start_date = date.today()
        loan.end_date = None
        loan.estimated_end_date = date(int(request.POST['end_date_year']),
                                       int(request.POST['end_date_month']),
                                       int(request.POST['end_date_day']))
        loan.state = STATE_IN_LOAN
        loan.observations_loan = request.POST['observations']
        loan.people = People.objects.get(pk=request.POST['people'])

    except(KeyError, People.DoesNotExist):
        error = True
        error_message.append("La persona es requerida")

    if error:
        peoples = People.objects.all().order_by('-last_name')
        end_date_widget = SelectDateWidget()
        end_date_render = end_date_widget.render('end_date',
                                                 loan.estimated_end_date)
        context = {
            'item': loan.item,
            'loan': loan,
            'peoples': peoples,
            'end_date_widget': end_date_render,
            'error_message': error_message,
        }
        return render(request, 'loan_add.html', context)
    else:
        loan.condition_loan = loan.item.condition
        loan.condition_return = None
        loan.start_date = datetime.today()
        loan.item.state = STATE_LENT
        loan.people.active_loans = loan.people.active_loans + 1
        loan.save()
        loan.item.save()
        loan.people.save()
        context = {
            'loan': loan,
            'success_message': 'El prestamo se ha relizado exitosamente.',
        }
        return render(request, 'loan.html', context)
예제 #3
0
파일: forms.py 프로젝트: enius76/Diabeto
class InscriptionDetailsForm(forms.Form):
    SEXE_CHOICES = (
        ('H', 'Homme'),
        ('F', 'Femme'),
    )
    DIABETE_CHOICES = (
        ('Type 1', 'Type 1'),
        ('Type 2', 'Type 2'),
    )

    #picture = forms.FileField(label='Ajoutez une photo de profil')
    birth = forms.DateField(widget=SelectDateWidget(years=range(1900, 2010)),
                            label='Date d\'anniversaire')
    sexe = forms.ChoiceField(label="Sexe",
                             choices=SEXE_CHOICES,
                             widget=forms.widgets.RadioSelect())
    height = forms.FloatField(label='Taille (en m)')
    weight = forms.FloatField(label='Poids (en kg)')
    typeDiabete = forms.ChoiceField(label="Type de diabète",
                                    choices=DIABETE_CHOICES,
                                    widget=forms.widgets.RadioSelect())
    glycMoyenne = forms.IntegerField(label='Glycémie moyenne (en mg/dl)')
예제 #4
0
class PatientInfoForm(forms.ModelForm):
    birthday = forms.DateField(
        widget=SelectDateWidget(years=range(timezone.now().year - 100,
                                            timezone.now().year)),
        initial=timezone.now().date())

    class Meta:
        model = Patient
        fields = ('birthday', 'sex', 'address', 'phone_number', 'insurance',
                  'height_ft', 'height_inch', 'weight', 'medical_info',
                  'hospital', 'ice_name', 'ice_phone')

        labels = {
            'phone_number': _('Phone Number [(999) 999-9999]'),
            'insurance': _('Insurance Number [123456789]'),
            'height_ft': _('Height (ft.)'),
            'height_inch': _('Height (in.)'),
            'medical_Info': _('Medical Info'),
            'hospital': _('Hospital'),
            'ice_name': _('Emergency Contact Name'),
            'ice_phone': _('Emergency Contact Phone')
        }
예제 #5
0
class ReservationForm(forms.ModelForm):
    first_name = forms.CharField(max_length=128, required=True, \
                                 widget=forms.TextInput(attrs={'required': 'true'}), \
                                 help_text="First name")
    last_name = forms.CharField(max_length=128, required=True,
                                widget=forms.TextInput(attrs={'required': 'true'}),\
                                help_text="Last name")
    city = forms.CharField(max_length=128, required=True, help_text="City")
    reservation_date = forms.DateField(help_text="Reservation date", \
                                       widget=SelectDateWidget(attrs={'required': 'true'}))
    phone_number = forms.CharField(max_length=128, required=True, \
                                   widget=forms.TextInput(attrs={'required': 'true'}), \
                                   help_text="Phone number")
    email = forms.EmailField(max_length=128, help_text="Email")
    comment = forms.CharField(max_length=200, widget=forms.Textarea)

    # An inline class to provide additional information on the form.
    class Meta:
        # Provide an association between the ModelForm and a model
        model = Reservation
        fields = ('first_name', 'last_name', 'city', 'reservation_date',
                  'phone_number', 'email', 'comment')
예제 #6
0
class CampForm(forms.ModelForm):
    #village = forms.ForeignKey(Village)
    camp_type = forms.CharField(max_length=20,
                                help_text="Camp Type Name")  #required
    date = forms.DateField(widget=SelectDateWidget(),
                           help_text="Enter Date")  #required
    strt_time = forms.TimeField(widget=SelectTimeWidget(),
                                help_text="Enter Start Time")
    end_time = forms.TimeField(widget=SelectTimeWidget(),
                               help_text="Enter End Time")
    organising_cost = forms.IntegerField(help_text="Enter Cost to Camp")
    #details = forms.TextField(widget=forms.Textarea, max_length=200, help_text="Details")
    slug = forms.SlugField(widget=forms.HiddenInput(), required=False)

    def clean(self):
        cleaned_data = self.cleaned_data
        village = self.cleaned_data.get("village")
        return cleaned_data

    class Meta:
        model = Camp
        fields = ('village', 'camp_type', 'date', 'strt_time', 'end_time',
                  'organising_cost', 'details')
예제 #7
0
class Register(forms.Form):
    nickname = forms.CharField(max_length=20,
                               label="昵称",
                               help_text="请输入您的别名!",
                               widget=forms.TextInput(attrs={
                                   'class': 'special',
                                   'id': 'nick'
                               }),
                               error_messages={'required': u'别名不能为空'})
    username = forms.CharField(label="用户名",
                               error_messages={'required': u'用户名不能为空'})
    password = forms.CharField(label="密码", widget=forms.PasswordInput)
    sex = forms.ChoiceField(widget=forms.RadioSelect,
                            choices=SEX_CHOICES,
                            label="性别")
    email = forms.EmailField(label="邮箱",
                             error_messages={
                                 'required': u'邮箱不能为空',
                                 'invalid': u'请输入正确的邮箱'
                             })
    phone = forms.CharField(required=False, label="手机号")
    birthday = forms.DateField(widget=SelectDateWidget(
        years=BIRTH_YEAR_CHOICES))
예제 #8
0
class MenuForm(forms.ModelForm):
    """form to edit or create a menu"""
    expiration_date = forms.DateTimeField(widget=SelectDateWidget(
        years=range(2017, 2030)))
    items = forms.ModelMultipleChoiceField(queryset=models.Item.objects.all(),
                                           widget=forms.SelectMultiple())

    class Meta:
        model = models.Menu
        fields = ('season', 'items', 'expiration_date')

    def clean(self):
        """the year appearing in the name of the season
        should not be after the year of the expire date"""
        data = self.cleaned_data
        if 'season' in self.cleaned_data:
            season, year = models.validate_season(self.cleaned_data['season'])
            if year and year.year > self.cleaned_data['expiration_date'].year:
                raise ValidationError(
                    "Year of the Season '%d' cannot be after "
                    "the expiration date '%d'" %
                    (year.year, self.cleaned_data['expiration_date'].year))
        return data
    def __init__(self, request, *args, **kwargs):
        super(ReactivateForm, self).__init__(request, *args, **kwargs)

        self.fields['userid'] = forms.CharField(
            label=_("User ID"),
            widget=HiddenInput
        )

        self.fields['expdate'] = forms.DateTimeField(
            label="Expiration date",
            widget=SelectDateWidget(None, get_year_list())
        )

        self.fields['projects'] = forms.MultipleChoiceField(
            label=_('Available projects'),
            required=True,
            widget=forms.SelectMultiple(attrs={'class': 'switched'})
        )

        avail_prjs = list()
        for prj_entry in Project.objects.all():
            avail_prjs.append((prj_entry.projectname, prj_entry.projectname))
        self.fields['projects'].choices = avail_prjs
예제 #10
0
class PersonRegistrationForm(forms.ModelForm):
    """
    @class: PersonRegistrationForm
    @description: This form is where the Person specific information is entered
    """
    birthday = forms.DateField(widget=SelectDateWidget(
        years={
            1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960,
            1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970, 1971,
            1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982,
            1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993,
            1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
            2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
        }),
                               label='Birthday:')

    # ssn = forms.IntegerField(widget=NumberInput, label='SSN:')
    # phoneNumber = USPhoneNumberField()

    class Meta:
        model = apps.get_model('base', 'Person')
        fields = ('birthday', 'phoneNumber')
        exclude = ('ssn', )
예제 #11
0
class IndividuForm(forms.Form):
    error_css_class = 'error'
    required_css_class = 'required'
    no = forms.IntegerField(label='n°', initial=1)
    date_de_naissance = forms.DateField(widget=SelectDateWidget(),
                                        initial=timezone.now())
    nodeclar = forms.IntegerField(label='Numéro de déclaration', initial=1)
    positiondeclar = forms.ChoiceField(label='Position déclaration impôts',
                                       choices=POSITION_DECLARATION_CHOICES)
    remplirdeclar = forms.BooleanField(required=False,
                                       initial=True,
                                       label='Foyer')
    #    test = forms.IntegerField(label = 'foyer1', initial = 42)
    #    test2 = forms.IntegerField(label = 'foyer2', initial = 42)
    nofam = forms.IntegerField(label='Numéro de famille', initial=1)
    positionfam = forms.ChoiceField(label='Position déclaration impôts',
                                    choices=POSITION_FAMILLE_CHOICES)


#    def __init__(self, *args, **kwargs):                        #fonction pour rajouter un paramètre au formulaire
#        no = kwargs.pop('no')
#        super(SimulationForm, self).__init__(*args, **kwargs)
#        self.fields = forms.IntegerField(label = 'n°')
예제 #12
0
    def __init__(self, *args, **kwargs):
        super(CongregacionForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)

        self.fields['fecha_fundacion'].widget = SelectDateWidget(
            years=(range(1900,
                         date.today().year + 1)))

        self.helper.form_tag = False
        self.helper.label_class = 'col-sm-3'
        self.helper.field_class = 'col-sm-9'

        self.fields['titulos_obtenidos'].widget = forms.TextInput(
            attrs={'placeholder': 'Tecnico en Biblia, Master en Biblia'})

        self.helper.all().wrap(Field, css_class='input-sm')
        self.helper.filter_by_widget(forms.Textarea).wrap(
            Field, css_class="input-xlarge", rows="2")
        self.helper.filter_by_widget(SelectDateWidget).wrap(
            Field,
            css_class="input-sm",
            style="width:110px; float:left; margin-right:5px;")
        self.helper.filter_by_widget(forms.Select).wrap(InlineRadios)
예제 #13
0
 def __init__(self,
              attrs=None,
              hour_step=None,
              minute_step=None,
              second_step=None,
              twelve_hr=None,
              use_seconds=True,
              required=True,
              years=None):
     """
     pass all these parameters to their respective widget constructors...
     """
     widgets = (SelectDateWidget(attrs=attrs,
                                 years=years,
                                 required=required),
                SelectTimeWidget(attrs=attrs,
                                 hour_step=hour_step,
                                 minute_step=minute_step,
                                 second_step=second_step,
                                 twelve_hr=twelve_hr,
                                 use_seconds=use_seconds,
                                 required=required))
     super(SplitSelectDateTimeWidget, self).__init__(widgets, attrs)
예제 #14
0
class UpdatePlayerProfile(forms.ModelForm):
    name = forms.CharField(label='Full Name', max_length=100, required=False)
    city = forms.CharField(label='City', max_length=100, required=False)
    club = forms.CharField(label='Club Team', max_length=100, required=False)
    state = forms.CharField(label='State', max_length=100, required=False)
    school = forms.CharField(label='School', max_length=100, required=False)
    position = forms.CharField(label='Position',
                               max_length=100,
                               required=False)
    phone = forms.CharField(label='Phone Number',
                            max_length=100,
                            required=False)
    SAT = forms.IntegerField(label='SAT', required=False)
    ACT = forms.IntegerField(label='ACT', required=False)
    GPA = forms.DecimalField(label='GPA',
                             max_digits=3,
                             decimal_places=2,
                             required=False)
    birthDate = forms.DateField(
        label='Birth Date',
        widget=SelectDateWidget(years=range(1985,
                                            datetime.date.today().year + 10)))
    video = forms.CharField(required=False,
                            label='Link To Highlight Video',
                            max_length=150)
    #achievements = forms.CharField(required=False, label='Achievements', max_length=500)
    photo = forms.ImageField(required=True, label='Upload a Profile Photo')

    #video = forms.CharField(required=False, label='Link To Highlight Video', max_length=150)
    class Meta:
        model = Player
        fields = [
            'name', 'club', 'city', 'state', 'school', 'position', 'SAT',
            'ACT', 'GPA', 'phone', 'birthDate', 'video', 'photo'
        ]

    """helper = FormHelper()
예제 #15
0
class WorkoutFormCreate(ModelForm):
    duration = DecimalField(
        min_value=0,
        max_value=40,
        max_digits=5,
        label="Duration (15 min blocks)",
        help_text="e.g., for a 30 minute workout, enter '2'.")

    with_other_class = BooleanField(
        label="With different class?",
        help_text="BONUS POINTS! Select this if you worked out with" +
        "a teammates from a different graduating class, like a" +
        "Sophomore with a Junior.")

    workout_date = DateField(initial=datetime.today,
                             widget=SelectDateWidget(years=(2015, 2016)),
                             label="Workout Date",
                             help_text="When did you do the workout?")

    activity = ModelChoiceField(
        queryset=Activity.objects.order_by('description'))

    class Meta:
        model = Workout
        fields = [  # Appears in the form in this order:
            'workout_date',
            'activity',
            'with_other_class',
            'duration',
        ]
        exclude = [
            'user',
        ]

    def __init__(self, user=None, *args, **kwargs):
        super(WorkoutFormCreate, self).__init__(*args, **kwargs)
        self._user = user
예제 #16
0
파일: forms.py 프로젝트: feekay/sofza
class projectForm(forms.ModelForm):
    CHOICES = (('$', "Dollar"), (u'\u00A3', "Pound"), (u'\u20AC', "Euro"))
    SITES = (("fb", "Facebook"), ("sk", "Skype"), ("fvr", "Fivrr"),
             ("mail", "Mail"), ("pph", "P/Hour"), ("etc", "Others"))

    client = forms.CharField(max_length=50,
                             label="Client Name",
                             widget=forms.TextInput(attrs={'required': ''}))
    client_mail = forms.EmailField(widget=forms.EmailInput(
        attrs={'required': ''}))
    title = forms.CharField(max_length=50,
                            label="Project Title",
                            widget=forms.TextInput(attrs={
                                'required': '',
                                'autocomplete': 'off'
                            }))
    source = forms.ChoiceField(
        choices=SITES, widget=forms.RadioSelect(attrs={'required': ''}))
    cost = forms.IntegerField(widget=forms.NumberInput(
        attrs={
            'required': '',
            'min': '1',
            'onkeypress': 'return event.charCode >= 48 && event.charCode <= 57'
        }))
    pay_type = forms.ChoiceField(choices=CHOICES,
                                 label="Payment Currency",
                                 initial='',
                                 widget=forms.Select(),
                                 required=True)
    start_date = forms.DateField(widget=SelectDateWidget())

    class Meta:
        model = Project
        exclude = [
            'id', 'alloted', 'last_updated', 'completed', 'completed_date',
            'revenue', 'success'
        ]
예제 #17
0
class FormContacto(forms.Form):
    _bandas = [('pink_floyd', 'Pink Floyd'), ('led_z', 'Led Zeppelin'),
               ('soda', 'Soda Stereo')]

    nombre_completo = forms.CharField(
        max_length=150,
        required=False,
        label="Nombre Completo",
        widget=TextInput(attrs={
            'class': 'form-control',
            'name': 'nombre_completo'
        }))

    email = forms.EmailField(
        required=True, widget=EmailInput(attrs={'class': 'form-control'}))

    mensaje = forms.CharField(max_length=750,
                              required=True,
                              widget=Textarea(attrs={
                                  'rows': 5,
                                  'class': 'form-control'
                              }))

    fecha = forms.DateField(
        required=False,
        widget=SelectDateWidget(attrs={'class': 'form-control'}))

    edad = forms.IntegerField(
        required=False,
        max_value=10,
        min_value=0,
        widget=NumberInput(attrs={'class': 'form-control'}))

    banda_favorita = forms.ChoiceField(
        required=False,
        choices=_bandas,
        widget=Select(attrs={'class': 'form-control'}))
예제 #18
0
파일: base.py 프로젝트: rds0751/newapr
    def get_form_field_instances(self, request=None, form_entry=None,
                                 form_element_entries=None, **kwargs):
        """Get form field instances."""
        widget_attrs = {
            'class': theme.form_element_html_class,
            'type': 'date',
        }

        years = None
        if self.data.year_min is not None and self.data.year_max is not None:
            years = range(self.data.year_min, self.data.year_max)

        field_kwargs = {
            'label': self.data.label,
            'help_text': self.data.help_text,
            'initial': self.data.initial,
            # 'input_formats': self.data.input_formats,
            'required': self.data.required,
            'widget': SelectDateWidget(attrs=widget_attrs, years=years),
        }
        # if self.data.input_formats:
        #     kwargs['input_formats'] = self.data.input_formats

        return [(self.data.name, DateField, field_kwargs)]
예제 #19
0
class ReferralForm(ModelForm):
    class Meta:
        model = Referral
        exclude = ('patient', 'worker', 'cpt_code', 'icd9_code', 'icd10_code')

    creation_date = forms.DateField(initial=datetime.date.today,
                                    widget=SelectDateWidget())

    required_css_class = 'required'

    def clean_organization(self):
        organization = self.cleaned_data["organization"]
        referral_type = self.cleaned_data["referral_type"]

        service_slugs = []
        services = organization.services.all()
        for s in services:
            service_slugs.append(s.slug)
        #if the referral_type is not something the service provides, then Val Er.
        if not referral_type in service_slugs:
            msg = "%s does not provide %s." % (organization, referral_type)
            raise forms.ValidationError(msg)

        return organization
예제 #20
0
 class Meta:
     model = Inscrit
     fields = [
         'email', 'prenom', 'nom', 'adresse_postale', 'numero_de_telephone',
         'numero_adherent', 'date_de_naissance', 'bio', 'photo', 'cni',
         'declaration', 'departement', 'compte_twitter', 'compte_facebook'
     ]
     # , 'document'
     help_texts = {
         'photo':
         'Cette photo sera utilisée pour vous représenter dans nos supports de communication.',
         'bio':
         'Un court texte de présentation pour accompagner la photo, 500 caractères maxi. Pensez à indiquer pourquoi vous êtes engagé au MoDem, vos responsabilités éventuelles, ainsi que les raisons de votre soutien à Fibre Démocrate.',
         'numero_adherent':
         'Si vous le connaissez...',
         'adresse_postale':
         'Numéro, rue, code postal, ville, ...',
         'declaration':
         'Vous trouverez une déclaration type <a href="http://goo.gl/NIowBb" target="_blank">ici</a>.'
     }
     widgets = {
         'date_de_naissance':
         SelectDateWidget(months=MOIS, years=range(2000, 1930, -1)),
     }
예제 #21
0
 def __init__(self, attrs=None, date_format=None, time_format=None):
     date_widget = SelectDateWidget(attrs=attrs)
     time_format = forms.SplitDateTimeWidget.time_format
     time_widget = forms.TimeInput(attrs=attrs, format=time_format)
     forms.MultiWidget.__init__(self, (date_widget, time_widget), attrs)
예제 #22
0
파일: forms.py 프로젝트: alumnicell/SAIC
class StudentForm(forms.Form):
    DateInput = partial(forms.DateInput, {'class': 'datepicker'})
    ranges = [(n, min(n + 1, 2021)) for n in xrange(1930, 2021, 1)]
    yearOfPassing = [(n, min(n, 2021)) for n in xrange(1920, 2021, 1)]
    birthYear = [(n, min(n, 1920)) for n in xrange(1930, 2005, 1)]
    courseChoices = (
        (
            'UGD',
            'UGD',
        ),
        (
            'IDD',
            'IDD',
        ),
        (
            'IMD',
            'IMD',
        ),
        (
            'M.Tech./M.Pharm.',
            'M.Tech./M.Pharm.',
        ),
        (
            'Ph.D',
            'Ph.D',
        ),
    )
    branchChoices = (
        (
            'BC: School of Biochemical Engineering',
            'BC: School of Biochemical Engineering',
        ),
        (
            'BM: School of Biomedical Engineering',
            'BM: School of Biomedical Engineering',
        ),
        (
            'CE: Department of Civil Engineering',
            'CE: Department of Civil Engineering',
        ),
        (
            'CH: Department of Chemical Engineering & Technology',
            'CH: Department of Chemical Engineering & Technology',
        ),
        (
            'CR: Department of Ceramic Engineering',
            'CR: Department of Ceramic Engineering',
        ),
        (
            'CS: Department of Computer Science & Engineering',
            'CS: Department of Computer Science & Engineering',
        ),
        (
            'CY: Department of Chemistry (Applied Chemistry)',
            'CY: Department of Chemistry (Applied Chemistry)',
        ),
        (
            'EC: Department of Electronics Engineering',
            'EC: Department of Electronics Engineering',
        ),
        (
            'EE: Department of Electrical Engineering',
            'EE: Department of Electrical Engineering',
        ),
        (
            'MA: Department of Mathematical Sciences (Applied Maths)',
            'MA: Department of Mathematical Sciences (Applied Maths)',
        ),
        (
            'ME: Department of Mechanical Engineering',
            'ME: Department of Mechanical Engineering',
        ),
        (
            'MN: Department of Mining Engineering',
            'MN: Department of Mining Engineering',
        ),
        (
            'MS: School of Material Science & Technology',
            'MS: School of Material Science & Technology',
        ),
        (
            'MT: Department of Metallurgical Engineering',
            'MT: Department of Metallurgical Engineering',
        ),
        (
            'PH: Department of Pharmaceutics',
            'PH: Department of Pharmaceutics',
        ),
        (
            'PY: Department of Physics (Applied Pysics)',
            'PY: Department of Physics (Applied Physics)',
        ),
    )
    firstName = forms.CharField(
        label='First Name:',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'id': 'firstName',
                'placeholder': "Please enter your first name here"
            }),
        max_length=20)
    lastName = forms.CharField(
        label='Last Name:',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'id': 'lastName',
                'placeholder': "Please enter your last name here"
            }),
        max_length=20)
    gender = forms.ChoiceField(label='Gender:',
                               widget=forms.Select(attrs={
                                   'class': 'form-control',
                                   'id': 'gender'
                               }),
                               choices=(
                                   ('Male', 'Male'),
                                   ('Female', 'Female'),
                               ))
    dob = forms.DateField(label='Date Of Birth:',
                          widget=SelectDateWidget(attrs={
                              'class': 'form-control',
                              'style': 'width:32.3%;display:inline-block;',
                              'id': 'dob'
                          },
                                                  years=range(1930, 2005)))
    course = forms.MultipleChoiceField(
        label="Degree (Select atleast one option):",
        required=True,
        widget=forms.CheckboxSelectMultiple(attrs={
            'class': 'checkbox-inline',
            'id': 'course'
        }),
        choices=courseChoices,
    )
    #motherName = forms.CharField(label="Mother's Name:",widget=forms.TextInput(attrs={'class' : 'form-control'}), max_length=40)
    roll = forms.CharField(
        label='Roll No:',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'id': 'rollNo',
                'placeholder': "Please enter your Enrollment No."
            }),
        max_length=12)
    branch = forms.ChoiceField(label='Department:',
                               widget=forms.Select(attrs={
                                   'class': 'form-control',
                                   'id': 'branch'
                               }),
                               choices=branchChoices)
    year = forms.ChoiceField(label='Graduation Year:',
                             widget=forms.Select(attrs={
                                 'class': 'form-control',
                                 'id': 'year'
                             }),
                             choices=yearOfPassing)
    #course = forms.ChoiceField(label='Course:',widget=forms.Select(attrs={'class' : 'form-control'}),choices=(('Btech.','Btech.'),("IDD",'IDD'),))
    mobile = forms.CharField(
        label='Mobile No.:',
        widget=forms.TextInput(
            attrs={
                'class':
                'form-control',
                'style':
                'display:inline',
                'id':
                'mobile',
                'placeholder':
                "Enter your mobile number with country code.For eg +91XXXXXXXXXX"
            }),
        max_length=15)
예제 #23
0
파일: forms.py 프로젝트: alumnicell/SAIC
class FacultyForm(forms.Form):
    DateInput = partial(forms.DateInput, {'class': 'datepicker'})
    ranges = [(n, min(n + 1, 2020)) for n in xrange(1930, 2020, 1)]
    yearOfPassing = [(n, min(n, 2016)) for n in xrange(1920, 2016, 1)]
    birthYear = [(n, min(n, 1920)) for n in xrange(1930, 2002, 1)]
    branchChoices = (
        (
            'BC: School of Biochemical Engineering',
            'BC: School of Biochemical Engineering',
        ),
        (
            'BM: School of Biomedical Engineering',
            'BM: School of Biomedical Engineering',
        ),
        (
            'CE: Department of Civil Engineering',
            'CE: Department of Civil Engineering',
        ),
        (
            'CH: Department of Chemical Engineering & Technology',
            'CH: Department of Chemical Engineering & Technology',
        ),
        (
            'CR: Department of Ceramic Engineering',
            'CR: Department of Ceramic Engineering',
        ),
        (
            'CS: Department of Computer Science & Engineering',
            'CS: Department of Computer Science & Engineering',
        ),
        (
            'CY: Department of Chemistry (Applied Chemistry)',
            'CY: Department of Chemistry (Applied Chemistry)',
        ),
        (
            'EC: Department of Electronics Engineering',
            'EC: Department of Electronics Engineering',
        ),
        (
            'EE: Department of Electrical Engineering',
            'EE: Department of Electrical Engineering',
        ),
        (
            'MA: Department of Mathematical Sciences (Applied Maths)',
            'MA: Department of Mathematical Sciences (Applied Maths)',
        ),
        (
            'ME: Department of Mechanical Engineering',
            'ME: Department of Mechanical Engineering',
        ),
        (
            'MN: Department of Mining Engineering',
            'MN: Department of Mining Engineering',
        ),
        (
            'MS: School of Material Science & Technology',
            'MS: School of Material Science & Technology',
        ),
        (
            'MT: Department of Metallurgical Engineering',
            'MT: Department of Metallurgical Engineering',
        ),
        (
            'PH: Department of Pharmaceutics',
            'PH: Department of Pharmaceutics',
        ),
        (
            'PY: Department of Physics (Applied Pysics)',
            'PY: Department of Physics (Applied Physics)',
        ),
    )
    firstName = forms.CharField(
        label='First Name:',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'id': 'firstName',
                'placeholder': "Please enter your first name here"
            }),
        max_length=20)
    lastName = forms.CharField(
        label='Last Name:',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'id': 'lastName',
                'placeholder': "Please enter your last name here"
            }),
        max_length=20)
    gender = forms.ChoiceField(label='Gender:',
                               widget=forms.Select(attrs={
                                   'class': 'form-control',
                                   'id': 'gender'
                               }),
                               choices=(
                                   ('Male', 'Male'),
                                   ('Female', 'Female'),
                               ))
    dob = forms.DateField(label='Date Of Birth:',
                          widget=SelectDateWidget(attrs={
                              'class': 'form-control',
                              'style': 'width:32.3%;display:inline-block;',
                              'id': 'dob'
                          },
                                                  years=range(1930, 2002)))
    #motherName = forms.CharField(label="Mother's Name:",widget=forms.TextInput(attrs={'class' : 'form-control'}), max_length=40)

    branch = forms.ChoiceField(label='Department:',
                               widget=forms.Select(attrs={
                                   'class': 'form-control',
                                   'id': 'branch'
                               }),
                               choices=branchChoices)
    year = forms.ChoiceField(label='Joining Year:',
                             widget=forms.Select(attrs={
                                 'class': 'form-control',
                                 'id': 'Joinyear'
                             }),
                             choices=yearOfPassing)
    DesignationChoice = (
        ('Professor', 'Professor'),
        ('Associate Professor', 'Associate Professor'),
        ('Assistant Professor', 'Assistant Professor'),
        ('Research Professor', 'Research Professor'),
        ('Visiting Professor', 'Visiting Professor'),
        ('Retired Professor', 'Retired Professor'),
    )
    designation = forms.ChoiceField(
        label='Designation:',
        widget=forms.Select(attrs={
            'class': 'form-control',
            'id': 'FacultyDesignation'
        }),
        choices=DesignationChoice)
    #course = forms.ChoiceField(label='Course:',widget=forms.Select(attrs={'class' : 'form-control'}),choices=(('Btech.','Btech.'),("IDD",'IDD'),))
    mobile = forms.CharField(
        label='Mobile No.:',
        widget=forms.TextInput(
            attrs={
                'class':
                'form-control',
                'style':
                'display:inline',
                'id':
                'mobile',
                'placeholder':
                "Enter your mobile number with country code.For eg +91XXXXXXXXXX"
            }),
        max_length=15)
예제 #24
0
class EventForm(forms.ModelForm):
    start_date = forms.DateField(widget=SelectDateWidget(), label="Start Date")

    class Meta:
        model = Event
        fields = '__all__'
예제 #25
0
class MyRegForm(UserCreationForm):
    form_name = 'reg_form'
    error_messages = {
        'password_mismatch': "Пароли не совпадают!",
    }
    username = forms.CharField(
        help_text='Максимум 30 символов',
        validators=[
            validators.RegexValidator(
                r'^[\w.@+-]+$', 'Введите правильный логин. '
                'Логин может состоять из букв,цифр'
                'и  @/./+/-/_ символов.', 'invalid'),
        ],
        error_messages={
            'required': 'Это поле обязательное к запонению',
            'unique': 'Пользователь с таким логином уже существует'
        })
    password1 = forms.CharField(
        min_length=6,
        label='Пароль',
        widget=forms.PasswordInput,
        help_text="Минимум 6 символов",
    )
    password2 = forms.CharField(
        min_length=6,
        label='Введите пароль еще раз',
        help_text="Введите повторно пароль для проверки",
        widget=forms.PasswordInput)
    last_name = forms.CharField(
        max_length=50,
        label='Фамилия',
        error_messages={'required': 'Это поле обязательное к запонению'})
    first_name = forms.CharField(
        max_length=50,
        label='Имя',
        error_messages={'required': 'Это поле обязательное к запонению'})
    email = forms.EmailField(
        label='Email',
        required=True,
        error_messages={'unique': 'Пользователь с таким email уже существует'})
    phone = forms.CharField(
        max_length=30,
        label='Телефон',
        help_text='Телефон в формате ***-*******',
        validators=[
            validators.RegexValidator(
                r'^\d{3}\-\d{7}$',
                'Введите телефон в правильном формате!(***-*******)',
                'invalid'),
        ])
    date_of_birth = forms.DateField(
        label='Дата рождения',
        required=True,
        widget=SelectDateWidget(years=range(2015, 1940, -1)),
        error_messages={'invalid': 'Неверный формат даты'})

    class Meta:
        model = MyUser
        fields = ('last_name', 'first_name', 'username', 'email', 'password1',
                  'password2', 'date_of_birth', 'phone')

    def save(self, commit=True):
        user = super(MyRegForm, self).save(commit=False)
        user.email = self.cleaned_data['email']

        if commit:
            user.save()
        return user
예제 #26
0
class ProfileForm(forms.ModelForm):
    avatar = forms.ImageField(required=False)
    first_name = forms.CharField(label=_('First Name'),
                                 required=False,
                                 help_text=_("Optional"))
    last_name = forms.CharField(label=_('Last Name'),
                                required=False,
                                help_text=_("Optional"))
    birth_date = forms.DateField(
        label=_('Birth date'),
        widget=SelectDateWidget(
            years=range(datetime.date.today().year, 1900, -1)))

    show_birthday = forms.BooleanField(label=_('Show your birthday?'),
                                       required=False)
    show_email = forms.BooleanField(label=_('Show your e-mail?'),
                                    required=False)
    show_real_name = forms.BooleanField(label=_('Show your real name?'),
                                        required=False)

    format_options = (
        ("nick (full_name)", _("Username (Full Name)")),
        ("full_name (nick)", _("Full Name (Username)")),
        ("nick (first_name)", _("Username (First Name)")),
        ("nick (last_name)", _("Username (Last Name)")),
        ("first_name (nick)", _("First Name (Username)")),
        ("last_name (nick)", _("Last Name (Username)")),
    )
    display_name_format = forms.ChoiceField(
        label=_('How should your name be displayed?'),
        required=True,
        choices=format_options,
        help_text=_('You can ignore this if you chose not to show your name.'))

    language_options = (("en", _("English")), ("es", _("Spanish")),
                        ("eus", _("Euskera")))
    language_preference = forms.ChoiceField(
        label=_('Language'),
        required=True,
        choices=language_options,
        help_text=_('In which language would you prefer to use Alpaca?'))

    class Meta:
        model = User
        fields = ("avatar", "first_name", "last_name", "birth_date",
                  "show_birthday", "show_email", "show_real_name",
                  "display_name_format", "language_preference")

    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        self.fields['avatar'].initial = self.instance.profile.avatar
        self.fields['birth_date'].initial = self.instance.profile.birth_date
        self.fields[
            'show_birthday'].initial = self.instance.profile.show_birthday
        self.fields['show_email'].initial = self.instance.profile.show_email
        self.fields[
            'show_real_name'].initial = self.instance.profile.show_real_name
        self.fields[
            'display_name_format'].initial = self.instance.profile.display_name_format
        self.fields[
            'language_preference'].initial = self.instance.profile.language_preference

    def save(self, commit=True):
        user = super(ProfileForm, self).save(commit=False)

        if commit:
            user.save()
            user.profile.avatar = self.cleaned_data["avatar"]
            user.profile.birth_date = self.cleaned_data["birth_date"]
            user.profile.show_birthday = self.cleaned_data["show_birthday"]
            user.profile.show_email = self.cleaned_data["show_email"]
            user.profile.show_real_name = self.cleaned_data["show_real_name"]
            user.profile.display_name_format = self.cleaned_data[
                "display_name_format"]
            user.profile.language_preference = self.cleaned_data[
                "language_preference"]
            user.profile.save()

        return user
예제 #27
0
class TimeTableForm(forms.Form):
    name = forms.CharField(label='Name Your TimeTable',
                           widget=forms.TextInput(attrs={
                               'id': 'name',
                               'class': 'red'
                           }),
                           max_length=100)
    color = forms.ChoiceField(
        label='Choose a color',
        required=False,
        widget=forms.RadioSelect(attrs={'class': 'color_choice'}),
        choices=COLOR_CHOICES)
    start_date = forms.DateField(
        label='Start Date',
        # widget=DateInput(format="%d/%m/%Y", attrs={'class': 'start_date'}),
        widget=SelectDateWidget(None, YEAR_CHOICES),
        initial=datetime.now()
        #input_formats=["%m/%d/%Y"]
    )
    start_time = forms.TimeField(label='Start Time (HH:MM)',
                                 widget=forms.TimeInput(
                                     format='%H:%M',
                                     attrs={'class': 'start_time'}))
    event_count = forms.IntegerField(
        label='Number of lessons',
        widget=NumberInput(attrs={'class': 'event_count'}))
    # might want to use CheckboxSelectMultiple widget for all of these guys
    # https://docs.djangoproject.com/en/1.7/ref/forms/widgets/#radioselect

    # avail_days = forms.MultipleChoiceField(
    #     label='Choose Available Days:',
    #     required=False,
    #     widget=CheckboxSelectMultiple(),
    #     choices=DAY_CHOICES
    # )
    save = forms.CharField(required=False,
                           widget=HiddenInput(attrs={'class': 'save'}))

    has_sunday = forms.BooleanField(
        label='S',
        required=False,
        widget=CheckboxInput(attrs={'class': 'cbox'}))

    has_monday = forms.BooleanField(
        label='M',
        required=False,
        widget=CheckboxInput(attrs={'class': 'cbox'}))

    has_tuesday = forms.BooleanField(
        label='T',
        required=False,
        widget=CheckboxInput(attrs={'class': 'cbox'}))

    has_wednesday = forms.BooleanField(
        label='W',
        required=False,
        widget=CheckboxInput(attrs={'class': 'cbox'}))

    has_thursday = forms.BooleanField(
        label='T',
        required=False,
        widget=CheckboxInput(attrs={'class': 'cbox'}))

    has_friday = forms.BooleanField(
        label='F',
        required=False,
        widget=CheckboxInput(attrs={'class': 'cbox'}))

    has_saturday = forms.BooleanField(
        label='S',
        required=False,
        widget=CheckboxInput(attrs={'class': 'cbox'}))
예제 #28
0
class intersForm(forms.Form):
    date = forms.DateField(label='请选择日期', widget=SelectDateWidget(years=YEARS_CHOICES))
    top = forms.CharField(label='请填写查询的top条数', max_length=160, widget=forms.TextInput, )
    history = forms.ChoiceField(choices=HISTORYS_CHOICES, label='请选择历史趋势时间', widget=forms.Select, )
예제 #29
0
class SignupForm(account.forms.SignupForm):

    birthdate = forms.DateField(widget=SelectDateWidget(
        years=range(1910, 1991)))
예제 #30
0
class MultipleOccurrenceForm(forms.Form):
    day = forms.DateField(label=_('Date'),
                          initial=date.today,
                          widget=SelectDateWidget())

    start_time_delta = forms.IntegerField(
        label=_('Start time'),
        widget=forms.Select(choices=default_timeslot_offset_options))

    end_time_delta = forms.IntegerField(
        label=_('End time'),
        widget=forms.Select(choices=default_timeslot_offset_options))

    # recurrence options
    repeats = forms.ChoiceField(choices=REPEAT_CHOICES,
                                initial='count',
                                label=_('Occurrences'),
                                widget=forms.RadioSelect())

    count = forms.IntegerField(
        label=_('Total Occurrences'),
        initial=1,
        required=False,
        widget=forms.TextInput(attrs=dict(size=2, max_length=2)))

    until = forms.DateField(required=False,
                            initial=date.today,
                            widget=SelectDateWidget())

    freq = forms.IntegerField(
        label=_('Frequency'),
        initial=rrule.WEEKLY,
        widget=forms.RadioSelect(choices=FREQUENCY_CHOICES),
    )

    interval = forms.IntegerField(
        required=False,
        initial='1',
        widget=forms.TextInput(attrs=dict(size=3, max_length=3)))

    # weekly options
    week_days = MultipleIntegerField(WEEKDAY_SHORT,
                                     label=_('Weekly options'),
                                     widget=forms.CheckboxSelectMultiple)

    # monthly  options
    month_option = forms.ChoiceField(choices=(('on', _('On the')),
                                              ('each', _('Each:'))),
                                     initial='each',
                                     widget=forms.RadioSelect(),
                                     label=_('Monthly options'))

    month_ordinal = forms.IntegerField(widget=forms.Select(choices=ORDINAL),
                                       required=False)
    month_ordinal_day = forms.IntegerField(
        widget=forms.Select(choices=WEEKDAY_LONG), required=False)
    each_month_day = MultipleIntegerField([(i, i) for i in range(1, 32)],
                                          widget=forms.CheckboxSelectMultiple)

    # yearly options
    year_months = MultipleIntegerField(MONTH_SHORT,
                                       label=_('Yearly options'),
                                       widget=forms.CheckboxSelectMultiple)

    is_year_month_ordinal = forms.BooleanField(required=False)
    year_month_ordinal = forms.IntegerField(
        widget=forms.Select(choices=ORDINAL), required=False)
    year_month_ordinal_day = forms.IntegerField(
        widget=forms.Select(choices=WEEKDAY_LONG), required=False)

    #---------------------------------------------------------------------------
    def __init__(self, *args, **kws):
        super(MultipleOccurrenceForm, self).__init__(*args, **kws)
        dtstart = self.initial.get('dtstart', None)
        if dtstart:
            dtstart = dtstart.replace(
                minute=((dtstart.minute // MINUTES_INTERVAL) *
                        MINUTES_INTERVAL),
                second=0,
                microsecond=0)

            weekday = dtstart.isoweekday()
            ordinal = dtstart.day // 7
            ordinal = '%d' % (-1 if ordinal > 3 else ordinal + 1, )
            offset = (dtstart - datetime.combine(
                dtstart.date(), time(0, tzinfo=dtstart.tzinfo))).seconds

            self.initial.setdefault('day', dtstart)
            self.initial.setdefault('week_days', '%d' % weekday)
            self.initial.setdefault('month_ordinal', ordinal)
            self.initial.setdefault('month_ordinal_day', '%d' % weekday)
            self.initial.setdefault('each_month_day', ['%d' % dtstart.day])
            self.initial.setdefault('year_months', ['%d' % dtstart.month])
            self.initial.setdefault('year_month_ordinal', ordinal)
            self.initial.setdefault('year_month_ordinal_day', '%d' % weekday)
            self.initial.setdefault('start_time_delta', '%d' % offset)
            self.initial.setdefault('end_time_delta',
                                    '%d' % (offset + SECONDS_INTERVAL, ))

    #---------------------------------------------------------------------------
    def clean(self):
        day = datetime.combine(self.cleaned_data['day'], time(0))
        self.cleaned_data['start_time'] = day + timedelta(
            seconds=self.cleaned_data['start_time_delta'])

        self.cleaned_data['end_time'] = day + timedelta(
            seconds=self.cleaned_data['end_time_delta'])

        return self.cleaned_data

    #---------------------------------------------------------------------------
    def save(self, event):
        if self.cleaned_data['repeats'] == 'count' and self.cleaned_data[
                'count'] == 1:
            params = {}
        else:
            params = self._build_rrule_params()

        event.add_occurrences(self.cleaned_data['start_time'],
                              self.cleaned_data['end_time'], **params)

        return event

    #---------------------------------------------------------------------------
    def _build_rrule_params(self):
        iso = ISO_WEEKDAYS_MAP
        data = self.cleaned_data
        params = dict(freq=data['freq'], interval=data['interval'] or 1)

        if data['repeats'] == 'until':
            params['until'] = data['until']
        else:
            params['count'] = data.get('count', 1)

        if params['freq'] == rrule.WEEKLY:
            params['byweekday'] = [iso[n] for n in data['week_days']]

        elif params['freq'] == rrule.MONTHLY:
            if 'on' == data['month_option']:
                ordinal = data['month_ordinal']
                day = iso[data['month_ordinal_day']]
                params.update(byweekday=day, bysetpos=ordinal)
            else:
                params['bymonthday'] = data['each_month_day']

        elif params['freq'] == rrule.YEARLY:
            params['bymonth'] = data['year_months']
            if data['is_year_month_ordinal']:
                ordinal = data['year_month_ordinal']
                day = iso[data['year_month_ordinal_day']]
                params['byweekday'] = day(ordinal)

        elif params['freq'] != rrule.DAILY:
            raise NotImplementedError(
                _('Unknown interval rule ' + params['freq']))

        return params
예제 #31
0
 def __init__(self, attrs=None):
     widgets = (SelectDateWidget(attrs=attrs),
                forms.Select(choices=default_timeslot_options, attrs=attrs))
     super(SplitDateTimeWidget, self).__init__(widgets, attrs)
예제 #32
0
파일: forms.py 프로젝트: zenny/tendenci
class ProfileForm(TendenciBaseForm):

    first_name = forms.CharField(
        label=_("First Name"),
        max_length=100,
        error_messages={'required': 'First Name is a required field.'})
    last_name = forms.CharField(
        label=_("Last Name"),
        max_length=100,
        error_messages={'required': 'Last Name is a required field.'})
    email = EmailVerificationField(
        label=_("Email"),
        error_messages={'required': 'Email is a required field.'})
    email2 = EmailVerificationField(label=_("Secondary Email"), required=False)

    initials = forms.CharField(label=_("Initial"),
                               max_length=100,
                               required=False,
                               widget=forms.TextInput(attrs={'size': '10'}))
    display_name = forms.CharField(
        label=_("Display name"),
        max_length=100,
        required=False,
        widget=forms.TextInput(attrs={'size': '30'}))

    url = forms.CharField(label=_("Web Site"),
                          max_length=100,
                          required=False,
                          widget=forms.TextInput(attrs={'size': '40'}))
    company = forms.CharField(
        label=_("Company"),
        max_length=100,
        required=False,
        error_messages={'required': 'Company is a required field.'},
        widget=forms.TextInput(attrs={'size': '45'}))
    department = forms.CharField(label=_("Department"),
                                 max_length=100,
                                 required=False,
                                 widget=forms.TextInput(attrs={'size': '35'}))
    address = forms.CharField(
        label=_("Address"),
        max_length=150,
        required=False,
        error_messages={'required': 'Address is a required field.'},
        widget=forms.TextInput(attrs={'size': '45'}))
    address2 = forms.CharField(label=_("Address2"),
                               max_length=100,
                               required=False,
                               widget=forms.TextInput(attrs={'size': '40'}))
    city = forms.CharField(
        label=_("City"),
        max_length=50,
        required=False,
        error_messages={'required': 'City is a required field.'},
        widget=forms.TextInput(attrs={'size': '15'}))
    state = forms.CharField(
        label=_("State"),
        max_length=50,
        required=False,
        error_messages={'required': 'State is a required field.'},
        widget=forms.TextInput(attrs={'size': '5'}))
    zipcode = forms.CharField(
        label=_("Zipcode"),
        max_length=50,
        required=False,
        error_messages={'required': 'Zipcode is a required field.'},
        widget=forms.TextInput(attrs={'size': '10'}))
    country = CountrySelectField(label=_("Country"), required=False)
    mailing_name = forms.CharField(
        label=_("Mailing Name"),
        max_length=120,
        required=False,
        error_messages={'required': 'Mailing name is a required field.'},
        widget=forms.TextInput(attrs={'size': '30'}))

    username = forms.RegexField(
        regex=r'^[\w.@+-]+$',
        max_length=30,
        widget=forms.TextInput(attrs=attrs_dict),
        label=_(u'Username'),
        help_text=
        _("Required. Allowed characters are letters, digits, at sign (@), period (.), plus sign (+), dash (-), and underscore (_)."
          ),
        error_messages={
            'invalid':
            'Allowed characters are letters, digits, at sign (@), period (.), plus sign (+), dash (-), and underscore (_).'
        })

    password1 = forms.CharField(label=_("Password"),
                                widget=forms.PasswordInput(attrs=attrs_dict))
    password2 = forms.CharField(
        label=_("Password (again)"),
        widget=forms.PasswordInput(attrs=attrs_dict),
        help_text=_("Enter the same password as above, for verification."))
    security_level = forms.ChoiceField(initial="user",
                                       choices=(
                                           ('user', 'User'),
                                           ('staff', 'Staff'),
                                           ('superuser', 'Superuser'),
                                       ))
    interactive = forms.ChoiceField(initial=1,
                                    choices=(
                                        (1, 'Interactive'),
                                        (0, 'Not Interactive (no login)'),
                                    ))
    direct_mail = forms.ChoiceField(initial=1,
                                    choices=(
                                        (1, 'Yes'),
                                        (0, 'No'),
                                    ))
    notes = forms.CharField(label=_("Notes"),
                            max_length=1000,
                            required=False,
                            widget=forms.Textarea(attrs={'rows': '3'}))
    admin_notes = forms.CharField(label=_("Admin Notes"),
                                  max_length=1000,
                                  required=False,
                                  widget=forms.Textarea(attrs={'rows': '3'}))
    language = forms.ChoiceField(initial="en", choices=settings.LANGUAGES)
    dob = forms.DateField(required=False,
                          widget=SelectDateWidget(None, range(1920,
                                                              THIS_YEAR)))

    status_detail = forms.ChoiceField(choices=(
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('pending', 'Pending'),
    ))

    class Meta:
        model = Profile
        fields = (
            'salutation',
            'first_name',
            'last_name',
            'username',
            'password1',
            'password2',
            'phone',
            'phone2',
            'fax',
            'work_phone',
            'home_phone',
            'mobile_phone',
            'email',
            'email2',
            'company',
            'position_title',
            'position_assignment',
            'display_name',
            'hide_in_search',
            'hide_phone',
            'hide_email',
            'hide_address',
            'initials',
            'sex',
            'mailing_name',
            'address',
            'address2',
            'city',
            'state',
            'zipcode',
            'county',
            'country',
            'url',
            'dob',
            'ssn',
            'spouse',
            'time_zone',
            'language',
            'department',
            'education',
            'student',
            'direct_mail',
            'notes',
            'interactive',
            'allow_anonymous_view',
            'admin_notes',
            'security_level',
            'status_detail',
        )

    def __init__(self, *args, **kwargs):
        if 'user_this' in kwargs:
            self.user_this = kwargs.pop('user_this', None)
        else:
            self.user_this = None

        if 'user_current' in kwargs:
            self.user_current = kwargs.pop('user_current', None)
        else:
            self.user_current = None

        if 'required_fields_list' in kwargs:
            self.required_fields_list = kwargs.pop('required_fields_list',
                                                   None)
        else:
            self.required_fields_list = None

        super(ProfileForm, self).__init__(*args, **kwargs)

        if self.user_this:
            self.fields['first_name'].initial = self.user_this.first_name
            self.fields['last_name'].initial = self.user_this.last_name
            self.fields['username'].initial = self.user_this.username
            self.fields['email'].initial = self.user_this.email

            if self.user_this.is_superuser:
                self.fields['security_level'].initial = "superuser"
            elif self.user_this.is_staff:
                self.fields['security_level'].initial = "staff"
            else:
                self.fields['security_level'].initial = "user"
            if self.user_this.is_active == 1:
                self.fields['interactive'].initial = 1
            else:
                self.fields['interactive'].initial = 0

            del self.fields['password1']
            del self.fields['password2']

            if not self.user_current.profile.is_superuser:
                del self.fields['admin_notes']
                del self.fields['security_level']
                del self.fields['status_detail']

            if self.user_current.profile.is_superuser and self.user_current == self.user_this:
                self.fields['security_level'].choices = (('superuser',
                                                          'Superuser'), )

        if not self.user_current.profile.is_superuser:
            if 'status_detail' in self.fields: self.fields.pop('status_detail')

        # we make first_name, last_name, email, username and password as required field regardless
        # the rest of fields will be decided by the setting - UsersRequiredFields
        if self.required_fields_list:
            for field in self.required_fields_list:
                for myfield in self.fields:
                    if field == self.fields[myfield].label:
                        self.fields[myfield].required = True
                        continue

    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.
        """
        try:
            user = User.objects.get(username=self.cleaned_data['username'])
            if self.user_this and user.id == self.user_this.id and user.username == self.user_this.username:
                return self.cleaned_data['username']
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(
            _(u'This username is already taken. Please choose another.'))

    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 not self.user_this:
            if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
                if self.cleaned_data['password1'] != self.cleaned_data[
                        'password2']:
                    raise forms.ValidationError(
                        _(u'You must type the same password each time'))
        return self.cleaned_data

    def save(self, request, user_edit, *args, **kwargs):
        """
        Create a new user then create the user profile
        """
        username = self.cleaned_data['username']
        email = self.cleaned_data['email']
        params = {
            'first_name': self.cleaned_data['first_name'],
            'last_name': self.cleaned_data['last_name'],
            'email': self.cleaned_data['email'],
        }

        if not self.user_this:
            password = self.cleaned_data['password1']
            new_user = User.objects.create_user(username, email, password)
            self.instance.user = new_user
            update_user(new_user, **params)
        else:
            # for update_subscription
            self.instance.old_email = user_edit.email

            params.update({'username': username})
            update_user(user_edit, **params)

        if not self.instance.id:
            self.instance.creator = request.user
            self.instance.creator_username = request.user.username
        self.instance.owner = request.user
        self.instance.owner_username = request.user.username

        return super(ProfileForm, self).save(*args, **kwargs)