我正在尝试使用Django 1.11和python为我的工作设置一些东西,它将显示登录用户提交的项目列表。用户可以单击项目名称,如果需要,用户将转到该项目进行编辑。我有它显示项目列表但是当用户点击名称时我得到一个错误。当只有一个项目显示给该用户时,它工作正常。错误和我的代码如下。
MultipleObjectsReturned at / edit /
get()返回多个Project - 它返回2!
请求方法:GET
请求网址:http://127.0.0.1:8000/edit/
Django版本:1.11
异常类型:MultipleObjectsReturned
例外价值:
get()返回多个Project - 它返回2!
url.py
urlpatterns = [
url(r'^index/',views.Index.as_view(),name='index'),
url(r'^form/', views.Form.as_view(), name = 'form'),
url(r'^edit/', views.EditProject.as_view(), name = 'editProject'),
]
views.py
class Index(LoginRequiredMixin,ListView):
template_name = 'sitename/index.html'
form_class = IndexForm
def get_queryset(self):
return Project.objects.filter(user=self.request.user)
class EditProject(LoginRequiredMixin, UpdateView):
template_name = 'irbSite/form.html'
form_class = ProjectForm
success_url = reverse_lazy('irbSite:index')
# works only when there is 1 project object
def get_object(self):
return Project.objects.get(user=self.request.user)
的index.html
{% if user.is_authenticated %}
{% if project_list %}
<tr>
<th>Project Number</th>
<th>Project Name</th>
<th>Is Complete</th>
<th>Is Approved</th>
</tr>
{% for project in project_list %}
<tr>
<td><a href="{% url 'irbSite:editProject'%}">{{project.project_id}}</td>
<td>{{project.project_name}}</a></td>
<td>{{project.is_complete}}</td>
<td>{{project.is_approved}}</td>
{% endfor %}
</tr>
{% else %}
<p>You dont have any current IRB forms. Select "Submit New Project" on the left to start one.<p>
答案 0 :(得分:0)
在查询时使用.filter
获取多个对象。
<强>实施例强>
def get_object(self):
return Project.objects.filter(user=self.request.user)