如何在Django中的编辑表单中的CheckboxSelectMultiple字段中保存选中的复选框

时间:2017-07-25 19:32:57

标签: python django forms

我为模型创建了一个表单,现在我想为该模型创建一个更新表单,但是我遇到了CheckboxSelectMultiple字段的问题。这是我的代码:

choices.py

FREQUENCY_CHOICES = (('sunday', 'Sunday'), ('monday', 'Monday'), ('tuesday', 'Tuesday'), ('wednesday', 'Wednesday'), ('thursday', 'Thursday'), ('friday', 'Friday'), ('saturday', 'Saturday'))

models.py

class Schedules(models.Model):
    course_name = models.ForeignKey(Course)
    location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield')
    room = models.CharField(max_length=128, choices=ROOM_CHOICES, default='A')
    start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
    start_time = models.CharField(max_length=128, choices=START_TIME_CHOICES, default='eight-thirty am')
    end_time = models.CharField(max_length=128, choices=END_TIME_CHOICES, default='eight-thirty am')
    instructor = models.ForeignKey(Instructor)
    total_hours = models.CharField(max_length=128, choices=TOTAL_HOURS_CHOICES, default='six')
    # Relevant code here
    frequency = models.CharField(max_length=128)
    status = models.CharField(max_length=128, choices=STATUS_CHOICES)
    interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='1 day')
    initiated_by = models.CharField(max_length=128, null=True)
    schedule_id = models.IntegerField(default=0)

forms.py

class ScheduleForm(forms.ModelForm):
    course_name = CourseChoiceField(queryset=Course.objects.filter(status=True), label="Course Name", widget=forms.Select(attrs={'class': 'form-control'}))
    location = forms.ChoiceField(choices=LOCATION_CHOICES, initial='south_plainfield', label="Location", widget=forms.Select(attrs={'class': 'form-control'}))
    room = forms.ChoiceField(choices=ROOM_CHOICES, initial='A', label="Room", widget=forms.Select(attrs={'class': 'form-control'}))
    start_date = forms.DateField(input_formats=['%m/%d/%Y'], label="Start Date", widget=DateInput(format='%m/%d/%Y'), help_text="MM/DD/YYYY")
    start_time = forms.ChoiceField(choices=START_TIME_CHOICES, initial='eight-thirty am', label="Start Time", widget=forms.Select(attrs={'class': 'form-control'}))
    interval = forms.ChoiceField(choices=INTERVAL_CHOICES, initial='1 day', label="Interval", widget=forms.Select(attrs={'class': 'form-control'}))
    # hours_per_class = forms.ChoiceField(choices=HOURS_PER_CLASS_CHOICES, initial='four_and_half', label="Hours Per Class", widget=forms.Select(attrs={'class': 'form-control'}))
    total_hours = forms.ChoiceField(choices=TOTAL_HOURS_CHOICES, initial='six', label="Total Hours", widget=forms.Select(attrs={'class': 'form-control'}))
    instructor = InstructorChoiceField(queryset=Instructor.objects.all(), label="Instructor", widget=forms.Select(attrs={'class': 'form-control'}))
    end_time = forms.ChoiceField(choices=END_TIME_CHOICES, initial='eight-thirty am', label="End Time", widget=forms.Select(attrs={'class': 'form-control'}))
    # Relevant code here
    frequency = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=FREQUENCY_CHOICES, label="Frequency", help_text="Please select at least one")
    status = forms.ChoiceField(widget=forms.RadioSelect, choices=STATUS_CHOICES, label="Status")

    class Meta:
        model = Schedules
        fields = ('course_name', 'instructor', 'location', 'room', 'start_date', 'start_time', 'end_time', 'interval', 'total_hours', 'frequency', 'status',)

views.py

def update_Schedule(request, pk):
    schedule = get_object_or_404(Schedules, pk=pk)
    form = ScheduleForm(request.POST or None, instance=schedule)
    if form.is_valid():
        form.save()
        return redirect('schedule_list')
    return render(request, "schedule/update_schedule.html", {'form':form})

update_schedule.html

{% block main_content %}
<style>
    ul {
        list-style: none;
    }
</style>
<h2>Update Course Schedule</h2>
<br>
<form id="update_schedule_form" method="post" action="">
    {% csrf_token %}
    <div class="row">
        {% for field in form %}
            <div class="col-gl-4 col-md-4">
                <div class="form-group">
                    <strong>{{ field.errors }}</strong>
                    {{ field.label_tag }}
                    {{ field.help_text }}
                    <br>
                    {{ field }}
                    <script></script>
                </div>
            </div>
        {% endfor %}
    </div>
    <button type="submit" name="submit">Update Schedule</button>
</form>
{% endblock %}

由于某些原因,在转到实例的更新表单时,频率字段中检查的选项不会保持检查状态,即使其他字段也是如此。我知道这是唯一接受多种选择的领域。奇怪的是,我制作的表格将频率作为数组返回。我知道之前已经问过,但是没有得到答案,所以我希望有人可以帮我解决这个难题。感谢。

1 个答案:

答案 0 :(得分:0)

我找到了答案。显然,我应该将模型中的字段更改为MultiSelectField。