我试图通过Django在我的网页上显示视图。但我做不到甚至我尝试了ChatGPT建议的几个解决方案。
这些是我的代码
- models.py
class PostView(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
views = models.PositiveIntegerField(default=0)
def __str__(self):
return f'Views for Post: {self.question}'
it's my code for create views for each question
1-1. models.py
class Question(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author_question')
subject = models.CharField(max_length=200)
content = models.TextField()
create_date = models.DateTimeField()
modify_date = models.DateTimeField(null=True, blank=True)
voter = models.ManyToManyField(User, related_name='voter_question')
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_question')
def __str__(self):
return self.subject
与PostView模型建立联系的是Question模型。
在我写了这段代码之后我运行了“makemigrations”和“migrate”
- base_views.py
def view_question(request, question_id):
question = get_object_or_404(Question, pk=question_id)
post_views, created = PostView.objects.get_or_create(question=question)
post_views.views += 1
post_views.save()
context = {'question': question, 'post_views': post_views}
return render(request, 'pybo/question_detail.html', context)
- url.py
path('question/list/',base_views.index, name='index'),
path('quesiton/list/<str:category_name>/', base_views.index, name='index'),
path('question/detail/<int:question_id>/', base_views.detail, name='detail'),
path('question/detail/<int:question_id>/',
base_views.view_question, name='views_question'),
1.模板
{% if question_list %}
{% for question in question_list %}
<tr class="text-center">
<td>{{question_list.paginator.count|sub:question_list.start_index|sub:forloop.counter0|add:1 }}</td>
<td>
{% if question.voter.all.count > 0 %}
<span class="badge badge-warning px-2 py-1">
{{ question.voter.all.count}}
</span>
{% endif %}
</td>
<td class="text-left">
<a href="{% url 'pybo:detail' question.id %}">
{{ question.subject }}
</a>
{% if question.answer_set.count > 0 %}
<span class="text-danger small ml-2">
{{ question.answer_set.count }}
</span>
{% endif %}
</td>
<td>{{ question.author.username }}</td>
<td>
{% with question.postviews_set.first as post_views %}
{{ post_views.views }}
{% endwith %}
</td>
<td>{{ question.create_date }}</td>
</tr>
{% endfor %}
它只显示了视图的空间,但它没有显示任何数字,即使我在模型中将默认值设置为0。我试图得到解决方案ChatGPT,并做了他们的建议,但我不能解决这个问题.也试图找到我的错误拼写ChatGPT和它没有发生任何错过的拼写。
如果你能就这个问题给给予,我会很高兴的。谢谢.
1条答案
按热度按时间vptzau2j1#
在你的
view_question()
函数中,你在你的上下文中返回了question_list
,所以在你的模板中没有什么需要修改的。同样,一旦你修复了这个问题,你就会遇到问题,把迭代器设置为与你已经传入的模板对象相同的名称。我也相信这只是因为它不是复制和粘贴,但确保所有的声明在您的模板有他们的结束语以及。
{% endif %}