Reputation: 33
I am trying to save the data from a form to the session but it seems that it's not the right datatype.
I have tried model_to_dict and cleaned as it is working fine for my other form that takes similar data in entry but it didn't work.
class ActivitiesForm(forms.Form):
activity = forms.ModelChoiceField(label='Select your activities', queryset=Activity.objects.all())
target_group = forms.ChoiceField(label='Who is the report destined to?', choices=OutputOutcomeImpact.TARGETGROUP)
class Activities(TemplateView):
template_name = 'blog/activities.html'
context = {'title': 'Activities selection page'}
def get(self, request):
form_act = ActivitiesForm()
form_act.fields['activity'].queryset = Activity.objects.filter(categories__sectors__name=request.session['sector']['name'])
self.context['form_act']=form_act
return render(request,self.template_name, self.context)
def post(self,request):
form_act = ActivitiesForm(request.POST)
if form_act.is_valid():
print(form_act.is_valid(),form_act.cleaned_data['activity'],type(form_act.cleaned_data['activity']),type(model_to_dict(form_act.cleaned_data['activity'])),form_act['activity'])
request.session['activity'] = model_to_dict(form_act.cleaned_data['activity'])
request.session['target_group'] = model_to_dict(form_act.cleaned_data['target_group'])
return redirect('/about', self.context)
Here's the type of data that I get from the print and the error:
True Municipal waste incineration <class 'blog.models.Activity'> <class 'dict'> <select name="activity" required id="id_activity">
<option value="">---------</option>
<option value="Municipal waste incineration" selected>Municipal waste incineration</option>
<option value="Plastic upcycling">Plastic upcycling</option>
</select>
Internal Server Error: /activities/
.
.
.
AttributeError: 'str' object has no attribute '_meta'
Hope it helps. Thanks.
Upvotes: 0
Views: 28
Reputation: 51988
Probably the problem is with target_group
. Its value should be string because it is coming from ChoiceField
. So you don't need to use model_to_dict
for that.
request.session['target_group'] = form_act.cleaned_data['target_group']
Upvotes: 1