Cannot resolve keyword 'calendar_id' into field. Choices are: description, end_date, event, id, name, owner, owner_id, start_date
Here is the code where I define the Event and Calendar models:
class Calendar(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True, null=True)
start_date = models.DateField()
end_date = models.DateField()
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Event(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True, null=True)
date = models.DateField( )
start_time = models.TimeField() # Example default time
duration = models.DurationField() # Example default duration of 1 hour
calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE)
# owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
Here is the view I am trying to use:
class EventListView(LoginRequiredMixin, ListView):
model = Event
template_name = 'list.html'
context_object_name = 'EventListView'
def get_queryset(self):
calendar_id = self.kwargs['calendar_id']
return Calendar.objects.filter(calendar_id=calendar_id)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if not self.request.user.is_authenticated:
for event in context['EventListView']:
event.name = ''
return context
I have another similar view that looks like this, also using the calendar_id and this view works fine. I am not sure why the EventListView is showing this error.
class CalendarDetailView(DetailView):
model = Calendar
template_name = 'calendars/detail.html'
context_object_name = 'calendar'
pk_url_kwarg = 'calendar_id'
def get_queryset(self):
return Calendar.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
You used Calendar as model, not Event in the .get_queryset():
class EventListView(LoginRequiredMixin, ListView):
model = Event
template_name = 'list.html'
context_object_name = 'EventListView'
def get_queryset(self):
calendar_id = self.kwargs['calendar_id']
# 🖟 not Calendar
return Event.objects.filter(calendar_id=calendar_id)
It is probably however better to make a super() call, such that you can mix in additional filtering, etc.:
class EventListView(LoginRequiredMixin, ListView):
model = Event
template_name = 'list.html'
context_object_name = 'EventListView'
def get_queryset(self, *args, **kwargs):
return (
super()
.get_queryset(*args, **kwargs)
.filter(calendar_id=self.kwargs['calendar_id'])
)
Note: normally the context object names in a Django model are written in snake_case, not PascalCase, so it should be:
event_listinstead of.EventListView