Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formset in Django Classbased CreateView

Model

class Timetable(models.Model):
    day = models.CharField(max_length=9,choices=timetable_choices)
    start = models.IntegerField()
    end = models.IntegerField()
    period = models.CharField(max_length=12)

Views

class Timetableadding(CreateView):
    model =  Timetable
    fields = ['day','period','start' ,'end']
    success_url = '/dashboard'

What I need is to process a view similar to following image , enter image description here

NB: I am not good in js so i want a solution without the use of JS

like image 200
Joel Deleep Avatar asked Mar 04 '23 00:03

Joel Deleep


1 Answers

Views

class Timetableadding(CreateView):
    model =  Timetable
    success_url = '/dashboard/'
    form_class = Timetableform
    template_name = 'form.html'


    def get_context_data(self, **kwargs):
        context = super(Timetableadding, self).get_context_data(**kwargs)
        context['formset'] = TimetableFormSet(queryset=Timetable.objects.none())
        context['day_form'] = DayForm()
        return context

    def post(self, request, *args, **kwargs):
        formset = TimetableFormSet(request.POST)
        day_form = DayForm(data=request.POST)
        if formset.is_valid() and day_form.is_valid():
            return self.form_valid(formset,day_form)

    def form_valid(self, formset,day_form):
        day = day_form.cleaned_data['day']
        instances = formset.save(commit=False)
        for instance in instances:
            instance.day = day
            instance.save()
        return HttpResponseRedirect('/dashboard/')

Forms

class DayForm(Form):
    day = ModelChoiceField(queryset=Day.objects.all())


class Timetableform(ModelForm):
    class Meta:
        model = Timetable
        fields = ( 'day','start', 'end', 'period')

TimetableFormSet = modelformset_factory(Timetable, fields=('start', 'end', 'period'),extra=8,)

Template

{% csrf_token %}
{{ day_form }} <br>
{{ formset.management_form }}
{% for form in formset %}
{{ form }}<br><br>
{% endfor %}
like image 86
Joel Deleep Avatar answered Mar 17 '23 06:03

Joel Deleep