How to render a CheckboxSelectMultiple form using forms.ModeForm that uses data from DB as :-> SomeModel.objects.filter(user=request.user)
Asked Answered
B

0

0

Please take a look at the code and if you can not comprehend what is going on, I am explaining it in the end

I have a model named Good

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

and a form

class GoodForm(forms.ModelForm):
    def __init__(self, request=None, *args, **kwargs):
        super(GoodForm, self).__init__(*args, **kwargs)
        self.input_list = request.user.love_set.all()
        self.fields['ans'] = forms.MultipleChoiceField(
            label="",
            choices=[(c.ans, c.ans) for c in self.input_list],
            widget=forms.CheckboxSelectMultiple
        )

    class Meta:
        model = Good
        fields = ('ans',)

and the view for this is

@login_required
def good_form(request):
    form = GoodForm(request)
    if request.method == 'POST':
        form = GoodForm(request, request.POST)
        if form.is_valid():
            answer = form.save(commit=False)  #problem is here
            answer.user = request.user
            answer.save()
            return redirect('app-2:money')

        else:
            form = GoodForm(request)
            return render(request, 'purpose_using_DB/good_at_form.html', {'form': form, 'error': 'Error occured'})

    else:
        return render(request, 'purpose_using_DB/good_at_form.html', {'form': form})

So what I want to do here is :-

  1. I want to render a form called GoodForm which is a ModelForm related to the model Good.

  2. The form is rendered as the options presented already in the table called Love.

  3. query Love.objects.filter(user=user) is equivalent to request.user.love_set.all() (in some sense if not completely)

  4. I want users to select the choices that were present already and click submit.

  5. At successful submit, I want the data to be saved inside ans in the Good table that mapped to user using ForeignKey

My questions are:

  1. How can I save the data from form in the DB? It is saving the selected ChechBoxes as a List. For example, IF I selected 1,2,3 and make a query against the user, it shows me ['1','2','3']

  2. Can I pre-populate the form using the data from Love Form inside views by using initial=some_list/query (or without the use of passing request object and without using the constructor)?

Any of the answers would and its solution would do. Much appreciated. Thank you in advance.

Backbreaking answered 11/9, 2019 at 18:43 Comment(6)
Did you makemigrations and migrate? And did that show you the table being created? If you did, have you added your app to the INSTALLED_APPS?Genoese
oh man!! so silly of me. thanks buddy !!but there's a new problem now. It is saving the values so weirdly. when I save the values in DB and fetch again using request.user.good_set.all() , it shows me a list of values selected. Means when I select the values in the GoodForm and save them, they get saved like a list. for example if I select 1,2,3 and save, It;ll get saved like ['1','2','3'] in DBBackbreaking
I don’t understand how you want the choices to be saved. ans is a CharField and in your form a multiple choice field which returns a list. How do you want to save the list?Genoese
If I check the box in front of answer one, answer two and answer three, I want them to be saved as seperate enteries. in DB than to save them as one entry ['answer one', answer two', 'answer three']. Anyways I found out a way. I have converted it to simple form and then saving the results by request.POST.getlist('ans') and then creating objects and saving them in DB using a loop. But I can learn more if you tell me how to do it using ModelFormsBackbreaking
There’s not much point in using a model form in this case because the form’s ans field isn’t actually mapping the model’s ans field. A ModelForm is for creating/updating one instance, not multiple instances. You could use modelformset so you have multiple forms, one for each instance, but because of the way the user selects the answers it’s also more work than the simple form.Genoese
Got it brother. Thanks for helping me out. Much appreciated.Backbreaking

© 2022 - 2024 — McMap. All rights reserved.