2010-08-08 3 views
0

J'ai un livre simple Auteur relationLes champs générés par inlineformset_factory disparaît lorsque la validation échoue

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 

C'est ce que j'ai à mon avis

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)) 

Mon modèle ressemble à ceci

<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> 

Si je laisse vide le champ du titre et que j'appuie sur Entrée, le champ du titre du livre disparaît au retour ars, et je ne peux pas savoir quoi faire à ce sujet. Je veux que le champ soit là avec toutes les données entrées par l'utilisateur.

Répondre

1

Vous pouvez essayer

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

au lieu de

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