问题描述
您好,我正在尝试创建一个主页,可以在其中从名为Lecturer的模型中列出并从名为distributionForm的模型中创建表单。我用CreateView尝试过,但出现错误 MainList缺少QuerySet。定义MainList.model,MainList.queryset或覆盖MainList.get_queryset()。 缺少查询集。你能帮我吗?
Views.py
class MainList(generic.CreateView):
template_name='home.html'
form=distributionForm
models=Lecturer
fields=['distribution','semester','lecture','lecturer']
success_url = "/home"
def form_valid(self,form):
form.instance.author=self.request.user
return super().form_valid(form)
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context ['lecturer_list'] = Lecturer.objects.order_by('lecturer')
return context
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('home/',views.MainList.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)
和我的home.html
{% 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%}
编辑
class MainList(generic.CreateView):
template_name='home.html'
model=distribution
fields=['distribution',**kwargs):
context = super().get_context_data(**kwargs)
context ['lecturer_list'] = Lecturer.objects.order_by('lecturer')
return context
解决方法
我认为将类属性作为queryset = Lecturer.objects.all()
添加到MainList
(或基于Lecturer
模型的任何查询集)或定义一个get_queryset
方法,例如以下代码:
class MainList(generic.CreateView):
template_name='home.html'
form=DistributionForm
models=Lecturer
fields=['distribution','semester','lecture','lecturer']
success_url = "/home"
def get_queryset(self):
return Lecturer.objects.all()
def form_valid(self,form):
form.instance.author=self.request.user
return super().form_valid(form)
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context ['lecturer_list'] = Lecturer.objects.order_by('lecturer')
return context
将解决您的问题。另一种方法是将类属性中的models=Lecturer
更改为model=Lecturer
(如果您不在其他地方使用它),只有在这种情况下,您才不需要为类定义查询集。