我想访问我的模板中用户的区域:
{% if object.seller.profile.post_code %}{{ object.seller.profile.post_code }} {% endif %}{% if object.seller.profile.city%}{{ object.seller.profile.city }}<br/>{% endif %}
{% if object.seller.profile.region.name %}{{ object.seller.profile.region.name }}, {% endif %}{% if object.seller.profile.region.country.name %}{{ object.seller.profile.region.country.name }}{% endif %}
这是我的型号:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics',
verbose_name='Profilbild')
post_code = models.CharField(max_length=5, blank=True, verbose_name='Postleitzahl')
region = models.ForeignKey(Region, on_delete=models.CASCADE,
null=True, blank=True, verbose_name='Region', help_text='Bundesland oder Kanton')
city = models.CharField(max_length=50, blank=True, verbose_name='Stadt')
street = models.CharField(max_length=50, blank=True, verbose_name='Straße')
class Region(models.Model):
name = models.CharField(max_length=30, verbose_name='Region', help_text='Bundesland oder Kanton', default='Berlin')
symbol = models.CharField(max_length=30, verbose_name='Region-Kürzel', default='BER')
country = models.ForeignKey('Country', on_delete=models.CASCADE, null=True,
verbose_name='Land', default=0)
class Country(models.Model):
name = models.CharField(max_length=30, verbose_name='Land', default='Deutschland')
symbol = models.CharField(max_length=4, verbose_name='Kürzel', default='DE')
但我不想强迫用户输入他们的地址数据。但是如果没有填写ForeignKey字段,我会得到
'NoneType' object has no attribute 'country'
如果在views.py中填写了每个字段,那么有没有比检查每个字段并将其单独添加到上下文中更优雅的方法呢?
可以在您的配置文件模型中添加一些快捷方式来帮助实现这一点:
views.py:
class Profile(models.Model):
...
@property
def country_name(self):
return self.region.country.name if self.region and self.region.country else None
template.html:
...
<div> {{object.seller.profile.country_name }} </div>