我有一个代表各种语言状态的模型,所以我使用的是django-hvad TranslatableModel
基类。
在表单中使用时,event_status
中的TranslatableModel
字段选项为1, 2
等,因此Status.__unicode__
必须返回与描述属性相对的pk
如预期的那样。
forms.py
class StatusForm(forms.ModelForm):
"""
Form for approving an event.
"""
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
self.base_fields['user'].queryset = User.objects.filter(pk=user.id)
super(StatusForm, self).__init__(*args, **kwargs)
user = forms.CharField(
widget=forms.HiddenInput()
)
timestamp = forms.DateField(
input_formats=DATE_INPUT_FORMATS
)
class Meta:
model = StatusHistory
fields = [
'event_status', 'timestamp', 'user'
]
models.py
class Status(TranslatableModel):
"""
Status to be applied to an event.
"""
translations = TranslatedFields(
description=models.CharField(
verbose_name=_("Status description"),
default=_("Submitted"),
max_length=255
)
)
class Meta:
app_label = 'events'
verbose_name = _("Status")
verbose_name_plural = _("Status")
def __unicode__(self):
return self.safe_translation_getter('description', str(self.pk))
class StatusHistory(models.Model):
"""
The historical log of event statuses.
"""
event = models.ForeignKey(
'events.Event',
related_name='StatusHistory'
)
event_status = models.ForeignKey(Status)
timestamp = models.DateTimeField(
verbose_name=_("Time of status change"),
auto_now=True
)
user = models.ForeignKey(User)
class Meta:
app_label = 'events'
verbose_name = _("Status history")
verbose_name_plural = _("Status history")
def __unicode__(self):
return u"{event}: {status}".format(
event=self.event, status=self.event_status
)
我是否错误地实施了TranslatableModel
?我有一次通过Pycharm的调试服务器运行它,其中一个Status
对象给了我描述,但另一个只返回一个id所以我认为我在这种方法中是正确的