G
G
German Jet2016-06-01 17:38:46
Django
German Jet, 2016-06-01 17:38:46

How to save a formset in Django?

In general, there are users (contractors), each user has several objects (roads).
For each object, they fill out an electronic work log of this kind:
8891628981f847b1b56015bf19b14f3e.JPG
I got confused with the formset, this is the first time I deal with them, here are the views:

def create(request):
  JournalFormSet = formset_factory(JournalForm)
        if request.method == 'POST':
            formset = JournalFormSet(request.POST)
            if formset.is_valid():
        	for form in formset:
        		if form.is_valid():
                rec = Journal(
                	id=form.cleaned_data['id'], 
                    work_type_id = 1,
                    count_all = form.cleaned_data['count_all'],
                    count_current = form.cleaned_data['count_current'],
                    val_all = form.cleaned_data['val_all'], 
                    val_current = form.cleaned_data['val_current'],
                    position = form.cleaned_data['position'])
                rec.save()
            return HttpResponseRedirect('oad/create/')
    else:        
        rec = Journal.objects.get(pk=1) 
        form = JournalForm(initial={
                    'count_all': rec.count_all, 
                    'count_current': rec.count_current, 
                    'val_all': rec.val_all, 
                    'val_current': rec.val_current, 
                    'position': rec.position}) 
    return render(request, 'oad/create.html', {'form': form, 'rec': rec})

Without formset, as I understand it, there is no way around it. If there are options, please advise.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question