vendredi 29 mai 2015

Formset can_delete function don't work with default values

When I set a default value for integer in my model class, my formset row can't be deleted until i fill all the fields in my empty extra row ( i understood that it is because the is_valid() works only if extra form is empty or is filled with everything). If I fill everything in my extra fields and choose the row to be deleted it works perfectly fine

I want to make a fields called hours,days,calendar_end readonly, so that they will be calculated using data from other fields and then showed in my formset.(not dynamically, but after adding a new row)

I have a couple of problems here:

If i don't use default values in my class, the formset won't allow me to add a new form without filling hours,days,calendar_end fields

If i use the default values for them, the can_delete function don't work until i complete all fields on my extra field

I hope it can be done without using the redirection to the other page

here's my view function.

def calend_graph_create(request):

AuthorFormSet = modelformset_factory(CalendGraph, fields=('project_name','work_name','work_amount','unit_name','employee_name','hours','days','approve_need','approve_time','calendar_start','calendar_end',),extra =1, can_delete=True)

for form in AuthorFormSet(): 
    form.fields['hours'].widget.attrs['readonly'] = True #can i do that?

if request.method == 'POST':
    if formset.is_valid():
        formset.save()
        return HttpResponseRedirect("/calend-graph-create/")

    args={}
    args.update(csrf(request))
    args['formset'] = formset
    return render_to_response("tasks/calend-graph-create.html",args)

else:
    formset = AuthorFormSet()

#starting to calculate hours, days, and calendar end
entries= CalendGraph.objects.all()
app_entries= Approve.objects.all()
for each in entries:
    temp=0
    if each.approve_need == True:
        for time in app_entries:
            if each.work_name == time.name_ap:
                temp=temp+ time.time_ap
                each.approve_time=time.time_ap
    temp=temp+each.work_amount
    each.hours=temp
    each.days=temp / 8
    each.calendar_end=each.calendar_start + timedelta(days=each.days)

for each in entries:
    each.save()


args={}
args.update(csrf(request))
args['formset'] = formset
return render_to_response("tasks/calend-graph-create.html",args)

Aucun commentaire:

Enregistrer un commentaire