/ startup / a-new-startup /的OperationalError;没有这样的专栏:organizer_newslink.slug

时间:2016-05-04 14:13:59

标签: python django

我正在练习Django-unleashed的书中的代码。完成第10章后,主要是数据迁移和模式迁移,当我尝试创建新的启动时,它给出了

  在/ startup / a-new-startup /

OperationalError       没有这样的专栏:organizer_newslink.slug。

我正在使用:     Django版本:1.9.5,Python 3.4.3和Win7。

In template f:\projects\env\django-unleash\organizer\templates\organizer\startup_detail.html, error at line 38
no such column: organizer_newslink.slug
28          {% for tag in startup.tags.all %}
29            <dd><a href="{{ tag.get_absolute_url }}">
30              {{ tag.name|title }}
31            </a></dd>
32          {% endfor %}
33  
34    </dl>
35  
36    {{ startup.description|linebreaks }}
37  
38        **{% if startup.newslink_set.all %}**
39            <section>
40              <h3>Recent News</h3>
41                <p>
42                  <a href="{% url 'organizer_newslink_create' %}">
43                    Add Article</a></p>
44              <ul>
45                {% for newslink in startup.newslink_set.all %}
46                  <li>
47                    <a href="{{ newslink.link }}">
48                      {{ newslink.title|title }}</a>

它还说&#34;上述异常(没有这样的列:organizer_newslink.slug)是以下异常的直接原因: ... startup_detail中的f:\ projects \ env \ django-unleash \ organizer \ views.py         {&#39; startup&#39 ;: startup}) ...&#34;  为了您的信息,当我创建新的帖子/博客时,它正常工作。

更新: 我的模特是:

from django.core.urlresolvers import reverse
from django.db import models

class Tag(models.Model):
    name = models.CharField(
        max_length=31, unique=True)
    slug = models.SlugField(
        max_length=31,
        unique=True,
        help_text='A label for URL config.')

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name.title()

    def get_absolute_url(self):
        return reverse('organizer_tag_detail',
                       kwargs={'slug': self.slug})

    def get_delete_url(self):
        return reverse('organizer_tag_delete',
                       kwargs={'slug': self.slug})

    def get_update_url(self):
        return reverse('organizer_tag_update',
                       kwargs={'slug': self.slug})

class Startup(models.Model):
    name = models.CharField(
        max_length=31, db_index=True)
    slug = models.SlugField(
        max_length=31,
        unique=True,
        help_text='A label for URL config.')
    description = models.TextField()
    founded_date = models.DateField(
        'date founded')
    contact = models.EmailField()
    website = models.URLField(max_length=255)
    tags = models.ManyToManyField(Tag, blank=True)

    class Meta:
        ordering = ['name']
        get_latest_by = 'founded_date'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('organizer_startup_detail',
                       kwargs={'slug': self.slug})

    def get_delete_url(self):
        return reverse('organizer_startup_delete',
                       kwargs={'slug': self.slug})

    def get_update_url(self):
        return reverse('organizer_startup_update',
                       kwargs={'slug': self.slug})


class NewsLink(models.Model):
    title = models.CharField(max_length=63)
    slug = models.SlugField(max_length=63)
    pub_date = models.DateField('date published')
    link = models.URLField(max_length=255)
    startup = models.ForeignKey(Startup)

    class Meta:
        verbose_name = 'news article'
        ordering = ['-pub_date']
        get_latest_by = 'pub_date'
        unique_together = ('slug', 'startup')

    def __str__(self):
        return "{}: {}".format(
            self.startup, self.title)

    def get_absolute_url(self):
        return self.startup.get_absolute_url()

    def get_delete_url(self):
        return reverse(
            'organizer_newslink_delete',
            kwargs={'pk': self.pk})

    def get_update_url(self):
        return reverse(
            'organizer_newslink_update',
            kwargs={'pk': self.pk})

每当我改变模型时,我也都做过移动。这是我的迁移文件包含:

0004_newslink_data.py:

from __future__ import unicode_literals
from datetime import date
from django.db import migrations, models

NEWSLINKS = [
    {
        "title": "Redundant Homepage Link",
        "link": "http://jambonsw.com",
        "pub_date": date(2013, 1, 18),
        "startup": 'jambon-software',
    },
    {
        "title": "Monkey (Wikipedia)",
        "link": "https://en.wikipedia.org/wiki/Monkey",
        "pub_date": date(2012, 7, 22),
        "startup": "monkey-software",
    },
    {
        "title": "William Shakespeare (Wikipedia)",
        "link": "https://en.wikipedia.org/wiki/William_Shakespeare",
        "pub_date": date(2014, 4, 26),
        "startup": "monkey-software",
    },
]


def add_newslink_data(apps, schema_editor):
    NewsLink = apps.get_model(
        'organizer', 'NewsLink')
    Startup = apps.get_model(
        'organizer', 'Startup')
    for newslink_dict in NEWSLINKS:
        newslink = NewsLink.objects.create(
            title=newslink_dict['title'],
            link=newslink_dict['link'],
            pub_date=newslink_dict['pub_date'],
            startup=Startup.objects.get(
                slug=newslink_dict['startup']))


def remove_newslink_data(apps, schema_editor):
    NewsLink = apps.get_model(
        'organizer', 'NewsLink')
    Startup = apps.get_model(
        'organizer', 'Startup')
    for newslink_dict in NEWSLINKS:
        newslink = NewsLink.objects.get(
            title=newslink_dict['title'],
            link=newslink_dict['link'],
            pub_date=newslink_dict['pub_date'],
            startup=Startup.objects.get(
                slug=newslink_dict['startup']),
        )
        newslink.delete()


class Migration(migrations.Migration):

    dependencies = [
        ('organizer', '0003_startup_data'),
    ]

    operations = [
        migrations.RunPython(
            add_newslink_data,
            remove_newslink_data)
    ]

0005_newslink_slug.py:

from __future__ import unicode_literals
from django.db import migrations, models
from django.utils.text import slugify

SLUG_LENGTH = 63


def add_slug_data(apps, schema_editor):
    NewsLink = apps.get_model(
        'organizer', 'NewsLink')
    query = NewsLink.objects.all()
    for newslink in query:
        expected_slug = slugify(newslink.title)
        rivals = (
            NewsLink.objects.filter(
                startup=newslink.startup,
                slug__startswith=expected_slug
            ).count())
        if rivals > 0:
            str_len = (
                SLUG_LENGTH - len(str(rivals)))
            newslink.slug = "{}-{}".format(
                expected_slug[:str_len - 1],
                rivals + 1)
        else:
            newslink.slug = expected_slug
        newslink.save()


def remove_slug_data(apps, schema_editor):
    NewsLink = apps.get_model(
        'organizer', 'NewsLink')
    NewsLink.objects.update(slug='')


class Migration(migrations.Migration):

    dependencies = [
        ('organizer', '0004_newslink_data'),
    ]

    operations = [
        migrations.AddField(
            model_name='newslink',
            name='slug',
            field=models.SlugField(
                max_length=SLUG_LENGTH,
                default=''),
        ),
        migrations.RunPython(
            add_slug_data,
            reverse_code=remove_slug_data
        ),
        migrations.AlterField(
            model_name='newslink',
            name='slug',
            field=models.SlugField(
                max_length=SLUG_LENGTH),
        ),
    ]

0006_newslink_unique_together_slug.py:

from __future__ import unicode_literals
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('organizer', '0005_newslink_slug'),
    ]

    operations = [
        migrations.AlterUniqueTogether(
            name='newslink',
            unique_together=set([('slug', 'startup')]),
        ),
    ]

为方便起见,我添加了我的github代码库,但不幸的是它已从问题中删除了。我希望现在很清楚问题出在哪里。

1 个答案:

答案 0 :(得分:0)

我不知道你的模型,但你在模板中使用的是错误的。

{% if startup.newslink_set.all %}

通过这个你可能想得到一组对象,但是在模板中以这种方式调用它是不对的。

你应该做的就是在这样的观点中调用它:

data = startup.newslink_set.all()

然后在渲染模板时传递参数中的数据。

然后使用

{% if data %} 
模板中的

类似地

{% for d in data %}
    do something
{% endfor %}