models.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 for显示来自两个表的数据库中的数据。
我的views.py是
def index(request):
book = forms.ModelMultipleChoiceField(queryset=Book.objects.all())
return render_to_response('index.html', locals(),context_instance=RequestContext(request))
我无法显示来自database.please的所有数据帮助我。如果我的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>
谢谢,
答案 0 :(得分:1)
您的模型和表单看起来正确无误。请参阅part 4 of the Django tutorial以获取编写视图以获取连接的帮助。
答案 1 :(得分:1)
在views.py中尝试此操作:
from models import Book
from django.shortcuts import render_to_response
from django.template import RequestContext
def index(request):
books = Book.objects.all()
return render_to_response('index.html',
locals(),
context_instance=RequestContext(request))