问题描述
我正在尝试在一种视图中使用一种表单和一种模型。但是,当我尝试保存表单时,收到错误消息:一般详细视图索引必须使用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)
urls.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):
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且没有可用的子弹。它返回通用详细视图错误。
raise AttributeError(
"Generic detail view %s must be called with either an object "
"pk or a slug in the URLconf." % self.__class__.__name__
)
您可以在索引视图中删除def post,因为您正在使用的form_valid()已经在create视图中。您不需要它。
,尝试将success_url
添加到您的CreateView中,以将您重定向到首页
from django.core.urlresolvers import reverse_lazy
class Index(generic.CreateView):
template_name='home.html'
form_class=DistributionForm
models=Lecturer
queryset = Lecturer.objects.all()
success_url = reverse_lazy('home')
否则,它将把您重定向到模型的get_absolute_url
路径