当试图在模型obj上打开管理页面时,它永远不会加载

时间:2017-08-29 09:56:00

标签: python django django-models django-forms django-admin

我有一个项目,我已经建立了一段时间,我最近发现了一个问题。 这是使用python 3.6和Django 1.11

我有以下型号

class Mail(models.Model):
    """
    This stores all Downloaded Mails.
    They relate To alerts raised by the email checking process.
    """
    # This is for turning column numbers into ordering commands
    ordering = {
        '0': {
            'asc': 'mail_from',
            'desc': '-mail_from'
        },
        '1': {
            'asc': 'subject',
            'desc': '-subject'
        },
        '3': {
            'asc': 'received',
            'desc': '-received'
        }
    }
    mail_id = models.CharField(unique=True, max_length=255)
    mail_from = models.EmailField()
    subject = models.CharField(max_length=255)
    message = models.TextField()
    alert = models.ForeignKey(Alert, null=True, blank=True)
    received = models.DateTimeField(default=timezone.now, db_index=True)
    processed = models.BooleanField(default=False)

    class Meta:
        """
        Mails should be ordered by newest first.
        get_latest_by should be the received property
        """
        get_latest_by = 'received'
        ordering = ['-received']

    def __str__(self) -> str:
        """
        :return: Return string in the format 'Mail_id: subject_text'
        :rtype: str
        """
        return f'<{self.mail_id}: {self.subject}>'

我可以使用我的观点访问和阅读邮件。我一直在手动显示它们,但我决定转而使用表格来显示它们。然后我注意到了我的问题。它似乎陷入无限循环,将这个模型放入一个表单中。

这是模型

class MailForm(forms.ModelForm):
    class Meta:
        model = Mail
        fields = ['mail_from', 'subject', 'alert', 'received', 'processed']

然后我在管理站点打开了这个,发现同样的事情正在发生。我可以查看邮件列表,但是当我尝试打开单个邮件时,它会继续加载。

1 个答案:

答案 0 :(得分:0)

感谢Daniel Roseman注意到可能存在的明显问题。 我用这个答案解决了How to Stop Django ModelForm From Creating Choices for a Foreign Key

class DiplayAlertText(forms.CharField):
    def prepare_value(self, value):
        alert = Alert.objects.get(id=value)
        return alert.message

class MailForm(forms.ModelForm):
    alert = DiplayAlertText()

    class Meta:
        model = Mail
        fields = ['mail_from', 'subject', 'alert', 'received', 'processed']