【问题标题】:How to show ManyToMany fields using CreateView in Django 1.8如何在 Django 1.8 中使用 CreateView 显示多对多字段
【发布时间】:2015-11-01 19:25:03
【问题描述】:

我在 Django 1.8 中做一个基本应用程序,我正在使用 Create-View,我不知道为什么创建表单没有 manyTOmany 字段,也没有以前在我的模型中定义的外键字段。这是我的代码:

我的模特:

class Autor(models.Model):
    nombre = models.CharField(max_length=30)
    ....
class Editor(models.Model):
    nombre = models.CharField(max_length=30)
    ...
class Libro(models.Model):
   titulo = models.CharField(max_length=100)
   autores = models.ManyToManyField(Autor) #MANY2MANY FIELD
   editor = models.ForeignKey(Editor) #FOREIGN KEY FIELD
   fecha_publicacion = models.DateField()
   portada = models.ImageField(upload_to = 'portadas/')

   def __unicode__(self):
    return self.titulo

我的观点:

class LibroCreateView(CreateView):
   model = Libro
   template_name = 'biblioteca/crear.html'
   fields = ['titulo', 'autores', 'editor', 'fecha_publicacion', 'portada']

我的模板:

{% block main %}
<form action="" enctype="multipart/form-data" method="POST">{% csrf_token %}
    <table>
        {{form.as_table}}   
    </table>
    <input type="submit" name="crear" value="Crear">
</form> <br>
{% endblock main %}

我的结果

为什么我的字段“Autores”(many2many)和“Editor”(外键)没有正确显示?谢谢。

【问题讨论】:

    标签: django django-models django-templates django-views django-1.8


    【解决方案1】:

    尝试为CreateView 的视图赋予形式。使用您的模型制作ModelForm

    在那里你可以查询你的外键和多对多字段。 你可以随心所欲地展示它们

    【讨论】:

    • 当然,我有我的 ModelForm,但我的多对多和外键字段仍然不起作用。在这里,我向您展示了我的代码图像......但是,如果我解决了它,我将发布我的解决方案。 cloud.githubusercontent.com/assets/8607266/9178906/…
    • 您在此处的代码和屏幕截图中的代码不同。使用创建视图,它只会根据您的表单保存模型。简单..
    猜你喜欢
    • 2019-10-12
    • 2021-06-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2021-06-20
    • 2011-04-20
    • 2017-02-01
    • 1970-01-01
    相关资源
    最近更新 更多