Render a CheckBoxSelectMultiple form using the data present in Database. [initial value is a queryset from DB]
Asked Answered
T

1

2

I have a form called DemoForm which is related to model Demo

class Demo(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    ans = models.CharField(max_length=1024)

and the form for this is

class DemoForm(forms.ModelForm):
    class Meta:
        model = Demo
        exclude = ('user',)
        widgets = {'ans': forms.CheckboxSelectMultiple}

I want to render this form using a queryset I have tried different approaches like

form = DemoForm(initial=Love.objects.filter(user=request.user))


<form=GoodForm()  
form.fields["ans"].queryset = Love.objects.filter(user=request.user) >


form=DemoForm(instance=Love.objects.filter(user=request.user)


form=DemoForm(instance=request.user.love_set.all())

Sometimes it is showing no _Meta present and when I use initial, it shows the expected length 2 got 1 (got 3)

NOTE- The Love model is related to user in the same way as the Demo is related to user using ForeignKey. Means the Love model is a copy of Demo model. So the query returns nested objects

Topper answered 11/9, 2019 at 7:34 Comment(6)
Instead of customizing the widget you can try the ModelMultipleChoiceField: docs.djangoproject.com/en/2.2/ref/forms/fields/… That could do the trick for you :)Sedgewake
and how can I pre-populate it? DO I have to convert it to list or the current query is okay?Topper
@Sedgewake and how'd I query it? My implementation requires request.Topper
You can simply pass a queryset. If you need it to change depending on the request you need to override the __init__ method of the form to change the queryset on the flySedgewake
can You please take a look at this? This the thing I implemented. But there's a new problem associated with it.Topper
Charfield is saved in DB. I want to render the char fields as the options.Topper
N
0

You can populate the charfield data with multiselect checkbox by using MultipleChoiceField with CheckboxSelectMultiple widget, and override choice field in init mwthod as per the requirement.

class DemoForm(ModelForm):
   ans = MultipleChoiceField(widget=CheckboxSelectMultiple)

class Meta:
    model = Demo
    exclude = ('user',)

def __init__(self, *args, user=None, **kwargs):
    super(DemoForm, self).__init__(*args, **kwargs)

    if user:
        # Assuming Love model has a CharField named 'ans'
        love_objects = Love.objects.filter(user=user)
        choices = [(obj.ans, obj.ans) for obj in love_objects]
        self.fields['ans'].choices = choices

And you can simple use the form in your views.py, For FBV

def demo_form_view(request):
   if request.method == 'POST':
       form = DemoForm(request.POST, user=request.user)
       if form.is_valid():
           # Do something with the valid form data
           # For example, save the form
   else:
       form = DemoForm(user=request.user)

   return render(request, 'demo_form.html', {'form': form})
Nelle answered 17/11, 2023 at 7:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.