Django基于类的CreateView中的Formset [英] Formset in Django Classbased CreateView

查看:84
本文介绍了Django基于类的CreateView中的Formset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模型

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)

视图

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 ,

注意:我的JS不好,所以我想要一个不使用JS的解决方案

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

推荐答案

视图



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



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 %}

这篇关于Django基于类的CreateView中的Formset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆