模型.py
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
age=models.IntegerField()
class Meta:
db_table=u'Author'
def __unicode__(self):
return u"%d %s %s %s %d" % (self.pk, self.first_name, self.last_name, self.email,self.age)
class Book(models.Model):
book_id=models.AutoField(primary_key=True,unique=True)
book_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
author=models.ForeignKey(Author)
class Meta:
db_table = u'Book'
def __unicode__(self):
return u'%d %s %s' % (self.pk, self.book_name, self.publisher_name)
你能告诉我如何为这个模型编写一个forms.py和views.py来显示来自数据库的数据。
我的 forms.py 是
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
fields = ['author_id','first_name','last_name','email','age']
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields=['book_id','book_name','publisher_name','author_id']
所以我以这种方式编写了forms.py,它是为模型字段编写的。所以请告诉我我给出的表单是正确的,如果不是,请告诉我如何编写forms.py和views.py来显示数据来自两个表的数据库。
我的views.py是
def index(request):
book = forms.ModelMultipleChoiceField(queryset=Book.objects.all())
return render_to_response('index.html', locals(),context_instance=RequestContext(request))
我无法显示数据库中的所有数据。请帮助我。如果我的views.py 内容有任何问题,请指导我如何编写views.py
我的 index.html 是
<html>
<head>
<title>
</title>
</head>
<body>
<div align="center">
<table border="0" cellpadding='8' cellspacing='10'>
<tr>
<td align="right" colspan="10"><a href="/addbook/">Add Book</a></td>
</tr>
<tr>
<th>Book Id</>
<th>Book name</th>
<th>Publication name</th>
<th>Author Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>E Mail</th>
<th>Age</th>
<th></th>
<th></th>
</tr>
{% for book in books %}
<tr>
<td>{{ book.book_id }}</td>
<td>{{ book.book_name }}</td>
<td>{{ book.publisher_name }}</td>
<td>{{ book.author_id }}</td>
<td>{{ book.author.first_name }}</td>
<td>{{ book.author.last_name }}</td>
<td>{{ book.author.email }}</td>
<td>{{ book.author.age }}</td>
<td><a href="/editbook/{{ book.book_id}}">Edit</a></td>
<td><a href="/deletebook/{{ book.book_id}}">Delete</a></td>
{% endfor %}
</table>
</div>
</body>
</html>
谢谢,