【发布时间】:2021-05-30 08:31:47
【问题描述】:
我正在尝试将基于功能的视图转换为基于类的视图,但使用此功能遇到了困难。
@login_required(login_url=settings.LOGIN_URL)
def list_bugs_view(request, id):
queryset = Bug.objects.filter(project=id)
project = Project.objects.filter(id=id)
context = {
'bug_list': queryset,
'project': project
}
return render(request, 'bugs/bug_list.html', context)
{% extends 'base.html' %}
<-- bug_list.html -->
{% block content %}
<h1>{{ project.name }}</h1>
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col">Bug ID</th>
<th scope="col">Name</th>
<th scope="col">Status</th>
<th scope="col">Severity</th>
<th scope="col">Creator</th>
<th scope="col">Created</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for bug in bug_list %}
<tr>
<th scope="row">{{ bug.id }}</th>
<td>{{ bug.name }}</td>
<td>{{ bug.status }}</td>
<td>{{ bug.severity }}</td>
<td>{{ bug.bug_creator }}</td>
<td>{{ bug.bug_created }}</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
我已经使用 generic.ListView 来转换另一个基于函数的视图,但不知道如何按从以下项目接收 id 的项目过滤错误:
# Class based view responsible for creating a project.
class ProjectCreateView(LoginRequiredMixin, CreateView):
model = Project
template_name = 'projects/project_create.html'
form_class = ProjectForm
success_url = '/projects/create'
# This come from LoginRequiredMixin
# Redirects page to LOGIN_URL page (the value of which is set in settings.py) when the user tires accessing the projects/project_create page but is not logged in.
login_url = settings.LOGIN_URL
def form_valid(self, form):
return super().form_valid(form)
def get_success_url(self):
return reverse('projects:project_list')
project_list.html
{% extends 'base.html' %}
{% block content %}
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col">Project ID</th>
<th scope="col">Name</th>
<th scope="col">Created</th>
<th scope="col">Creator</th>
<th class="text-center" scope="col">Bugs</th>
<th class="text-center" scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for project in project_list %}
<tr>
<th scope="row">{{ project.id }}</th>
<td>{{ project.name }}</td>
<td>{{ project.project_created }}</td>
<td>{{ project.project_creator }}</td>
<td class="text-center"><a class="btn btn-primary" href="{% url 'bugs:bug_list' project.id %}">View</a></td>
<td class="text-center">
<a class="btn btn-info" href="{% url 'projects:project_detail' project.id %}">Details</a>
<a class="btn btn-primary" href="{% url 'projects:project_update' project.id %}">Update</a>
<a class="btn btn-danger" href="{% url 'projects:project_delete' project.id %}">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
我真的很难理解如何让这项工作像其他人一样工作。
【问题讨论】:
标签: python django django-class-based-views