扩展的CreateView不会在模板中提供所需的输出

时间:2013-06-10 10:46:23

标签: django django-templates django-class-based-views django-generic-views

我的 model.py

中有两个表格
class Partner(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, blank=True)
    class Meta:
        db_table = 'partner'

class Device(models.Model):
    id = models.AutoField(primary_key=True)
    partner = models.ForeignKey('Partner', null=True, blank=True)
    username = models.CharField(max_length=255, blank=True)
    password = models.CharField(max_length=255, blank=True)
    class Meta:
        db_table = 'device'

我为通用表单生成创建了一个View:

class CreateDeviceView(CreateView):
    model = Device
    template_name = 'device_form.html'
    #form_class = DeviceForm

    def get_success_url(self):
        return reverse('partners')

我从 urls.py

中拨打电话
 url(r'^device/new', CreateDeviceView.as_view(), name='device-new'),

模板 device_form.html 是:

<form action="{{ action }}" method="POST">
        {% csrf_token %}
        <ul>
            {{ form.as_p }}
        </ul>
        <input type="submit" class="btn btn-info" value="Save"/>
    </form>

生成的创建表单在选择菜单中有值(对于外键):合作伙伴对象,合作伙伴对象...... 如何将选择菜单中的值变为Partner.name? 我试图构建自己的表单,但我没有得到所需的输出。

1 个答案:

答案 0 :(得分:1)

Partner模型中,添加__unicode__方法:

class Partner(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, blank=True)

    def __unicode__(self):
        return unicode(self.name)

    class Meta:
        db_table = 'partner'