Anonymous
Django — общее подробное представление DailyForecastDetailView необходимо вызывать либо с объектом pk, либо с фрагментом
Сообщение
Anonymous » 06 мар 2026, 20:26
Может ли кто-нибудь мне в этом помочь? Я новичок в Django и, видимо, где-то отсутствует связь между моим кодом. Я уже пробовал некоторые решения этой проблемы, упомянутые в SOF, но не могу заставить их работать.
Я получаю сообщение об ошибке:
Общее подробное представление DailyForecastDetailView должно вызываться либо с объектом pk, либо с пулом в URLconf
На моем локальном URL-адресе с датой (
http://127.0.0.1:8000/forecast/narnia/2023-03-26/ ) и без параметра даты (
http://127.0.0.1:8000/forecast/narnia/ )
Код: Выделить всё
models.py:
from django.conf import settings
from django.db import models
from django.utils.text import slugify
User = settings.AUTH_USER_MODEL
# Create your models here.
class DefaultProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
bio = models.TextField()
def __str__(self):
return f"{self.__class__.__name__} object for {self.user}"
class Location(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(unique=True)
country = models.CharField(max_length=255)
region = models.CharField(max_length=255, blank=True, null=True)
lat = models.DecimalField(max_digits=9, decimal_places=6)
lon = models.DecimalField(max_digits=9, decimal_places=6)
timezone_id = models.CharField(max_length=255)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super().save(*args, **kwargs)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "locations"
# class CurrentWeather(models.Model):
class Forecast(models.Model):
location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="forecasts")
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class DailyForecast(Forecast):
date = models.DateField()
date_epoch = models.IntegerField()
maxtemp_c = models.DecimalField(max_digits=5, decimal_places=2)
maxtemp_f = models.DecimalField(max_digits=5, decimal_places=2)
mintemp_c = models.DecimalField(max_digits=5, decimal_places=2)
mintemp_f = models.DecimalField(max_digits=5, decimal_places=2)
avgtemp_c = models.DecimalField(max_digits=5, decimal_places=2)
avgtemp_f = models.DecimalField(max_digits=5, decimal_places=2)
maxwind_mph = models.DecimalField(max_digits=5, decimal_places=2)
maxwind_kph = models.DecimalField(max_digits=5, decimal_places=2)
totalprecip_mm = models.DecimalField(max_digits=5, decimal_places=2)
totalprecip_in = models.DecimalField(max_digits=5, decimal_places=2)
avgvis_km = models.DecimalField(max_digits=5, decimal_places=2)
avgvis_miles = models.DecimalField(max_digits=5, decimal_places=2)
avghumidity = models.IntegerField()
daily_will_it_rain = models.IntegerField()
daily_will_it_snow = models.IntegerField()
daily_chance_of_rain = models.IntegerField()
daily_chance_of_snow = models.IntegerField()
uv = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return f"{self.location.name}, {self.date}"
class Meta:
verbose_name_plural = "daily forecasts"
class HourlyForecast(Forecast):
time_epoch = models.IntegerField()
time = models.DateTimeField()
temp_c = models.DecimalField(max_digits=5, decimal_places=2)
temp_f = models.DecimalField(max_digits=5, decimal_places=2)
is_day = models.BooleanField()
text = models.CharField(max_length=255)
icon = models.CharField(max_length=255)
code = models.IntegerField()
wind_mph = models.DecimalField(max_digits=5, decimal_places=2)
wind_kph = models.DecimalField(max_digits=5, decimal_places=2)
wind_degree = models.IntegerField()
wind_dir = models.CharField(max_length=255)
pressure_mb = models.DecimalField(max_digits=5, decimal_places=2)
pressure_in = models.DecimalField(max_digits=5, decimal_places=2)
precip_mm = models.DecimalField(max_digits=5, decimal_places=2)
precip_in = models.DecimalField(max_digits=5, decimal_places=2)
humidity = models.IntegerField()
cloud = models.IntegerField()
feelslike_c = models.DecimalField(max_digits=5, decimal_places=2)
feelslike_f = models.DecimalField(max_digits=5, decimal_places=2)
windchill_c = models.DecimalField(max_digits=5, decimal_places=2)
windchill_f = models.DecimalField(max_digits=5, decimal_places=2)
heatindex_c = models.DecimalField(max_digits=5, decimal_places=2)
heatindex_f = models.DecimalField(max_digits=5, decimal_places=2)
dewpoint_c = models.DecimalField(max_digits=5, decimal_places=2)
dewpoint_f = models.DecimalField(max_digits=5, decimal_places=2)
will_it_rain = models.IntegerField()
will_it_snow = models.IntegerField()
vis_km = models.DecimalField(max_digits=5, decimal_places=2)
vis_miles = models.DecimalField(max_digits=5, decimal_places=2)
chance_of_rain = models.IntegerField()
chance_of_snow = models.IntegerField()
gust_mph = models.DecimalField(max_digits=5, decimal_places=2)
gust_kph = models.DecimalField(max_digits=5, decimal_places=2)
uv = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return f"{self.location.name}, {self.time}"
class Meta:
verbose_name_plural = "hourly forecasts"
Код: Выделить всё
views.py:
from datetime import date
from django.shortcuts import get_object_or_404, render
from django.views.generic import DetailView, ListView, TemplateView
from .models import DailyForecast, HourlyForecast, Location
class BaseView(TemplateView):
template_name = "forecast/daily_forecast_detail.html"
class LocationListView(ListView):
model = Location
template_name = "forecast/location_list.html"
context_object_name = "locations"
class DailyForecastDetailView(DetailView):
model = DailyForecast
template_name = "forecast/daily_forecast_detail.html"
context_object_name = "forecast"
def get_queryset(self):
location_slug = self.kwargs["location_slug"]
date = self.kwargs["date"]
location = get_object_or_404(Location, slug=location_slug)
return DailyForecast.objects.filter(location=location, date=date)
class DailyForecastTodayView(DetailView):
model = DailyForecast
template_name = "forecast/daily_forecast_detail.html"
context_object_name = "forecast"
def get_queryset(self):
location_slug = self.kwargs["location_slug"]
location = get_object_or_404(Location, slug=location_slug)
date_today = date.today()
return DailyForecast.objects.filter(location=location, date=date_today)
class HourlyForecastDetailView(DetailView):
model = HourlyForecast
template_name = "forecast/hourly_forecast_detail.html"
context_object_name = "forecast"
def get_queryset(self):
location_slug = self.kwargs["location_slug"]
date = self.kwargs["date"]
hour = self.kwargs["hour"]
location = get_object_or_404(Location, slug=location_slug)
return HourlyForecast.objects.filter(location=location, date=date, hour=hour)
Код: Выделить всё
urls.py:
from django.urls import path
from .views import (
BaseView,
DailyForecastDetailView,
DailyForecastTodayView,
HourlyForecastDetailView,
LocationListView,
)
app_name = "forecast"
urlpatterns = [
# path("", LocationListView.as_view(), name="location_list"),
path("//", DailyForecastDetailView.as_view(), name="daily_forecast_detail"),
path("/", DailyForecastTodayView.as_view(), name="daily_forecast_today"),
# path("", BaseView.as_view(), name="daily_forecast_detail"),
path("///", HourlyForecastDetailView.as_view(), name="hourly_forecast_detail"),
]
На моем локальном компьютере я получил доступ к следующему временному URL-адресу с датой (
http://127.0.0.1:8000/forecast/narnia/2023-03-26/ ) и без параметра даты (
http://127.0.0.1:8000/forecast/narnia/ ) и получаю сообщение об ошибке:
Общий подробный вид DailyForecastDetailView необходимо вызывать либо с объектом pk, либо с фрагментом в URLconf
Подробнее здесь:
https://stackoverflow.com/questions/759 ... ith-either
1772818009
Anonymous
Может ли кто-нибудь мне в этом помочь? Я новичок в Django и, видимо, где-то отсутствует связь между моим кодом. Я уже пробовал некоторые решения этой проблемы, упомянутые в SOF, но не могу заставить их работать. Я получаю сообщение об ошибке: Общее подробное представление DailyForecastDetailView должно вызываться либо с объектом pk, либо с пулом в URLconf На моем локальном URL-адресе с датой (http://127.0.0.1:8000/forecast/narnia/2023-03-26/) и без параметра даты (http://127.0.0.1:8000/forecast/narnia/) [code]models.py: from django.conf import settings from django.db import models from django.utils.text import slugify User = settings.AUTH_USER_MODEL # Create your models here. class DefaultProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") bio = models.TextField() def __str__(self): return f"{self.__class__.__name__} object for {self.user}" class Location(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(unique=True) country = models.CharField(max_length=255) region = models.CharField(max_length=255, blank=True, null=True) lat = models.DecimalField(max_digits=9, decimal_places=6) lon = models.DecimalField(max_digits=9, decimal_places=6) timezone_id = models.CharField(max_length=255) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class Meta: verbose_name_plural = "locations" # class CurrentWeather(models.Model): class Forecast(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="forecasts") created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class DailyForecast(Forecast): date = models.DateField() date_epoch = models.IntegerField() maxtemp_c = models.DecimalField(max_digits=5, decimal_places=2) maxtemp_f = models.DecimalField(max_digits=5, decimal_places=2) mintemp_c = models.DecimalField(max_digits=5, decimal_places=2) mintemp_f = models.DecimalField(max_digits=5, decimal_places=2) avgtemp_c = models.DecimalField(max_digits=5, decimal_places=2) avgtemp_f = models.DecimalField(max_digits=5, decimal_places=2) maxwind_mph = models.DecimalField(max_digits=5, decimal_places=2) maxwind_kph = models.DecimalField(max_digits=5, decimal_places=2) totalprecip_mm = models.DecimalField(max_digits=5, decimal_places=2) totalprecip_in = models.DecimalField(max_digits=5, decimal_places=2) avgvis_km = models.DecimalField(max_digits=5, decimal_places=2) avgvis_miles = models.DecimalField(max_digits=5, decimal_places=2) avghumidity = models.IntegerField() daily_will_it_rain = models.IntegerField() daily_will_it_snow = models.IntegerField() daily_chance_of_rain = models.IntegerField() daily_chance_of_snow = models.IntegerField() uv = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return f"{self.location.name}, {self.date}" class Meta: verbose_name_plural = "daily forecasts" class HourlyForecast(Forecast): time_epoch = models.IntegerField() time = models.DateTimeField() temp_c = models.DecimalField(max_digits=5, decimal_places=2) temp_f = models.DecimalField(max_digits=5, decimal_places=2) is_day = models.BooleanField() text = models.CharField(max_length=255) icon = models.CharField(max_length=255) code = models.IntegerField() wind_mph = models.DecimalField(max_digits=5, decimal_places=2) wind_kph = models.DecimalField(max_digits=5, decimal_places=2) wind_degree = models.IntegerField() wind_dir = models.CharField(max_length=255) pressure_mb = models.DecimalField(max_digits=5, decimal_places=2) pressure_in = models.DecimalField(max_digits=5, decimal_places=2) precip_mm = models.DecimalField(max_digits=5, decimal_places=2) precip_in = models.DecimalField(max_digits=5, decimal_places=2) humidity = models.IntegerField() cloud = models.IntegerField() feelslike_c = models.DecimalField(max_digits=5, decimal_places=2) feelslike_f = models.DecimalField(max_digits=5, decimal_places=2) windchill_c = models.DecimalField(max_digits=5, decimal_places=2) windchill_f = models.DecimalField(max_digits=5, decimal_places=2) heatindex_c = models.DecimalField(max_digits=5, decimal_places=2) heatindex_f = models.DecimalField(max_digits=5, decimal_places=2) dewpoint_c = models.DecimalField(max_digits=5, decimal_places=2) dewpoint_f = models.DecimalField(max_digits=5, decimal_places=2) will_it_rain = models.IntegerField() will_it_snow = models.IntegerField() vis_km = models.DecimalField(max_digits=5, decimal_places=2) vis_miles = models.DecimalField(max_digits=5, decimal_places=2) chance_of_rain = models.IntegerField() chance_of_snow = models.IntegerField() gust_mph = models.DecimalField(max_digits=5, decimal_places=2) gust_kph = models.DecimalField(max_digits=5, decimal_places=2) uv = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return f"{self.location.name}, {self.time}" class Meta: verbose_name_plural = "hourly forecasts" [/code] [code]views.py: from datetime import date from django.shortcuts import get_object_or_404, render from django.views.generic import DetailView, ListView, TemplateView from .models import DailyForecast, HourlyForecast, Location class BaseView(TemplateView): template_name = "forecast/daily_forecast_detail.html" class LocationListView(ListView): model = Location template_name = "forecast/location_list.html" context_object_name = "locations" class DailyForecastDetailView(DetailView): model = DailyForecast template_name = "forecast/daily_forecast_detail.html" context_object_name = "forecast" def get_queryset(self): location_slug = self.kwargs["location_slug"] date = self.kwargs["date"] location = get_object_or_404(Location, slug=location_slug) return DailyForecast.objects.filter(location=location, date=date) class DailyForecastTodayView(DetailView): model = DailyForecast template_name = "forecast/daily_forecast_detail.html" context_object_name = "forecast" def get_queryset(self): location_slug = self.kwargs["location_slug"] location = get_object_or_404(Location, slug=location_slug) date_today = date.today() return DailyForecast.objects.filter(location=location, date=date_today) class HourlyForecastDetailView(DetailView): model = HourlyForecast template_name = "forecast/hourly_forecast_detail.html" context_object_name = "forecast" def get_queryset(self): location_slug = self.kwargs["location_slug"] date = self.kwargs["date"] hour = self.kwargs["hour"] location = get_object_or_404(Location, slug=location_slug) return HourlyForecast.objects.filter(location=location, date=date, hour=hour) [/code] [code]urls.py: from django.urls import path from .views import ( BaseView, DailyForecastDetailView, DailyForecastTodayView, HourlyForecastDetailView, LocationListView, ) app_name = "forecast" urlpatterns = [ # path("", LocationListView.as_view(), name="location_list"), path("//", DailyForecastDetailView.as_view(), name="daily_forecast_detail"), path("/", DailyForecastTodayView.as_view(), name="daily_forecast_today"), # path("", BaseView.as_view(), name="daily_forecast_detail"), path("///", HourlyForecastDetailView.as_view(), name="hourly_forecast_detail"), ] [/code] На моем локальном компьютере я получил доступ к следующему временному URL-адресу с датой (http://127.0.0.1:8000/forecast/narnia/2023-03-26/) и без параметра даты (http://127.0.0.1:8000/forecast/narnia/) и получаю сообщение об ошибке: Общий подробный вид DailyForecastDetailView необходимо вызывать либо с объектом pk, либо с фрагментом в URLconf Подробнее здесь: [url]https://stackoverflow.com/questions/75904853/django-generic-detail-view-dailyforecastdetailview-must-be-called-with-either[/url]