def __init__(self, *args, **kwargs): super(ChosenModelForm, self).__init__(*args, **kwargs) for field in self.fields: if self.fields[field].__class__.__name__ in ['ChoiceField', 'TypedChoiceField', 'MultipleChoiceField']: choices = self.fields[field].choices self.fields[field] = chosenforms.ChosenChoiceField(choices=choices) elif self.fields[field].__class__.__name__ in ['ModelChoiceField', 'ModelMultipleChoiceField']: queryset = self.fields[field].queryset self.fields[field] = chosenforms.ChosenModelMultipleChoiceField(queryset=queryset)
class EventAddForm(ModelForm): tags = chosenforms.ChosenModelMultipleChoiceField(required = False,queryset = Tag.objects.all()) class Meta: model = Event # fields = ('title','events_logo','tags') fields = ('title','events_logo', 'tags', 'lock_status', 'unlock_reason') widgets = { 'lock_status' : forms.HiddenInput(), 'unlock_reason' : forms.HiddenInput(), }
class SyllabusForm(ChosenTermMixin, forms.ModelForm): """Used as a base for UploadForm and EditForm.""" department = chosen_forms.ChosenModelChoiceField( queryset=Department.objects.all()) course_number = forms.CharField() instructors = chosen_forms.ChosenModelMultipleChoiceField( queryset=Instructor.objects.all()) course_instance = None # set by set_course_instance syllabus_instructors = None # set by set_course_instance class Meta(object): model = Syllabus fields = () def __init__(self, *args, **kwargs): super(SyllabusForm, self).__init__(*args, **kwargs) self.fields.keyOrder = [ 'department', 'course_number', 'instructors', 'term' ] def set_course_instance(self, cleaned_data): """Check if a course is valid and whether a course instance exists with the exact instructors given, and create a course instance if one doesn't exist. """ department = self.cleaned_data.get('department') course_number = self.cleaned_data.get('course_number') term = self.cleaned_data.get('term') course = get_object_or_none(Course, department=department, number=course_number) if not course: error_msg = '{department} {number} does not exist.'.format( department=department, number=course_number) self._errors['department'] = self.error_class([error_msg]) self._errors['course_number'] = self.error_class([error_msg]) raise forms.ValidationError('Invalid course') # check instructors to prevent trying to iterate over nothing self.syllabus_instructors = self.cleaned_data.get('instructors') if not self.syllabus_instructors: raise forms.ValidationError('Please fill out all fields.') course_instance = CourseInstance.objects.annotate( count=Count('instructors')).filter(count=len( self.syllabus_instructors), term=term, course=course) for instructor in self.syllabus_instructors: course_instance = course_instance.filter(instructors=instructor) if course_instance.exists(): course_instance = course_instance.get() else: course_instance = CourseInstance.objects.create(term=term, course=course) course_instance.instructors.add(*self.syllabus_instructors) course_instance.save() self.course_instance = course_instance def save(self, *args, **kwargs): """Add a course instance to the syllabus.""" self.instance.course_instance = self.course_instance return super(SyllabusForm, self).save(*args, **kwargs)
class CandidateUserProfileForm(forms.ModelForm): """Form for creating a candidate's user profile. Similar to quark.user_profiles.forms.UserProfileForm, but leaves out the fields that clash with UserCreationForm, as well as the bio field (not very important for candidates).""" gender = forms.ChoiceField(choices=UserProfile.GENDER_CHOICES, widget=forms.RadioSelect, required=True) major = chosen_forms.ChosenModelMultipleChoiceField( Major.objects.filter(is_eligible=True)) start_term = forms.ModelChoiceField( Term.objects.get_terms(reverse=True).exclude( id=Term.objects.get_current_term().id)) grad_term = forms.ModelChoiceField( Term.objects.get_terms(include_future=True).filter( id__gte=Term.objects.get_current_term().id)) class Meta(object): model = UserProfile fields = ('preferred_name', 'middle_name', 'birthday', 'gender', 'alt_email', 'major', 'start_term', 'grad_term', 'cell_phone', 'receive_text', 'home_phone', 'local_address1', 'local_address2', 'local_city', 'local_state', 'local_zip', 'perm_address1', 'perm_address2', 'perm_city', 'perm_state', 'perm_zip', 'international_address') widgets = { 'local_state': chosen_forms.ChosenSelect, 'perm_state': chosen_forms.ChosenSelect } def __init__(self, *args, **kwargs): super(CandidateUserProfileForm, self).__init__(*args, **kwargs) self.fields['birthday'].required = True year_max = timezone.now().year - 10 year_min = year_max - 70 self.fields['birthday'].widget = SelectDateWidget( years=range(year_min, year_max)) self.fields['cell_phone'].required = True self.fields['local_address1'].required = True self.fields['local_city'].required = True self.fields['local_state'].required = True self.fields['local_zip'].required = True def clean(self): cleaned_data = super(CandidateUserProfileForm, self).clean() UserProfileForm.clean_userprofile_addresses(cleaned_data) return cleaned_data def save(self, *args, **kwargs): major = self.cleaned_data['major'] start_term = self.cleaned_data['start_term'] grad_term = self.cleaned_data['grad_term'] college_student_info = CollegeStudentInfo.objects.get_or_create( user=self.instance.user)[0] college_student_info.major = major college_student_info.start_term = start_term college_student_info.grad_term = grad_term college_student_info.save(update_fields=['start_term', 'grad_term']) return super(CandidateUserProfileForm, self).save(*args, **kwargs)
class UserProfileForm(forms.ModelForm): # Include the user's username, first name, last name, and email address # from the user model, but don't allow the user to edit any except the # email address username = forms.CharField(required=False) first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) email = forms.EmailField(label='Primary email address') gender = forms.ChoiceField(choices=UserProfile.GENDER_CHOICES, widget=forms.RadioSelect, required=True) bio = forms.CharField(required=False, widget=forms.Textarea, help_text='Bio is optional for candidates') major = chosen_forms.ChosenModelMultipleChoiceField(Major.objects) start_term = forms.ModelChoiceField( Term.objects.get_terms(reverse=True).exclude( id=Term.objects.get_current_term().id)) grad_term = forms.ModelChoiceField( Term.objects.get_terms(include_future=True)) class Meta(object): model = UserProfile fields = ('username', 'first_name', 'preferred_name', 'middle_name', 'last_name', 'birthday', 'gender', 'email', 'alt_email', 'major', 'start_term', 'grad_term', 'bio', 'cell_phone', 'receive_text', 'home_phone', 'local_address1', 'local_address2', 'local_city', 'local_state', 'local_zip', 'perm_address1', 'perm_address2', 'perm_city', 'perm_state', 'perm_zip', 'international_address') widgets = { 'local_state': chosen_forms.ChosenSelect, 'perm_state': chosen_forms.ChosenSelect } def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) # Set the initial values for the user model fields based on those # corresponding values. Note that editing a user profile only makes # sense if an instance is provided, as every user will have a user # profile. self.fields['username'].initial = self.instance.user.username self.fields['first_name'].initial = self.instance.user.first_name self.fields['last_name'].initial = self.instance.user.last_name self.fields['email'].initial = self.instance.user.email student_org_user_profile = self.instance.get_student_org_user_profile() if student_org_user_profile: self.fields['bio'].initial = student_org_user_profile.bio # Set initial values for college student info college_student_info = self.instance.get_college_student_info() if college_student_info: self.fields['major'].initial = college_student_info.major.all() self.fields['start_term'].initial = \ college_student_info.start_term self.fields['grad_term'].initial = college_student_info.grad_term # Disable editing for user account fields (besides email): self.fields['username'].widget.attrs['disabled'] = 'disabled' self.fields['first_name'].widget.attrs['disabled'] = 'disabled' self.fields['last_name'].widget.attrs['disabled'] = 'disabled' # TODO(sjdemartini): Add clarifying help_text regarding forwarding email # to the "email" field here, as it will affect the forwarding email # address once LDAP modification is enabled in the save() method. # Change the range of dates shown for the birthday field to only # relevant times year_max = timezone.now().year - 10 year_min = year_max - 70 self.fields['birthday'].widget = SelectDateWidget( years=range(year_min, year_max)) # Make the local address required for someone editing their user # profile: self.fields['local_address1'].required = True self.fields['local_city'].required = True self.fields['local_state'].required = True self.fields['local_zip'].required = True def clean(self): cleaned_data = super(UserProfileForm, self).clean() UserProfileForm.clean_userprofile_addresses(cleaned_data) return cleaned_data @staticmethod def clean_userprofile_addresses(cleaned_data): """Require that the submitted form has either a permanent or international address.""" international_address = cleaned_data.get('international_address') perm_address1 = cleaned_data.get('perm_address1') perm_city = cleaned_data.get('perm_city') perm_state = cleaned_data.get('perm_state') perm_zip = cleaned_data.get('perm_zip') if (not international_address) and not (perm_address1 and perm_city and perm_state and perm_zip): raise forms.ValidationError( 'A permanent or international address is required.') def save(self, *args, **kwargs): """Save the user email if it has changed.""" email = self.cleaned_data['email'] if self.instance.user.email != email: self.instance.user.email = email self.instance.user.save(update_fields=['email']) # Save email address to LDAP if LDAP is enabled if getattr(settings, 'USE_LDAP', False): set_email(self.instance.user.get_username(), email) bio = self.cleaned_data['bio'] student_org_user_profile = self.instance.get_student_org_user_profile() if student_org_user_profile and student_org_user_profile.bio != bio: student_org_user_profile.bio = bio student_org_user_profile.save(update_fields=['bio']) major = self.cleaned_data['major'] start_term = self.cleaned_data['start_term'] grad_term = self.cleaned_data['grad_term'] college_student_info = self.instance.get_college_student_info() if college_student_info: update_fields = [] if college_student_info.major != major: college_student_info.major = major if college_student_info.start_term != start_term: college_student_info.start_term = start_term update_fields.append('start_term') if college_student_info.grad_term != grad_term: college_student_info.grad_term = grad_term update_fields.append('grad_term') college_student_info.save(update_fields=update_fields) return super(UserProfileForm, self).save(*args, **kwargs)
class compatibilidadForm(forms.Form): dispositivo = chosenforms.ChosenModelChoiceField( queryset=Dispositivo.objects.all()) subtipo = chosenforms.ChosenModelMultipleChoiceField( queryset=Subtipo.objects.all())
class BroadcastForm(forms.Form): def _get_unique_domisili(seq): seen = set() seen_add = seen.add return [x for x in seq if x not in seen and not seen_add(x)] REL_CHOICES = ( (0, "Dan"), (1, "Atau"), ) persons = Person.objects.all() bulk_domisili = [x.domisili for x in persons] unique_domisili = _get_unique_domisili(bulk_domisili) DOMISILI_CHOICES = [] for domisili in unique_domisili: DOMISILI_CHOICES.append( (domisili, domisili) ) message = forms.CharField( max_length=160, widget=forms.widgets.Textarea(attrs={'cols':100, 'rows':3},), ) external = forms.BooleanField( required = False, label = "Nomor Handphone", ) nonmembers = forms.BooleanField( required = False, label = "Non Member", ) member = forms.BooleanField( required = False, label = "Member", ) extra_phones = forms.CharField( required = False, widget=forms.TextInput(attrs={'class':'input-xlarge'},), ) non_member = chosenforms.ChosenModelMultipleChoiceField( queryset = nonmember.objects.all(), required = False, widget = chosenwidg.ChosenSelectMultiple() ) tema_informasi = forms.ModelMultipleChoiceField( queryset = TemaInformasi.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) tema_informasi_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) hubungan_keluarga = forms.ModelMultipleChoiceField( queryset = HubunganKeluarga.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) hubungan_keluarga_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) jenis_kelamin = forms.MultipleChoiceField( choices = ( (0, 'Laki-laki'), (1, 'Perempuan'), ), required = False, widget = forms.CheckboxSelectMultiple, ) jenis_kelamin_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) domisili = forms.MultipleChoiceField( choices = DOMISILI_CHOICES, required = False, widget = chosenwidg.ChosenSelectMultiple(), ) domisili_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) agama = forms.ModelMultipleChoiceField( queryset = Agama.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) agama_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) organisasi = chosenforms.ChosenModelMultipleChoiceField( queryset = Organisasi.objects.all(), required = False, widget = chosenwidg.ChosenSelectMultiple() ) organisasi_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) jenis_usaha = forms.ModelMultipleChoiceField( queryset = JenisUsaha.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) jenis_usaha_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) keahlian = forms.ModelMultipleChoiceField( queryset = Keahlian.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) keahlian_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) pendidikan_terakhir = forms.ModelMultipleChoiceField( queryset = PendidikanTerakhir.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) pendidikan_terakhir_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) hobi = forms.ModelMultipleChoiceField( queryset = Hobi.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) hobi_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) jurusan = forms.ModelMultipleChoiceField( queryset = Jurusan.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) jurusan_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) pekerjaan = forms.ModelMultipleChoiceField( queryset = Pekerjaan.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) pekerjaan_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) penerima_jaminan_sosial = forms.MultipleChoiceField( choices = ( (0, "Tidak"), (1, "Ya"), ), required = False, widget = forms.CheckboxSelectMultiple, ) penerima_jaminan_sosial_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) golongan_darah = forms.ModelMultipleChoiceField( queryset = GolonganDarah.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) golongan_darah_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) jadwal_ronda = forms.ModelMultipleChoiceField( queryset = JadwalRonda.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) jadwal_ronda_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) usia = forms.ModelMultipleChoiceField( queryset = Usia.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) usia_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) status_sosial = forms.ModelMultipleChoiceField( queryset = StatusSosial.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) status_sosial_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) desa = forms.ModelMultipleChoiceField( queryset = Desa.objects.all(), required = False, widget = forms.CheckboxSelectMultiple, ) dusun = forms.ModelMultipleChoiceField( queryset = Dusun.objects.all(), widget = forms.CheckboxSelectMultiple, required = False, ) kampung = forms.ModelMultipleChoiceField( queryset = Kampung.objects.all(), widget = forms.CheckboxSelectMultiple, required = False, ) rt = forms.ModelMultipleChoiceField( queryset = RT.objects.all(), widget = forms.CheckboxSelectMultiple, required = False, ) wilayah_rel = forms.ChoiceField( choices = REL_CHOICES, required = False, ) # data member yang ultah hari ini ultah = forms.BooleanField( required = False, label = "Member Ulang Tahun", ) kalender = datetime.date.today() bulan = kalender.month tanggal = kalender.day ultah_today = forms.ModelMultipleChoiceField( queryset = Person.objects.filter(tanggal_lahir__month=bulan, tanggal_lahir__day=tanggal), widget = forms.CheckboxSelectMultiple, required = False, )
class ExamForm(ChosenTermMixin, forms.ModelForm): """Used as a base for UploadForm and EditForm.""" department = chosen_forms.ChosenModelChoiceField( queryset=Department.objects.all()) course_number = forms.CharField() instructors = chosen_forms.ChosenModelMultipleChoiceField( queryset=Instructor.objects.all()) course_instance = None # set by set_course_instance exam_instructors = None # set by set_course_instance class Meta(object): model = Exam fields = ('exam_number', 'exam_type') def __init__(self, *args, **kwargs): super(ExamForm, self).__init__(*args, **kwargs) self.fields['exam_type'].label = 'Exam or solution file?' self.fields.keyOrder = [ 'department', 'course_number', 'instructors', 'term', 'exam_number', 'exam_type' ] def set_course_instance(self, cleaned_data): """Check if a course is valid and whether a course instance exists with the exact instructors given, and create a course instance if one doesn't exist. """ department = self.cleaned_data.get('department') course_number = self.cleaned_data.get('course_number') term = self.cleaned_data.get('term') course = get_object_or_none(Course, department=department, number=course_number) if not course: error_msg = '{department} {number} does not exist.'.format( department=department, number=course_number) self._errors['department'] = self.error_class([error_msg]) self._errors['course_number'] = self.error_class([error_msg]) raise forms.ValidationError('Invalid course') # check instructors to prevent trying to iterate over nothing self.exam_instructors = self.cleaned_data.get('instructors') if not self.exam_instructors: raise forms.ValidationError('Please fill out all fields.') # check whether each instructor has given permission for their exams for instructor in self.exam_instructors: instructor_permission = get_object_or_none(InstructorPermission, instructor=instructor) if instructor_permission and \ not instructor_permission.permission_allowed: error_msg = 'Instructor {name} has requested that their' \ 'exams not be uploaded to our exam files' \ 'database.'.format(name=instructor.full_name()) self._errors['instructors'] = self.error_class([error_msg]) raise forms.ValidationError('Ineligible exam') course_instance = CourseInstance.objects.annotate( count=Count('instructors')).filter(count=len( self.exam_instructors), term=term, course=course) for instructor in self.exam_instructors: course_instance = course_instance.filter(instructors=instructor) if course_instance.exists(): course_instance = course_instance.get() else: course_instance = CourseInstance.objects.create(term=term, course=course) course_instance.instructors.add(*self.exam_instructors) course_instance.save() self.course_instance = course_instance def save(self, *args, **kwargs): """Add a course instance to the exam.""" self.instance.course_instance = self.course_instance return super(ExamForm, self).save(*args, **kwargs)