Issue
Getting this KeyError on form POST action. What I'm trying to do here is my users have lists and in those lists they can add number values. Here I'm trying to call for all of some specific users lists to my form where user can choose which for of his/hers list they want to add the value to.
form:
class data_form(forms.Form):
selection = forms.ModelChoiceField(queryset=None)
data = forms.IntegerField()
def __init__(self, *args, **kwargs):
user = kwargs.pop("user")
super(data_form, self).__init__(*args, **kwargs)
self.fields['selection'].queryset = List.objects.filter(user=user)
Views, first handles main page and second is for adding the data
@login_required
def app(request):
form = list_form
form2 = data_form(user=request.user)
user = request.user.pk
user_lists = List.objects.filter(user=user)
list_data = {}
for list in user_lists:
list_data[list.name] = DataItem.objects.filter(list=list)
context = {'user_lists': user_lists, 'form': form, 'form2': form2, 'list_data': list_data}
return render(request, 'FitApp/app.html', context)
@require_POST
def addData(request):
form = data_form(request.POST)
if form.is_valid():
new_data = DataItem(data=request.POST['data'], list=List.objects.get(id=request.POST['selection']))
new_data.save()
return redirect('/app/')
Solution
You forgot to pass the user instance to your form. Also you shouldn't be accessing the POST data directly, use the form cleaned_data. And since selection is a ModelChoiceField you get the instance selected already not the id, so no need make a query.
@require_POST
def addData(request):
form = data_form(request.POST, user=request.user)
if form.is_valid():
cd = form.cleaned_data
new_data = DataItem(data=cd['data'], list=cd['selection'])
new_data.save()
return redirect('/app/')
Answered By - p14z
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.