__str__返回非字符串(类型NoneType)

时间:2017-09-21 11:00:52

标签: django django-models django-views

当我尝试在课程中保存一个步骤时,我收到一个错误 str 返回非字符串(类型NoneType)

  

您可以使用以下网址下载截图

step page details

当我尝试保存时:

error page

我的代码是

网址格式:

urlpatterns = [
    url(r'^$', views.course_list),
    url(r'(?P<pk>\d+)/(?P<pk>\d+)/$', views.step_details),  
    url(r'(?P<pk>\d+)/$', views.course_details),
]

models.py:

class Course(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=255)
    description = models.TextField()

    def __str__(self):
        return self.title

    class Step(models.Model):
        title = models.CharField(max_length = 255)
        description = models.TextField()
        order = models.IntegerField(default=0)
        course = models.ForeignKey(Course)

        class Meta:
            ordering = ['order', ]


        def __str__(self):
            self.title

views.py:

def step_details(request, course_pk, step_pk):
    step = get_object_or_404(Step, course_id = course_pk, pk=step_pk)
    return render(request, 'courses/step_details.html', {'step':step})

step_details.html:

{% extends "layout.html"%}


{% block title%} {{step.title}} - {{ step.course.title }} {% endblock title %}

{% block content %}
<article>
<h2> {{ step.course.title }} </h2>
{{ step.description }}
{{ step.content|linebreaks }}
{{ step.course.created_at }}

{##}
{#    <section>#}
{#      {% for step in course.step_set.all %}#}
{#        <h3> {{ step.title}}</h3>#}
{#      {{step.description}}#}
{#      {% endfor %}#}
{#    </section>#}
 </article>
{% endblock %}

谢谢...

1 个答案:

答案 0 :(得分:3)

你的缩进是错的,你在课堂上写了一个课

class Course(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=255)
    description = models.TextField()

    def __str__(self):
        return self.title

class Step(models.Model):
   title = models.CharField(max_length = 255)
   description = models.TextField()
   order = models.IntegerField(default=0)
   course = models.ForeignKey(Course)

   class Meta:
      ordering = ['order', ]


   def __str__(self):
      return self.title