验证失败时,inlineformset_factory生成的字段将消失

时间:2010-08-08 02:23:19

标签: django django-models django-forms

我有一个简单的图书作者关系

class Author(models.Model):
    first_name = models.CharField(max_length=125)
    last_name = models.CharField(max_length=125)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

class Book(models.Model):
    title = models.CharField(max_length=225)
    author = models.ForeignKey(Author)

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author

class BookForm(forms.ModelForm):
    class Meta:
        model = Book

这就是我的观点

def addbook(request):

    BookFormSet = inlineformset_factory(models.Author, models.Book, extra=1)

    if request.method == 'GET':
        author = models.AuthorForm()
        books = BookFormSet()
    else:
        author = models.AuthorForm(request.POST)
        if author.is_valid():
            books = BookFormSet(request.POST)
            if books.is_valid():
                print(books)

    return render_to_response('bookadd.html', locals(), context_instance = RequestContext(request))

我的模板看起来像这样

<form action="/books/add_new" method="post">
      {% csrf_token %}
      <table>
        <tr>
          <td>First name: </td>
          <td>{{ author.first_name }}</td>
          <td>{{author.first_name.errors}}</td>
        </tr>
        <tr>
          <td>Last name</td>
          <td>{{ author.last_name }}</td>
          <td>{{author.last_name.errors}}</td>
        </tr>
      </table>
      {{ books.management_form }}
      {{ books.as_table }}
      <br/>
      <input type="submit" value="Submit" />
    </form>

如果我将标题字段留空并按Enter键,则在帖子后面,书名字段会消失,我无法弄清楚如何处理它。我希望该字段与用户输入的任何数据一致。

1 个答案:

答案 0 :(得分:1)

您可以尝试

    author = models.AuthorForm(request.POST)
    books = BookFormSet(request.POST)
    if author.is_valid():

而不是

    author = models.AuthorForm(request.POST)
    if author.is_valid():
        books = BookFormSet(request.POST)