Django表单包含外键字段列表

时间:2012-05-20 10:57:15

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

我有以下模型,我正在尝试为其创建表单:

class Letter(models.Model):
   title = models.CharField(max_length=100)
   publish_date = models.TimeField()

class LetterRecipients(models.Model):
   letter = models.ForeignKey(Letter)
   recipient_name = models.CharField(max_length=200)
   recipient_rating = models.IntegerField()
   has_responded = models.BooleanField()

我想要一个允许用户为该字母输入标题和publish_date的表单,并以相同的形式按名称和等级输入多个收件人。

任何人都可以帮忙创建表单模型吗?我无法弄清楚如何让django使用{{ form.as_p }}生成此表单。我想我将不得不使用jQuery在HTML页面上创建额外的收件人行,但是我如何让django将它们解析为模型呢?

非常感谢任何帮助。

感谢。 方舟

1 个答案:

答案 0 :(得分:6)

Ark,您可以在Django表单中使用ModelMultipleChoiceField。这里有一些粗略的例子。我创建“帖子”应用程序只是为了快速测试:

forms.py

from django import forms
from django_test.posts.models import Letter, LetterRecipients


class LetterForm(forms.Form):
    title = forms.CharField()
    publish_date = forms.TimeField()
    recepient = forms.ModelMultipleChoiceField(
                                        queryset=LetterRecipients.objects.all()
                                        )

models.py

from django.db import models


class Letter(models.Model):
    title = models.CharField(max_length=100)
    publish_date = models.TimeField()


class LetterRecipients(models.Model):
    letter = models.ForeignKey(Letter)
    recipient_name = models.CharField(max_length=200)
    recipient_rating = models.IntegerField()
    has_responded = models.BooleanField()

    def __unicode__(self):
        return self.recipient_name

views.py

# Create your views here.
from django_test.posts.forms import LetterForm
from django.shortcuts import render


def index(request):
    form = LetterForm()
    data = {'form': form}

    return render(request, 'posts/index.html', data)

的index.html

{% load url from future %}

{{ form.as_p }}