我需要这样做,以便可以从主页打开新闻。但是我遇到了一个问题,解释器抛出错误“ ValueError:字段'id'期望有一个数字,但是得到了'news1'(我在下面添加了Traceback和代码)。我知道它期望有一个数字,但是接收到一个字符串,但我不知道如何解决它。谁知道,请帮忙
跟踪:
Internal Server Error: /news1/
Traceback (most recent call last):
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'news1'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\dadi2\Desktop\church\website\views.py", line 18, in get
posts = Blog.objects.get(id=slug)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\query.py", line 404, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\sql\query.py", line 1351, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\sql\query.py", line 1378, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\sql\query.py", line 1312, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\sql\query.py", line 1166, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\lookups.py", line 22, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\lookups.py", line 72, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got 'news1'.
[09/May/2020 14:10:52] "GET /news1/ HTTP/1.1" 500 132319
Not Found: /favicon.ico
[09/May/2020 14:10:53] "GET /favicon.ico HTTP/1.1" 404 2430
观看次数:
from django.shortcuts import get_object_or_404, render
from django.views.generic.base import View
from .models import Blog, Event
# Create your views here.
class EventView(View):
def get(self, request):
events = Event.objects.all()
posts = Blog.objects.all()
return render(request, "home/home.html", {"events": events, "posts":posts})
class BlogDetailView (View):
def get(self, request, slug):
posts = Blog.objects.get(id=slug)
return render(request, "home/blog-detail.html", {"posts": posts})
型号:
from django.db import models
from datetime import date
from django.urls import reverse
# Create your models here.
class Blog(models.Model):
"""Новости"""
name = models.CharField("Заголовок", max_length=100)
description = models.TextField("Описание")
descriptionTwo = models.TextField("Описание (второй абзац)", blank=True, default="")
blockquote = models.TextField("Цитата", blank=True, default="")
short = models.TextField("Краткое описание", max_length=300)
poster = models.ImageField("Изображение", upload_to="news/")
prewiew = models.ImageField("Превью", upload_to="news/")
dataPost = models.DateField("Дата публикации", default=date.today)
url = models.SlugField(max_length=160, unique=True, blank=True)
draft = models.BooleanField("Черновик", default=False)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("home_detail", kwargs={"slug": self.url})
class Meta:
verbose_name = "Новости"
verbose_name_plural = "Новости"
class Event(models.Model):
"""События"""
name = models.CharField("Заголовок", max_length=100)
adress = models.TextField("Адрес")
description = models.TextField("Описание")
short = models.TextField("Краткое описание")
phone = models.TextField("Контактный номер телефона")
email = models.EmailField()
image = models.ImageField("Изображение", upload_to="event/")
dataStart = models.DateField("Дата старта", default=date.today)
def __str__(self):
return self.name
class Meta:
verbose_name = "Событие"
verbose_name_plural = "События"
网址:
from django.urls import path
from . import views
urlpatterns = [
path("", views.EventView.as_view()),
path("<slug:slug>/", views.BlogDetailView.as_view(), name="home_detail")
]
HTML:
<!-- Latest-Blog -->
<section class="latest_blog section-padding">
<div class="container">
<div class="blog">
<div class="section-header text-center">
<h2 class="text-capitalize">Новости церкви</h2>
<p>Здесь вы найдёте самые последние новости из жизни церкви</p>
</div>
<div class="row">
{% if posts %}
{% for posts in posts %}
<article class="col-md-6 col-12">
<div class="blog_wrap">
<div class="blog_img">
<a href="{{ posts.get_absolute_url }}"><img src="{{ posts.prewiew.url }}" alt="image"></a>
</div>
<div class="blog_info">
<div class="post_date"><a href="#">{{ posts.dataPost}}</a></div>
<h5><a href="{{ posts.get_absolute_url }}">{{ posts.name }}</a></h5>
<p>{{ posts.short}}</p>
<a href="#" class="btn btn-primary">Details <i class="fa fa-caret-right"></i> </a>
</div>
</div>
</article>
{% endfor %}
{% else %}
<p>На данный момент новостей нет</p>
{% endif %}
</div>
</div>
</div>
</section>
<!-- Latest-Blog -->
答案 0 :(得分:0)
您已使用模板中的post.url
字段定义了href
<h5><a href="{{ posts.url }}/">{{ posts.name }}</a></h5>
因此查询集必须由url slug请求
class BlogDetailView (View):
def get(self, request, slug):
posts = Blog.objects.get(url=slug)
return render(request, "home/blog-detail.html", {"posts": posts})