问题
I am trying to simply display Model formset in django template. I get the following error
Here is what I am trying to display: the actual formset within a form
In the view.py, here is the related code snippet:
#
# create Address Model Form Set
#
AddressFormSet = modelformset_factory( Address, form=businessForms.AddressModelForm )
if request.method == 'GET':
businessModelForm = businessForms.BusinessModelForm( instance = business )
addressModelFormSet = AddressFormSet( queryset=Address.objects.filter(business__id=business.id) )
#addressModelFormSet = AddressFormSet( )
print addressModelFormSet.is_valid() /* prints False */
print addressModelFormSet.errors /* prints [] empty list */
return render(request, "business_profile.html", { 'businessModelForm' : businessModelForm,
'addressModelFormSet': addressModelFormSet })
I assume the validity of the form has nothing to do with this error since we check validity upon POST request, yet I could be wrong. No error list is shown though for the formset.
The AddressModelForm:
class AddressModelForm(ModelForm):
class Meta:
model = Address
fields = ['street_address', 'address_line2', 'city', 'state', 'zip_code']
The model definition:
class Country(models.Model):
country_name = models.CharField(max_length = 50)
country_code = models.CharField(max_length = 2)
phone_code = models.CharField(max_length = 3, default = '000')
country_name_ar = models.CharField(max_length = 50, default = '')
#many-to-many fields
currencies = models.ManyToManyField(Currency)
def __str__(self):
return "%s" % self.country_name
class City(models.Model):
city_name = models.CharField(max_length = 93)
city_name_ar = models.CharField(max_length = 93, default = '')
country = models.ForeignKey(Country)
def __str__(self):
return ("%s" % self.city_name) + "," + str(self.country)
class Address(models.Model):
street_address = models.CharField(max_length = 500)
address_line2 = models.CharField(max_length = 500, default = '')
city = models.ForeignKey(City) # country included implicitly in city
zip_code = models.CharField(max_length = 5, default = '')
state = models.CharField(max_length = 2, default = '')
def __str__(self):
usStr = ("%s" % self.street_address) + "," + str(self.city) + "," + self.state + "," + self.zip_code
nonUsStr = ("%s" % self.street_address) + "," + str(self.city)
if self.state != '':
return usStr
else:
return usStr
I am suspecting the fact that city model has city_name_ar which is Arabic field for city name ...
UPDATE If I remove 'city' from AddressModelForm, or override the field to be CharField, I don't get this error, however, I get text field with city ID which is useless ...
回答1:
You're using Python 2.x. Under 2.x, models should either have a __unicode__
method rather than or in addition to a __str__
method, and each method should return the appropriate type (unicode for __unicode__
, encoded bytes for __str__
) or you should use the python_2_unicode_compatible
decorator if you're on a sufficiently recent version of Django. If you're planning to stay on 2.x for the immediately future, I'd recommend just writing __unicode__
methods and not bothering with the decorator since you're concatenating string representations and I'm not quite sure what it does with that.
Some relevant docs are:
https://docs.djangoproject.com/en/1.8/ref/utils/#django.utils.encoding.python_2_unicode_compatible
https://docs.djangoproject.com/en/1.8/topics/python3/#str-and-unicode-methods
Either way, you should avoid converting database values (which are passed around as Unicode object) without specifying the encoding. Generally it's easiest to just define a method that returns unicode, eg:
class Country(models.Model):
# as above, except
def __unicode__(self):
return self.country_name
Or:
@python_2_unicode_compatible
class Country(models.Model):
# as above, except
def __str__(self):
return self.country_name
Similarly for your other models:
class City(models.Model):
...
def __unicode__(self):
return self.city_name + "," + unicode(self.country)
Or (untested, you might need to call unicode(self.country)
here as well):
@python_2_unicode_compatible
class City(models.Model):
...
def __str__(self):
return self.city_name + "," + str(self.country)
来源:https://stackoverflow.com/questions/32557468/django-unicodeencodeerror-when-displaying-formset-ascii-codec-cant-encode-char