class AbsenceForm(ModelForm): person = ModelChoiceField(queryset=User.objects.filter(is_active=True)) start = DateField() end = DateField(widget=SelectDateWidget) class Meta: model = Absence
class ProjectForm(ModelForm): client = ModelChoiceField(queryset=Client.objects.filter(is_active=True)) start = DateField(widget=SelectDateWidget) end = DateField(widget=SelectDateWidget) class Meta: model = Project
def edit_fees_schedule(request , fee_schedule_id): ''' edit fees schedule ''' errors = {} ins_obj = None try: ins_id = request.session['ins_id'] ins_obj = Institution.objects.get(pk=ins_id) except Exception: return HttpResponse('<html><body><h3>Broken Session</h3></body></html' '>') record_updated = False try: instance = Fees_schedule.objects.get(pk=fee_schedule_id) except Exception: errors['object_does_not_exists'] = 'Object Does Not Exist' return render(request, 'add_edit_fees_schedule.html', locals()) if request.method == 'POST': form = FeeScheduleForm(request.POST, instance=instance) sh_amount = int(request.POST.get('fees_amount')) amount = instance.fee.amount s_date = request.POST.get('start_date') from django.forms.fields import DateField d = DateField() start_date = d.to_python(request.POST.get('start_date')) end_date = d.to_python(request.POST.get('end_date')) fee_obj = instance.fee results = get_date_for_edit(fee_schedule_id, fee_obj, start_date, end_date) amount = get_basic_amount_edit(fee_schedule_id, fee_obj) if results == 'start_date': errors['start_date_greater'] = \ 'Start date should not be greater than previous '\ 'installment\'s end date' return render(request, 'add_edit_fees_schedule.html', locals()) if results == 'end_date': errors['end_date_greater'] = \ 'end date should not be greater than next installment\'s '\ 'start date' return render(request, 'add_edit_fees_schedule.html', locals()) if sh_amount > amount: errors['amount_greater_than_basic_amount'] = \ ('Fees Amount should not be greater than ' + str(amount) + '(basic amount)') return render(request, 'add_edit_fees_schedule.html', locals()) else: if form.is_valid(): form1 = form.save(commit = False) form1.institution = ins_obj form1.save() # [2nd]===if u want to specify which fields to save use: # instance.save(update_fields=['name']) record_updated = True else: form = FeeScheduleForm(request.GET, instance=instance) form = FeeScheduleForm(instance=instance) return render(request , 'add_edit_fees_schedule.html', locals())
class PoolStatForm(Form): start_date = DateField(input_formats=['%Y-%m-%dT%H:%M'], widget=DateTimeInput( format='%Y-%m-%dT%H:%M', attrs={'type': 'datetime-local'})) end_date = DateField(input_formats=['%Y-%m-%dT%H:%M'], widget=DateTimeInput(format='%Y-%m-%dT%H:%M', attrs={'type': 'datetime-local'}))
class FuelStatForm(Form): start_date = DateField(input_formats=['%Y-%m-%dT%H:%M'], widget=DateTimeInput( format='%Y-%m-%dT%H:%M', attrs={'type': 'datetime-local'})) end_date = DateField(input_formats=['%Y-%m-%dT%H:%M'], widget=DateTimeInput(format='%Y-%m-%dT%H:%M', attrs={'type': 'datetime-local'})) auto = ModelChoiceField(queryset=models.Auto.objects.all())
class AllocationForm(ModelForm): project = ModelChoiceField(queryset=Project.objects.all()) person = ModelChoiceField(queryset=User.objects.filter(is_active=True)) start = DateField(widget=SelectDateWidget) end = DateField(widget=SelectDateWidget) weekly_hours = DateField(widget=SelectDateWidget) class Meta: model = Allocation exclude = ('person', )
class TimeEntryForm(ModelForm): project = ModelChoiceField(queryset=Project.objects.all()) # ovo mora biti aktivnost koju je upravo unio activity = ModelChoiceField(queryset=Activity.objects.all()) # ovo mora biti trenutno logirani user person = ModelChoiceField(queryset=User.objects.filter(is_active=True)) # ovo moraju biti sati i minute start = DateField(widget=SelectDateWidget) end = DateField(widget=SelectDateWidget) class Meta: model = Project
class AddHolidayForm(forms.Form): '''A form having from_date, to_date and purpose field. This will be used to ass holiday ''' from_date = DateField(widget=SelectDateWidget(years=YEAR_CHOICE), initial=datetime.now()) to_date = DateField(widget=SelectDateWidget(years=YEAR_CHOICE), initial=datetime.now()) purpose = CharField(max_length=200, required=True, widget=forms.Textarea, help_text="Maximum 200 character")
def test_insert_master_data(self): department = Department.objects.create(name="agriculture") designation = Designation.objects.create(name="jr_teacher") skill_type = Skill_Type.objects.create(name = "teaching") position_type = Position_Type.objects.create(name = "senior") salutions = Salutations.objects.create(name = "Dr") maritial_status = Maritial_Status.objects.create(name = "married") skill = Skills.objects.create(skill_type = skill_type, name="botany") staff_type = Staff_Type.objects.create(name="Worker") person = Person.objects.create(position_type=position_type, prefix = salutions, first_name = 'harish',farmer_id = '123',gender = 'male',maritial_status= maritial_status, uuid = 'sdf45') d = DateField() joining_date = d.to_python('2014-02-02') staff = Staff.objects.create(staff_type=staff_type, personal_info=person, date_of_joining=joining_date, work_experience=2)
class PresentationForm(ModelForm): birthdate = DateField(widget=AdminDateWidget) #birthdate = forms.DateTimeField( # input_formats=['%Y-%m-%d'], # label='Дата рождения', # widget=AdminDateWidget, # # widget=forms.CalendarInput, #) class Meta: model = Presentation fields = ( 'name', 'surname', 'birthdate', 'bio', 'phone', 'skype', 'photo', ) widgets = {'birthdate': DateWidget} def __init__(self, *args, **kwargs): super(PresentationForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs['class'] = 'form-control input-md' self.fields['surname'].widget.attrs['class'] = 'form-control input-md' self.fields['phone'].widget.attrs['class'] = 'form-control input-md' self.fields['skype'].widget.attrs['class'] = 'form-control input-md' #self.fields['birthdate'].widget.attrs['class'] = 'form-control' self.fields['photo'].widget.attrs['class'] = 'input-file' self.fields['bio'].widget.attrs['class'] = 'form-control'
class LancamentoForm(ModelForm): """ Form para cadastro de lancamentos. """ tags = TagField(max_length=50, label='Tags', required=False, widget=AutoCompleteTagInput()) vencimento = DateField(('%d/%m/%Y', ), label='Vencimento', widget=DateTimeInput(format='%d/%m/%Y')) tipo = ChoiceField(choices=Lancamento.TIPO_CHOICES) valor = PositiveDecimalField() class Meta: model = Lancamento fields = [ 'desc', 'vencimento', 'valor', 'tipo', 'forma_pagamento', 'credor', 'caixa', 'tags', 'pago' ] def __init__(self, *args, **kwargs): super(LancamentoForm, self).__init__(*args, **kwargs) if self.instance.id: self.initial['tags'] = ' '.join([ item.name for item in Tag.objects.get_for_object(self.instance) ]) #() def as_ext(self): # Converte os campos para o formato ExtJS return mark_safe(simplejson.dumps(self, cls=ExtJSONEncoder))
class LancamentoFormFilter(Form): """ Form apenas para validar os dados enviados para filtrar lancamentos. """ cadastro = DateField(('%d/%m/%Y', ), required=False, widget=DateTimeInput(format='%d/%m/%Y')) vencimento = DateField(('%d/%m/%Y', ), required=False, widget=DateTimeInput(format='%d/%m/%Y')) credor = CharField(required=False) caixa = CharField(required=False) tipo = ChoiceField(choices=Lancamento.TIPO_CHOICES, required=False) pago = BooleanField(required=False) tags = TagField(max_length=50, required=False)
class WorkoutForm(forms.ModelForm): title = forms.CharField(widget=EmojiPickerTextInput) creation_date = DateField(widget=AdminDateWidget()) class Meta: model = Workout fields = ['user', 'day', 'title', 'creation_date']
class ResetPasswordSecondForm(FormFieldConfigMixin, Form): question = CharField(widget=TextInput(attrs={'readonly': 'readonly'})) security_answer = CharField(label='Answer') date_of_birth = DateField(widget=DateInput()) def __init__(self, user, *args, **kwargs): super(ResetPasswordSecondForm, self).__init__(*args, **kwargs) self.fields['question'].initial = user.security_question self.user = user def clean_security_answer(self): try: return validators.validate_security_answer(self) except ValidationError: self.add_error(None, 'Invalid details') return self.cleaned_data['security_answer'] def clean_date_of_birth(self): try: return validators.validate_date_of_birth(self) except ValidationError: self.add_error(None, 'Invalid details') class Meta: config = ResetPasswordForm.Meta.config
class PostMovieForm(forms.ModelForm): """ Create movie form excluding user in form """ release_date = DateField(widget=forms.SelectDateWidget( years=range(datetime.date.today().year, 1800, -1))) class Meta: model = Movie exclude = ('author', )
class StaffSearchForm(forms.ModelForm): hire_after = DateField(label='在此之后就职:',required=False, widget=MyDateInput()) bank = ModelChoiceField(SubBank.objects.all(),label='所属支行',required=False) name = CharField(label='职工姓名',max_length=Staff._meta.get_field('name').max_length,required=False) class Meta: model = Staff fields = ['name','bank']
class PostActorForm(forms.ModelForm): """ Create actor form excluding user in form """ birthdate = DateField(widget=forms.SelectDateWidget( years=range(datetime.date.today().year, 1800, -1))) class Meta: model = Actor exclude = ('author', )
def get_discounts(room_key: int, check_in: fields.DateField, check_out: fields.DateField) -> str: rv = '' room = Room.objects.get(pk = room_key) d = room.discountedroom_set.all() t = d.filter(start_date__range=(check_in.initial(), check_out.initial.date())) for i in t: rv += f' {i.discount}' return rv
class AppointmentForm(forms.ModelForm): date = DateField(widget = AdminDateWidget()) time = forms.TimeField(widget= AdminTimeWidget) class Meta: model = Appointment fields = ['user', 'task', 'date', 'time']
class PostAwardForm(forms.ModelForm): """ Create award form excluding user, content type and object id in form """ date = DateField(widget=forms.SelectDateWidget( years=range(datetime.date.today().year, 1800, -1))) class Meta: model = Award exclude = ('author', 'content_type', 'object_id')
class DayForm(forms.ModelForm): """ Form for Day. """ day = DateField(widget=HiddenInput(), ) father = CharField(required=False, ) brother = CharField(required=False, ) class Meta: model = Day fields = '__all__'
class MyModelForm(ModelForm): #on definit les formats de date acceptes my_date = DateField( input_formats=['%d/%m/%Y', '%Y-%m-%d'], # et on affecte le widget de date du site d'administration widget=AdminDateWidget(format='%d/%m/%Y')) class Meta: model = Shopping fields = ['my_date', 'date', 'supplier', 'meals']
class EventForm(forms.ModelForm): start_date = DateField() end_date = DateField() def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.fields['start_date'].label = 'Start Date' self.fields['end_date'].label = 'End Date' self.fields['title'].label = 'Title' self.fields['place'].label = 'Place' self.fields['description'].label = 'Description' self.fields['title'].widget.attrs.update({'class': 'uk-input'}) self.fields['place'].widget.attrs.update({'class': 'uk-input'}) self.fields['description'].widget.attrs.update({'class': 'uk-input'}) def clean(self): cleaned_data = super(EventForm, self).clean() start_date = cleaned_data.get('start_date') end_date = cleaned_data.get('end_date') if start_date and end_date: if start_date > end_date: msg = u"Start date must be before the end date" self._errors['start_date'] = self.error_class([msg]) return self.cleaned_data def save(self): instance = super(EventForm, self).save(commit=False) if not instance.slug: instance.slug = orig = slugify(instance.title) for x in itertools.count(1): if not Event.objects.filter(slug=instance.slug).exists(): break instance.slug = '%s-%d' % (orig, x) instance.save() return instance class Meta: model = Event fields = {'title', 'description', 'place'}
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance.pk: self.fields['file'].disabled = True self.fields['file'].widget = LinkWidget( link='file/{}/'.format(self.instance.pk), text=str(self.instance), ) self.fields['last_changed'] = DateField( widget=ConstantTextWidget(), required=False, disabled=True, label='Ostatnia zmiana', initial=self.instance.last_changed) else: self.fields['last_changed'] = DateField( widget=ConstantTextWidget(), required=False, disabled=True, label='Ostatnia zmiana')
class AppointmentForm(forms.ModelForm): """ create Appointment form """ user = forms.ModelChoiceField(queryset=User.objects.all(), widget=autocomplete.ModelSelect2(url='/appointments/country-autocomplete')) date = DateField(widget = AdminDateWidget()) time = forms.TimeField(widget= AdminTimeWidget) class Meta: model = Appointment fields = ['user', 'task', 'date', 'time']
class UsersJournalAccessForm(forms.Form): """ Form to give access for a journal to multiple users. """ expiration_date = DateField( required=True, widget=AdminDateWidget, ) bulk_upload_csv = forms.FileField( required=True, label=_("Users' CSV file"), help_text=_(".csv file with single column consists of only usernames"), )
class DeclaratieCotizatieSocialaForm(CrispyBaseModelForm, DocumentRegistraturaMixin): class Meta(object): model = DocumentCotizatieSociala fields = ['nume_parinte', 'motiv', 'este_valabil', 'fisier', 'registru', 'numar_inregistrare', 'data_inregistrare', 'valabilitate_start', 'valabilitate_end'] data_inregistrare = DateField(widget=BootstrapDateInput, label=u"Data înregistrare", required=False, help_text=u"Lasă gol pentru data de azi") valabilitate_start = DateField(widget=BootstrapDateInput, label=u"Valabiliă de la", required=True) valabilitate_end = DateField(widget=BootstrapDateInput, label=u"Valabilă până la", required=False) def __init__(self, *args, **kwargs): super(DeclaratieCotizatieSocialaForm, self).__init__(*args, **kwargs) self.fields['registru'].queryset = Registru.objects.filter(tip_registru__in=DocumentCotizatieSociala.registre_compatibile) def clean(self): self.check_inregistrare() if self.cleaned_data.get("valabilitate_end", None) is not None: if self.cleaned_data.get("valabilitate_end") <= self.cleaned_data.get("valabilitate_start"): raise ValidationError(u"Valabilitatea declarației nu poate să se termine înainte să înceapă!") return self.cleaned_data
class MarkForm(Form): id = CharField(label='ID', disabled=True) due_back = DateField(label='Renew_due_back', help_text='Input date between today and three weeks later.') def save(self, id): bookinstance = BookInstance.objects.get(id=id) bookinstance.due_back = self.data['due_back'] bookinstance.save() def clean_due_back(self): due_back = self.cleaned_data['due_back'] if date.fromisoformat(self.data['due_back']) < date.today() or date.fromisoformat(self.data['due_back']) > (date.today()+timedelta(days=21)): raise ValidationError('The date must be between today and three weeks later.') return due_back
def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs): errors = self.default_error_messages.copy() if 'error_messages' in kwargs: errors.update(kwargs['error_messages']) localize = kwargs.get('localize', False) fields = ( DateField(input_formats=input_date_formats, error_messages={'invalid': errors['invalid_date']}, localize=localize), TimeField(input_formats=input_time_formats, error_messages={'invalid': errors['invalid_time']}, localize=localize), TimeZoneFormField(error_messages={'invalid': errors['invalid_time']}, localize=localize, initial="Australia/Sydney"), ) super(SplitDateTimeTimeZoneField, self).__init__(fields, *args, **kwargs)
def add_fields(self, form, index): super(BillExpenseInlineFormset, self).add_fields(form, index) qs = Expense.objects.filter(lead=self.instance.lead, chargeable=True) qs_widget = qs.filter(billexpense__isnull=True ) # Don't propose an expense already billed form.fields["expense"] = ModelChoiceField( label=_("Expense"), required=False, widget=ExpenseChoices(queryset=qs_widget), queryset=qs) form.fields["expense_date"] = DateField( label=_("Expense date"), required=False, widget=DateInput(format="%d/%m/%Y"), input_formats=[ "%d/%m/%Y", ])
def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs): errors = self.default_error_messages.copy() if 'error_messages' in kwargs: errors.update(kwargs['error_messages']) localize = kwargs.get('localize', False) field = DateField(input_formats=input_date_formats, error_messages={'invalid': errors['invalid_date']}, localize=localize) fields = ( field, field, ) super(DateRangeField, self).__init__(fields, *args, **kwargs)
class DonorRegForm(forms.ModelForm): birth_date = DateField(widget=DateInput( attrs={'class': 'dateinput form-control'})) class Meta: model = models.Donor fields = ('name', 'phone', 'email', 'blood_group', 'birth_date', 'present_address', 'permanent_address') labels = { 'name': _('আপনার নাম'), 'phone': _('মোবাইল'), 'email': _('ইমেইল'), 'blood_group': _('রক্তের গ্রুপ'), 'birth_date': _('জন্ম তারিখ'), 'present_address': _('বর্তমান ঠিকানা'), 'permanent_address': _('স্থায়ী ঠিকানা'), }
def __init__(self, *args, **kwargs): input_formats = DATE_INPUT_FORMATS [translation.get_language() ] DateField.__init__(self, input_formats=input_formats, *args, **kwargs)
def manage_staff(request, task=None): """ Staff record management funtions """ response = {} success = False msg = '' if task == "add": form = add_staff_form() if request.method == "POST": form = add_staff_form(request.POST) from farmer.models import Position_Type if form.is_valid(): from farmer.models import Maritial_Status maritial_status_obj = Maritial_Status.objects.get(id=int(request.POST.get('maritial_status'))) user_obj = None from farmer.models import Salutations prefix_obj = Salutations.objects.get(id=int(request.POST.get('prefix'))) birth_date = ""; leaving_date = "" d = DateField() joining_date = None;leaving_date = None;birth_date = None if request.POST.get('date_of_joining'): joining_date = d.to_python(request.POST.get('date_of_joining','')) if request.POST.get('date_of_leaving'): leaving_date = d.to_python(request.POST.get('date_of_leaving','')) if request.POST.get('dob'): birth_date = d.to_python(request.POST.get('dob','')) from uuid import uuid4 uuid = uuid4().hex # generates unique ID person_obj = Person.objects.create(first_name=request.POST.get('first_name'),middle_name=request.POST.get('middle_name'),Last_name=request.POST.get('Last_name'),\ prefix=prefix_obj, farmer_id=request.POST.get('farmer_id'),gender=request.POST.get('gender'),\ dob= birth_date, maritial_status=maritial_status_obj, uuid=uuid, added_by=request.user) from django.template.defaultfilters import slugify slug = slugify(str(person_obj.id)+str(person_obj.first_name)) person_obj.slug = slug person_obj.save() staff_type_obj = Staff_Type.objects.get(id=int(request.POST.get('staff_type'))) department_obj = None;designation_obj = None if request.POST.get('department'): department_obj = Department.objects.get(id=int(request.POST.get('department'))) if request.POST.get('designation'): designation_obj = Designation.objects.get(id=int(request.POST.get('designation'))) staff_obj = Staff.objects.create(staff_type = staff_type_obj, personal_info = person_obj, \ department = department_obj, designation=designation_obj, \ date_of_joining = joining_date, date_of_leaving = leaving_date, \ photo = request.POST.get('photo',''),work_experience = request.POST.get('work_experience','') ) if request.POST.getlist('skills'): sk_list = [int(i) for i in request.POST.getlist('skills')] for i in sk_list: sk_obj = Skills.objects.get(id= i) staff_obj.skills.add(sk_obj) staff_obj.save() from farmer.models import Educational_Qualification if request.POST.getlist('qualification'): sk_list = [int(i) for i in request.POST.getlist('qualification')] for i in sk_list: sk_obj = Educational_Qualification.objects.get(id= i) staff_obj.qualification.add(sk_obj) staff_obj.save() request.session['staff_id'] = staff_obj.id form = add_staff_address_form(staff_obj.id) added = True msg = "Staff added successfully" success = True #return HttpResponseRedirect('/hr/Staff-Address/add/') #return render(request, 'hrmanagement/add_edit_staff_address.html', locals()) else: msg = "Error Occurred" response = {'msg':msg, 'success':success} return HttpResponse(json.dumps(response), mimetype = "application/json") elif task =="edit": id_edit = request.GET.get('id_edit') staff_obj = Staff.objects.get(id=int(id_edit)) person_obj = Person.objects.get(id = staff_obj.personal_info.id) form = add_staff_form(initial = {'prefix':person_obj.prefix, 'first_name':person_obj.first_name, \ 'middle_name':person_obj.middle_name, 'Last_name':person_obj.Last_name, \ 'farmer_id':person_obj.farmer_id, \ 'gender':person_obj.gender, 'dob':person_obj.dob, 'maritial_status':person_obj.maritial_status, 'designation':staff_obj.designation, \ 'staff_type':staff_obj.staff_type, 'personal_info':staff_obj.personal_info, 'skills':staff_obj.skills.all(), 'department':staff_obj.department, \ 'qualification':staff_obj.qualification.all(), 'date_of_joining':staff_obj.date_of_joining, 'date_of_leaving':staff_obj.date_of_leaving, \ 'photo':staff_obj.photo, 'work_experience':staff_obj.work_experience}) if request.method == 'POST': form = add_staff_form(request.POST, request.FILES) if form.is_valid(): from farmer.models import Position_Type, Maritial_Status, Educational_Qualification, Salutations maritial_status_obj = Maritial_Status.objects.get(id=int(request.POST.get('maritial_status'))) prefix_obj = Salutations.objects.get(id=int(request.POST.get('prefix'))) d = DateField() person_obj.prefix = prefix_obj;person_obj.first_name = request.POST.get('first_name','') person_obj.middle_name = request.POST.get('middle_name','');person_obj.Last_name = request.POST.get('Last_name','') person_obj.farmer_id = request.POST.get('farmer_id','') person_obj.gender = request.POST.get('gender','') if request.POST.get('dob'): birth_date = d.to_python(request.POST.get('dob','')) person_obj.dob = birth_date person_obj.maritial_status = maritial_status_obj;person_obj.uuid = request.POST.get('uuid','') if request.POST.get('added_by'): user_obj = User.objects.get(id=int(request.POST.get('added_by'))) person_obj.added_by = user_obj person_obj.save() staff_type_obj = Staff_Type.objects.get(id=int(request.POST.get('staff_type'))) department_obj = None;designation_obj = None if request.POST.get('department'): department_obj = Department.objects.get(id=int(request.POST.get('department'))) if request.POST.get('designation'): designation_obj = Designation.objects.get(id=int(request.POST.get('designation'))) staff_obj.staff_type = staff_type_obj;staff_obj.personal_info = person_obj staff_obj.department = department_obj staff_obj.designation = designation_obj if request.POST.get('date_of_joining'): joining_date = d.to_python(request.POST.get('date_of_joining','')) staff_obj.date_of_joining = joining_date if request.POST.get('date_of_leaving'): leaving_date = d.to_python(request.POST.get('date_of_leaving','')) staff_obj.date_of_leaving = leaving_date staff_obj.photo = request.POST.get('photo','') staff_obj.work_experience = request.POST.get('work_experience','') staff_obj.save() if request.POST.getlist('skills'): sk_list = [int(i) for i in request.POST.getlist('skills')] for i in sk_list: sk_obj = Skills.objects.get(id= i) staff_obj.skills.add(sk_obj) staff_obj.save() if request.POST.getlist('qualification'): sk_list = [int(i) for i in request.POST.getlist('qualification')] for i in sk_list: sk_obj = Educational_Qualification.objects.get(id= i) staff_obj.qualification.add(sk_obj) staff_obj.save() edit_done = True msg = "Staff edited successfully" success = True else: msg = "Invalid Form" response = {'msg':msg, 'success':success} return HttpResponse(json.dumps(response), mimetype = "application/json") elif task =="delete": id_del = request.GET.get('id_del') staff = Staff.objects.get(id = id_del) staff.active = 0 staff.save() msg = "Staff deactivated successfully" success = True response = {'msg':msg, 'success':success} return HttpResponse(json.dumps(response), mimetype = "application/json") elif task == "active": active = request.GET.get('active') staff = Staff.objects.get(id = active) staff.active = 2 staff.save() msg = "Staff activated successfully" success = True response = {'msg':msg, 'success':success} return HttpResponse(json.dumps(response), mimetype = "application/json") return render_to_response('hrmanagement/add_edit_staff.html', locals(), context_instance = RequestContext(request))
def add_fees_schedule(request, fee_id): ''' add a arecord for fee schedule ''' form = FeeScheduleForm() ins_obj = None try: ins_id = request.session['ins_id'] ins_obj = Institution.objects.get(pk = ins_id) # put this in try...catch except Exception: return HttpResponse('<html><body><h3>Broken Session</h3></body></html' '>') fee_obj = Fee.objects.get(id=fee_id) record_added = False errors = {} if request.method == 'POST': form = FeeScheduleForm(request.POST) if form.is_valid(): sh_amount = int(request.POST.get('fees_amount')) fee_amount = fee_obj.amount s_date = request.POST.get('start_date') from django.forms.fields import DateField date1 = DateField() start_date = date1.to_python(s_date) fee_obj = Fee.objects.get(id = fee_id) max_date = get_date_for_add(fee_obj) amount = get_basic_amount(fee_obj) if max_date: if max_date >= start_date: errors['start_date_greater'] = \ ('Start date should not be greater than previous ' 'installment\'s end date(' + str(max_date) + ') ') return render(request, 'add_edit_fees_schedule.html', locals()) if sh_amount > amount: errors['amount_greater_than_basic_amount'] = \ ('Fees Amount should not be greater than ' + str(amount) + '(basic_amount - installment_amount)') return render(request, 'add_edit_fees_schedule.html', locals()) else: form1 = form.save(commit = False) form1.fee = fee_obj form1.created_by = request.user form1.institution = ins_obj form1.save() record_added = True return render(request, 'add_edit_fees_schedule.html', locals()) else: errors['invalid_datails'] = 'Please enter valid data' return render(request, 'add_edit_fees_schedule.html', locals()) else: form = FeeScheduleForm() fee_sh_list = Fees_schedule.objects.filter(fee = fee_obj , is_active = True) if fee_obj.payment_type == "recursive": remaining_installments = fee_obj.installments - fee_sh_list.count() if remaining_installments == 1: amount = 0 for i in fee_sh_list: amount = amount + i.fees_amount remaining_amount = fee_obj.amount - amount if remaining_installments == fee_obj.installments: installment_no = 1 return render(request, 'add_edit_fees_schedule.html', locals())