python - 通用详细视图索引必须使用 URLconf 中的对象 pk 或 slug 调用
问题描述
我试图在一个有效的视图中拥有一种形式和一种模型。但是当我尝试保存表单时,我收到错误消息:必须使用 URLconf 中的对象 pk 或 slug 调用通用详细视图索引。
以下是我的观点和网址:
class Index(generic.CreateView):
template_name='home.html'
form_class=DistributionForm
models=Lecturer
queryset = Lecturer.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context ['lecturer_list'] = Lecturer.objects.order_by('lecturer')
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
网址.py
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
app_name='distribution'
urlpatterns=[
path('',views.Index.as_view(),name='home'),
path('hocalar/<slug:slug>/',views.LecturerDistribution.as_view(),name='lecturer_distribution'),
path('dersler/<slug:slug>/',views.LectureDistribution.as_view(),name='lecture_distribution'),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
编辑 这是我的另外两个观点
class LecturerDistribution(generic.DetailView):
model=Lecturer
template_name='lecturer.html'
def get_success_url(self):
return reverse('lecturer_distribution', kwargs={'slug': self.object.slug})
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context ['distribution'] = Distribution.objects.filter(lecturer=self.object).order_by('-created_on')
return context
class LectureDistribution(generic.DetailView):
model=Lecture
template_name='lecture.html'
def get_success_url(self):
return reverse('lecture_distribution', kwargs={'slug': self.object.slug})
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context ['distribution_'] = Distribution.objects.filter(lecture=self.object).order_by('-created_on')
return context
这里是我的模板
{% extends "base.html" %}
{%block content%}
{% load crispy_forms_tags %}
<div class="container">
<div class="form-group pull-right">
<input type="text" class="search form-control" placeholder="Ara">
</div>
<span class="counter pull-right"></span>
<table class="table table-hover results">
<thead>
<tr>
<th >Hoca</th>
<th >Ders</th>
</tr>
<tr class="warning no-result">
<td><i class="fa fa-warning"></i> Sonuç Yok</td>
</tr>
</thead>
<tbody>
{%for lec in lecturer_list%}
<tr>
<td>
<p ><a style="text-decoration:none" href="{% url 'distribution:lecturer_distribution' slug=lec.slug%}">{{lec.lecturer}}</a></p>
</td>
<td>
{%for ders in lec.lecture.all%}
<a style="text-decoration:none" href="{% url 'distribution:lecture_distribution' slug=ders.slug%}">{{ders.lecture}}</a>,
{% endfor%}
</td>
</tr>
{%endfor%}
</tbody>
</table>
</div>
<div class="col-md-2 float-right ">
<button style= "position: fixed; top:175px; " type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Add New Distribution</button>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New Distribution</h5>
</div>
<div class="modal-body">
<form method="post" style="margin-top: 1.3em;">
{% csrf_token %}
{{ form|crispy }}
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="submit" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
<style >
body{
padding:20px 20px;
}
.results tr[visible='false'],
.no-result{
display:none;
}
.results tr[visible='true']{
display:table-row;
}
.counter{
padding:8px;
color:#ccc;
}
</style>
<script>
$(document).ready(function() {
$(".search").keyup(function () {
var searchTerm = $(".search").val();
var listItem = $('.results tbody').children('tr');
var searchSplit = searchTerm.replace(/ /g, "'):containsi('")
$.extend($.expr[':'], {'containsi': function(elem, i, match, array){
return (elem.textContent || elem.innerText || '').toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
$(".results tbody tr").not(":containsi('" + searchSplit + "')").each(function(e){
$(this).attr('visible','false');
});
$(".results tbody tr:containsi('" + searchSplit + "')").each(function(e){
$(this).attr('visible','true');
});
var jobCount = $('.results tbody tr[visible="true"]').length;
if(jobCount == '0') {$('.no-result').show();}
else {$('.no-result').hide();}
});
});
</script>
{% endblock content%}
先感谢您
解决方案
我想我发现了你的问题,因为你在索引视图的 post 函数中使用了 get_object() 。
见代码:
def get_object(self, queryset=None):
"""
Return the object the view is displaying.
Require `self.queryset` and a `pk` or `slug` argument in the URLconf.
Subclasses can override this to return any object.
"""
# Use a custom queryset if provided; this is required for subclasses
# like DateDetailView
if queryset is None:
queryset = self.get_queryset()
# Next, try looking up by primary key.
pk = self.kwargs.get(self.pk_url_kwarg)
slug = self.kwargs.get(self.slug_url_kwarg)
if pk is not None:
queryset = queryset.filter(pk=pk)
# Next, try looking up by slug.
if slug is not None and (pk is None or self.query_pk_and_slug):
slug_field = self.get_slug_field()
queryset = queryset.filter(**{slug_field: slug})
# If none of those are defined, it's an error.
if pk is None and slug is None:
raise AttributeError(
"Generic detail view %s must be called with either an object "
"pk or a slug in the URLconf." % self.__class__.__name__
)
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except queryset.model.DoesNotExist:
raise Http404(_("No %(verbose_name)s found matching the query") %
这是 get_object() 的代码,因为您没有 pk 也没有可用的 slug。它返回通用详细视图错误。
raise AttributeError(
"Generic detail view %s must be called with either an object "
"pk or a slug in the URLconf." % self.__class__.__name__
)
您可以在索引视图中删除 def 帖子,因为您正在使用的 form_valid() 已经在创建视图中。你不需要它。
推荐阅读
- oracle-apex - Oracle Apex 19 Web 源模块:获取返回 JSON 对象中的列表
- sphinx - 如何设置实时索引属性类型
- sql - 查询优化,问题
- excel - 在 UserForm.Show 上显示文本框滚动到顶部而没有突出显示的文本
- spring - Request Body with Content-Type: application/x-www-form-urlencoded;charset=UTF-8 Not working
- c++ - 使用宏初始化具有额外元素的数组
- javascript - 动态添加的 noscript 标记未显示在查看源页面 Angular Universal 中
- python - 在 Jupyter Notebook 中使用 Python 虚拟环境
- google-apps-script - How do I paste format with google sheets script?
- matlab - Is Simulink build something like .exe from our model?