型号
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'
NB:我的JS不好,所以我想要一个不使用JS的解决方案
答案 0 :(得分:1)
class MyForm(ModelForm):
class Meta:
model = Timetable
fields = ['day','start','end','period',]
from django.forms import formset_factory
class YourView(CreateView):
form = formset_factory(MyForm)
model = Timetable
success_url ="Your success url"
template_name = "your template"
<form method="post">{% csrf_token %}
<fieldset>
<div class="row">
<div class="form-group col-lg-12">
{{ form.management_form }}
{% for contact in form %}
<div class="link-formset">
{{ contact.as_p }}
</div>
{% endfor %}
<button class="user-sent" type="submit" value="Send"> Send</button>
</div>
</div>
</fieldset>
<script src="{% static 'forms/jquery.formset.js' %}"></script>
<script>
$('.link-formset').formset({
addText: '<i class="fa fa-plus"></i> Add User',
deleteText: '<i class="fa fa-trash-o"></i>Remove'
});
</script>
</form>
答案 1 :(得分:0)
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/')
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,)
{% csrf_token %}
{{ day_form }} <br>
{{ formset.management_form }}
{% for form in formset %}
{{ form }}<br><br>
{% endfor %}