开发者

Display/Edit fields across tables in a Django Form

开发者 https://www.devze.com 2022-12-31 12:53 出处:网络
I have 2 tables/models, which for all practical purposes are the same as the standard Author/Book example, but with the additional restriction that in my application each Author can only write 0 or 1

I have 2 tables/models, which for all practical purposes are the same as the standard Author/Book example, but with the additional restriction that in my application each Author can only write 0 or 1 books. (eg, the ForeignKey field in the Book model is or can be a OneToOneField, and there may be authors who have no corresponding book in the Book table.)

I would like to be able to display a form showing multiple books and also show some fields from the corresponding Author table (eg author_name, author_address). I followed the example of the inlineformset and but that doesn't even display the author name in the generated form.

EDIT --- Added code sample

# Models
class Author(models.Model):
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=100)

class Book(models.Model):
    author = models.OneToOneField(Author)
    title = models.CharField(max_length=100)

# views
def manage_books(request):
    author = Author.objects.get(pk=1)
    BookInlineFormSet = inlineformset_factory(Author, Book)
    formset = BookInlineFormSet(instance=author)
    return render_to_response("manage_books.html", {
        "formset": formset,
    })

# template
<table>
<tr>
<th>Author</th>
<th>Address</th>
<th>Title</th>
</tr>
{% for form in formset.forms %}
<tr>
<td>{{ form.author }}</t开发者_运维问答d>
<td>{{ form.author_address }}</td>
<td>{{ form.title }}</td>
</tr>
{% endfor %}
</table>

The output is blank for the Author and the Author_address Note I can get the author to print if I define a unicode function in the model, but that doesn't solve the general problem. Note also that form.author.address doesn't work either.


I'm new to Django, but I think this is what you're after.

Try adding null=True to your OneToOneField. eg:

book = model.OneToOneField(Book, null=True)

With regards to the second part, inline forms are what you're looking for. I'd assume there's an error somewhere in your form or - more likely - your template. Did you add (for example):

{{ author_formset.as_p }}

in your template under {{ form.as_p }}?

If that's not the problem, you may need to post the related template, view, model & form code.

0

精彩评论

暂无评论...
验证码 换一张
取 消