获取基于主键的数据并在html中显示

时间:2018-03-15 10:11:52

标签: django django-models django-forms django-templates django-views

我正在尝试基于主键获取数据并在html页面中显示EDIT。但我收到'QuerySet' object has no attribute '_meta'错误。 我试着通过查看其他帖子来解决它,但无法这样做..希望有人会帮助解决问题。

我的表格:

class StudentForm(forms.ModelForm): class Meta: model = Student fields = ('stuName','stuCity','stuPhone','stuNationality','stuCreatedt') class CourseForm(forms.ModelForm): class Meta: model = Course fields = ('courseId','courseName','enrolledStu','students','dept') class DeptForm(forms.ModelForm): class Meta: model = Dept fields = ('deptId','deptName')

Models.py

class Student(models.Model):
 stuName = models.CharField(max_length=100)
 stuCity = models.CharField(max_length=100)
 stuPhone = models.IntegerField(max_length=10)
 stuNationality = models.CharField(max_length=50)
 stuCreatedt = models.DateTimeField(default=timezone.now)
 def __str__(self):
     return '%s %s %s' % (self.stuName,self.stuCity,self.stuNationality)

班级部门:

class Dept(models.Model):
 deptId = models.AutoField(primary_key=True)
 deptName = models.CharField(max_length=100)
 def __str__(self):
      return '%s %s' % (self.deptId, self.deptName)

课程

class Course(models.Model):
 courseId = models.AutoField(primary_key=True)
 courseName = models.CharField(max_length=100)
 enrolledStu = models.IntegerField(max_length=3)
 students = models.ManyToManyField(Student)
 dept = models.ForeignKey(Dept, on_delete=models.CASCADE)
 def __str__(self):
      return '%s %s %s %s' % (self.courseName,self.enrolledStu,self.students,self.dept)

用于编辑的urls.py是

url(r' ^ stuApp /(?P \ d +)/ $',views.edtStudent,name =' edtStudent'),

在view.py中编辑的方法是:

def edtStudent(request,pk):
course = Course.objects.filter(pk=1).prefetch_related('students').select_related('dept')
if request.method =="POST":
    form = CourseForm(request.POST,instance=Course)
    if form.is_valid():
       course = form.save(commit=False)
       course.courseName = request.POST['courseName']
       course.enrolledStu = request.Post['enrolledStu']
       course.save()
       course.save_m2m()
       return redirect('liststudent')
else:

    #form = CourseForm()
    #return render(request, 'stuApp/edtStudent.html', {'form':form})
    form = CourseForm(instance=course)
    return render_to_response('edtStudent.html', {'form': form})

Html是:

<form method="POST" class="post-form">{% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="save btn btn-default">Save</button>
</form>

它显示来自else的日志,但不知何故在html上没有显示任何内容..

谢谢你的时间......

1 个答案:

答案 0 :(得分:1)

filter始终返回一个查询集。但是您需要将模型实例而不是查询集传递给表单。请改用get

course = Course.objects.filter(pk=1).prefetch_related('students').select_related('dept').get()