如何在 Django 中的 HTML 表单上显示表单中的多对多字段

How to show many-to-many fields from form on on HTML form in Django

我无法通过 HTML 表单将输入数据转换为多对多字段数据。如何解决?

这是我的代码:

models.py

class SetStaffSchedule(models.Model):  # generated work for staffs by admins
    schedule = models.ManyToManyField('Staff')
    shift = models.DateTimeField("Shift")
    detail = models.TextField("Task Detail", max_length=200)

    def __str__(self):
        return self.shift

    def __str__(self):
        return self.detail

forms.py

from django import forms
from attendance.models import SetStaffSchedule, Staff


class SetStaffScheduleForm(forms.ModelForm):

    class Meta:
        model = SetStaffSchedule
        fields = ['schedule','shift', 'detail']

views.py

    def schedules(request):  # getting schedules for staffs' work
    all_schedules = SetStaffSchedule.objects.all()

    context = {
        'all_schedules': all_schedules
    }
    return render(request, 'getschedule.html', context)


def post(request):  # posting schedules for staffs' work
    form = SetStaffScheduleForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save();
        return redirect ('schedules')
    return render(request, 'post_schedules.html', {"form": form})

post_schedules.html

    {% csrf_token %}
    {{ form.as_p }}

您需要处理请求方法为 "GET" 的情况,以便您可以在不进行任何验证的情况下呈现表单 运行。如果用户随后将表单作为 "POST" 提交,您应该 运行 validation/saving

def create_staff_schedule(request):  # posting schedules for staffs' work
    if request.method == 'GET':
        form = SetStaffScheduleForm()
    else:  #  POST
        form = SetStaffScheduleForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('schedules')
    return render(request, 'post_schedules.html', {"form": form})

您还需要将表单包装在 form 标记中,并将方法设置为 "post"

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
</form>