MainList缺少QuerySet定义MainList.model,MainList.queryset或覆盖MainList.get_queryset

如何解决MainList缺少QuerySet定义MainList.model,MainList.queryset或覆盖MainList.get_queryset

您好,我正在尝试创建一个主页,可以在其中从名为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(如果您不在其他地方使用它),只有在这种情况下,您才不需要为类定义查询集。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?