问题
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 :-
I want to render a form called
GoodForm
which is aModelForm
related to the modelGood
.The form is rendered as the options presented already in the table called
Love
.query
Love.objects.filter(user=user)
is equivalent torequest.user.love_set.all()
(in some sense if not completely)I want users to select the choices that were present already and click submit.
At successful submit, I want the data to be saved inside
ans
in theGood
table that mapped to user usingForeignKey
My questions are:
How can I save the data from form in the DB? It is saving the selected
ChechBoxes
as aList
. For example, IF I selected1,2,3
and make a query against the user, it shows me['1','2','3']
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