mercredi 26 juillet 2017

CheckBox Form Validation and Saving in the Views

I am new to django forms .. i am trying to save some related fields using a check box widget .. we have a manger and he want to choose team members using a check box of all available members, but the return value of this checkbox is always an empty dictionary

forms.py

class AddAgentStaffForm(forms.ModelForm):

    class Meta:
        model = Hierarchy
        fields = ('agent',)
        widgets = {'agent': forms.CheckboxSelectMultiple}

    def __init__(self, agent, **kwargs):
        super(AddAgentStaffForm, self).__init__(**kwargs)

        self.fields['agent'].queryset = Agent.objects.filter(
            company=agent.company).exclude(
            agent__agent=agent).exclude(
            id=agent.id)

    def clean(self):
        agent = super(AddAgentStaffForm, self).clean()
        print agent # i got an empty dictionary here
        # some validation code 

so my question is what is the correct way to do this form .. and how to save it in the views

here is my attempt to save one object .. what should i add to it to work for CheckBox

view.py

def add_staff(request, pk):
    agent = Agent.objects.get(id=pk)
    heads = Hierarchy.objects.filter(agent=agent)
    staff = Hierarchy.objects.filter(head=agent)

    if request.method == "POST":
        staff_form = AddAgentStaffForm(agent=agent, data=request.POST)

        if staff_form.is_valid():
            obj = staff_form.save(commit=False)
            obj.head = agent
            obj.company = agent.company
            staff_form.save()
    else:
        staff_form = AddAgentStaffForm(agent=agent)

    context = {
        'agent': agent,
        'heads': heads,
        'staff': staff,
        'staff_form': staff_form}
    return render(request, 'hierarchy/add_staff.html', context=context)




Aucun commentaire:

Enregistrer un commentaire