View does not seem to be saving all the information in my model

只愿长相守 提交于 2019-12-08 11:58:34

问题


I have a model and a view for saving books. However, when I access the information it does not appear to be complete. All queries seem to be running properly. I'm at a loss what could be going wrong

my model

class Book(models.Model):
      title = models.CharField(max_length=50)
      user = models.ForeignKey(CustomUser, on_delete=models.CASCADE,)
      cover_pic = models.FileField(null=True, blank=True)
      author = models.CharField(max_length=100, blank=True)
      description = models.TextField(max_length=1000)
      uploaded_on = models.DateTimeField(auto_now_add=True)

      def __str__(self):
        return self.title

      def get_absolute_url(self):
        return reverse("books:addBook")

      class Meta:
        ordering = ["-uploaded_on"]

My views.py

class addBook(FormUserNeededMixin, CreateView):
    form_class = BookForm
    success_url = reverse_lazy('addbook')
    template_name = 'books/addbook.html'

forms.py

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        exclude = ['user', 'uploaded_on']

am trying to access the details using this view

class BookListView(ListView):
    model = Book
    template_name = 'books/viewbooks.html'

and this template

{% for books in object_list %}
  <img src="{{ book.cover_pic }}">
  <h5>{{ book.title }}</h5>
  <p>{{ book.author }}</p>
{% endfor %}

everytime I add an item I can see another list item added in view books but has none of the details that I requested.


回答1:


Your loop variable is books not book. Rename one of them, for example the one in the for tag:

{% for book in object_list %}
  <img src="{{ book.cover_pic }}">
  <h5>{{ book.title }}</h5>
  <p>{{ book.author }}</p>
{% endfor %}


来源:https://stackoverflow.com/questions/55419739/view-does-not-seem-to-be-saving-all-the-information-in-my-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!