This is my form which uses a model called modelQuizQuestion
. This model has a char
field in it. Now everything works fine if the char field in that model does not have a quote in it. Otherwise I get an exception on form.is_valid()
which is
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
class DynamicQuizForm(forms.Form):
def __init__(self, patient, *args, **kwargs):
super(DynamicQuizForm, self).__init__(*args, **kwargs)
question_qset = modelQuizQuestion.objects.filter(patient=patient)
counter = 0
for question in question_qset:
counter+=1
#Construct choices
choice_qset = modelQuizChoice.objects.filter(question=question)
main_choices = []
for choice in choice_qset:
small_choices = []
small_choices.append(choice.choice)
small_choices.append(choice.choice)
main_choices.append(small_choices)
self.fields[question.question] = forms.ChoiceField(choices=main_choices, widget=forms.RadioSelect(),)
and this is how I am using it
if request.method == "POST":
quizForm = DynamicQuizForm(patient=patient_qset, data=request.POST)
if quizForm.is_valid(): #<------------ gives exception here
.....
Any suggestions why this might be happening. I looked at these two links link1 and link2
However it seems like it is a unicode issue and the answers recommend to use decode
instead of str
. Howeever in my code I am not using str
anywhere
Update
I believe the reason for this issue is because of the statement
self.fields[question.question] = forms.ChoiceField(choices=main_choices, widget=forms.RadioSelect(),)
and this only occurs if question.question
has a string with apostrophe in it.
This is the question model
class modelQuizQuestion(models.Model):
patient = models.ManyToManyField(modelPatient,default=None,blank=True)
question = models.CharField(max_length=800, unique=True)
class Meta:
verbose_name_plural = "Questions in the Quizes"
def __unicode__(self):
return "Question : " +self.question
Any suggestions on how i can fix this ?