我有以下代码。产品是这样的:有一个书单。每本书上都有一个表格。该表格保存了一个帖子,并使其与这本书相关。当您单击某本书项目时,您会看到所有与该本书项目相关的帖子列表。到目前为止,书籍列表可以正常工作,保存帖子数据可以很好地工作,并且当您单击列表时,它(DetailView)可以显示帖子列表(而不是书籍描述,通常是使用DetailView的方式)。不起作用的是将帖子保存为与保存该帖子的表单的特定书籍相关。更简单地说,当您保存帖子时,该帖子应与表单所在的书相关。
非常感谢您的帮助。谢谢!
views.py:
<Text text="{path:'oTesTableModel>score',formatter:'publicservices.scr.myscorereq.util.Formatter.score'}"/>
models.py:
class BookList(ListView):
model = Book
template_name='books/books.html'
class PostForm(ModelForm):
class Meta:
model = Post
# Previously I tried, unsuccessfully, this among others:
# books = Book.objects.filter(book)
# posts = Post.objects.filter(the_book=books)
# model = posts
fields = ['post']
widgets = {
'post': forms.Textarea()
}
def get_context_data(self, **kwargs):
context = super(BookList, self).get_context_data(**kwargs)
context['form'] = BookList.PostForm
return context
def post(self, request, *args, **kwargs):
form = BookList.PostForm(request.POST)
if form.is_valid():
form.save()
return render(request, self.template_name, {'form': form })
class Posts(DetailView):
model = Book
template_name='books/post_create.html'
slug_field = 'id'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
book = self.object
posts = Post.objects.filter(the_book=book)
context['posts'] = posts
return context
books.html:
class Book(models.Model):
book = models.CharField(max_length=1000, blank=False, null=False, default="1")
def __str__(self):
return self.book
class Post(models.Model):
post = models.CharField(max_length=1000, blank=False, null=False)
the_book = models.ForeignKey('Book', on_delete=models.CASCADE, default="1")
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.post
post_create.html(名称稍后会更改...):
<ul>
{% for book in object_list %}
<div class='ui card'>
<a class="content" href='{% url 'books:posts' book.id %}'>
<div class="header">{{ book }}</div>
</a>
<div class="ui bottom attached button">
<form class='ui form' action='' method='post'> {% csrf_token %}
{{ form.as_p }}
<div class='postbutton'>
<input class='ui button' type="submit" value="Done" />
</div>
</form>
</div>
</div>
{% empty %}
<h5>You don't have any books!</h5>
{% endfor %}
答案 0 :(得分:1)
尝试一下:在您的表单中添加一个book_id隐藏输入:
<form class='ui form' action='' method='post'> {% csrf_token %}
{{ form.as_p }}
<input type="hidden" name="book_id" value="{{ book.id }}">
<div class='postbutton'>
<input class='ui button' type="submit" value="Done" />
</div>
并在BookList视图中使用它:
def post(self, request, *args, **kwargs):
form = BookList.PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.the_book_id = request.POST['book_id']
post.save()
return render(request, self.template_name, {'form': form })