vendredi 2 juillet 2021

Django can't able to save multichoice field (checkbox) data in database

Am trying to save data from multi choice field to database but it doesn't get saved in database instead it shows all many to many relationship data.

Models.py

class masterList(models.Model):
    mastername=models.CharField(max_length=150)
    unit=models.ForeignKey(unit, on_delete=models.CASCADE)
    status =models.IntegerField()

    def __str__(self):
        return self.mastername


class subCategory(models.Model):
    sub_category_name=models.CharField(max_length=200)
    category=models.ForeignKey(category,on_delete=models.CASCADE)
    masters= models.ManyToManyField(masterList)
    status=models.IntegerField()

    def __str__(self):
        return str(self.sub_category_name)

Forms.py

class subCategoryForm(forms.ModelForm):
    
the_choices = forms.ModelMultipleChoiceField(queryset=masterList.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
    class Meta:
        model=subCategory
        fields=[
            "category",
            "sub_category_name",
            "status",
        ]

Views.py

def add_sub_category(request):
    context={}
    form = subCategoryForm(request.POST)
    if form.is_valid():
        form.save()
    context = {'form':form}
    return render(request,'add_sub_category.html',context)

I think form.save_m2m() will do this job but i couldn't understand how it works. Thanks in advance :)




Aucun commentaire:

Enregistrer un commentaire