2👍
Thank you all so much for the fast reply (I did not expect that!) Sorry if I do not react to all comments but I appreciate every help.
I worked on it again and now understand that queryset returns a set and not a single model instance (for which I better use ‘get’). I changed as follows and now it works:
assignments_list.html
<a href="{% url 'assignment-detail' pk=assignment.teacher.pk pk1=assignment.pk %}">
views.py
class AssignmentDetailView(generic.DetailView):
model = Assignment
template_name = 'assignment_detail.html'
def get_object(self, **kwargs):
assignment = Assignment.objects.get(id=self.kwargs['pk1'])
return assignment
def get_context_data(self, **kwargs):
context = super(AssignmentDetailView, self).get_context_data(**kwargs)
context['teacher'] = Teacher.objects.get(id=self.kwargs['pk'])
return context
Now it works. I needed both pk numbers because the header on ‘assignment_detail.html’ is an {% include 'header-teacher.html' %}
that contains <a href="{% url 'teacher-profile' teacher.pk %}">
. Now I have passed two values from the url: pk1 for retrieving the correct assignment and pk to provide the (extra) correct context (that delivers the teacher pk).
0👍
Your view only returns a query set, not an actual object (which a detail view needs).
If you are just trying to get the assignment object you don’t even need to pass the teacher_id. On your first page you list all the assignments from a single teacher, you just need to pass the assignment.pk to the detail view.
path('assignment/<int:pk>/', views.AssignmentDetailView.as_view(), name='assignment-detail')
If you create your url like above, the detail view handles getting the object by the pk.
If you want to have the teacher id in your url you can still do that but call it something like <int:teacher_id>
. The detailview will by default only look for a ‘pk’ in the kwargs, so ignore the teacher_id
- [Django]-Access AppConfig members
- [Django]-Custom django-admin commands – AttributeError: 'Command' object has no attribute 'stdout'
- [Django]-Django: TemplateDoesNotExist at /