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

对着背影说爱祢 提交于 2019-12-11 16:46:44

问题


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.

来源:https://stackoverflow.com/questions/57895082/how-to-render-a-checkboxselectmultiple-form-using-forms-modeform-that-uses-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!