pythondjangoformstemplatesmanytomanyfield

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


I couldn't get my input data to many-to-many field data via the HTML form. How to solve this?

This is my code:

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

Solution

  • You need to handle the case where the request method is "GET" so that you can render the form without any validation being run. If the user then submits the form as a "POST" you should run the 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})
    

    You need to also wrap the form in a form tag with the method set to "post"

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