【问题标题】:Fields generated by inlineformset_factory disappears when validation fails验证失败时 inlineformset_factory 生成的字段消失
【发布时间】:2010-08-08 02:23:19
【问题描述】:

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

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,则在回发时,书名字段会消失,我不知道该怎么办。我希望该字段与用户输入的任何数据一起存在。

【问题讨论】:

    标签: django django-models django-forms


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多