ModelChoiceForm不显示任何值

2024-04-26 05:44:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我的models.py文件中有一个this ModelApuntes

class Apuntes(models.Model):
    PRIVACY_CHOICES=(
        ('public', 'Público'),
        ('private', 'Privado'),
        ('password', 'Protegido')
    )
    owner=models.ForeignKey(User)
    privacy=models.CharField("Privacidad", max_length=10, choices=PRIVACY_CHOICES, default='private')
    password=models.CharField("Contraseña", max_length=20, blank=True)
    asignatura=models.ForeignKey(Asignaturas)
    datos=models.FileField()
    descripcion=models.CharField(max_length=150)
    added=models.DateTimeField(auto_now=True)

我还有一个由ApuntesForm模型在forms.py中生成的表单:

class ApuntesForm(forms.ModelForm):
    class Meta:
        model = Apuntes
        fields = ['privacy', 'password', 'asignatura', 'datos', 'descripcion']
        widgets = {
            'descripcion': forms.Textarea(attrs={'class': 'form-control'}),
            'privacy': forms.Select(attrs={'class': 'form-control'}),
            'password': forms.PasswordInput(attrs={'class': 'form-control'}),
            'asignatura': forms.Select(attrs={'class': 'form-control'}),
        }

当我尝试在视图中使用此窗体时,AsignaturasSelect字段无法正确显示:

Look here

我希望它显示数据库中的nombre列,而不仅仅是一个泛型对象。你知道吗


Tags: pyformmodelsformspasswordlengthattrsmax
2条回答

从文档中:

__str__

Model.__str__() The __str__() method is called whenever you call str() on an object. Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object. Thus, you should always return a nice, human-readable representation of the model from the __str__() method.

For example:

from django.db import models 
from django.utils.encoding import python_2_unicode_compatible`

@python_2_unicode_compatible  # only if you need to support Python 2
class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def __str__(self):
        return '%s %s' % (self.first_name, self.last_name) 

If you’d like compatibility with Python 2, you can decorate your model class with python_2_unicode_compatible() as shown above.

Puam的答案可以在python2.7中使用,但是如果您在3中,您将需要阅读Django docsPort to Python 3中的strunicode方法部分

试试这个。。。你知道吗

class Asignaturas(models.Model):
    ...
    #your fields
    ...
    nombre = models.CharField(max_length=255)

    def __unicode__(self):
        return self.nombre

;)

相关问题 更多 >