简体   繁体   中英

Wagtail error new models.CharField in models.py

I hope you're all well:) Could you please help me. I'm a beginner. I'm launching a new website with python and I choose wagtail for the CMS. I'd like to change the model of each blog_page in order to have more information on it. But I'm running into some issues:(

Everything was working with this code (blog/models.py):

from django.db import models   
from django import forms

from modelcluster.fields import ParentalKey, ParentalManyToManyField
from wagtail.core.models import Page, Orderable
from wagtail.core.fields import RichTextField, StreamField
from wagtail.core import blocks
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel, TabbedInterface, ObjectList, StreamFieldPanel
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.images.blocks import ImageChooserBlock
from wagtail.search import index

from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.models import TaggedItemBase

from wagtail.snippets.models import register_snippet

class BlogIndexPage(Page):
    intro = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('intro', classname="full")
    ]


class BlogPageTag(TaggedItemBase):
    content_object = ParentalKey(
        'BlogPage',
        related_name='tagged_items',
        on_delete=models.CASCADE
    )



class BlogPage(Page):
    date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)
    recette = RichTextField(blank=True)
    aliment = RichTextField(blank=True)
    forcealiment = RichTextField(blank=True)
    tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
    categories = ParentalManyToManyField('blog.BlogCategory', blank=True)

    def main_image(self):
        gallery_item = self.gallery_images.first()
        if gallery_item:
            return gallery_item.image
        else:
            return None

    search_fields = Page.search_fields + [
        index.SearchField('intro'),
        index.SearchField('body'),
        index.SearchField('recette'),
        index.SearchField('aliment'),
        index.SearchField('forcealiment'),
    ]

    content_panels = Page.content_panels + [
        MultiFieldPanel([
            FieldPanel('date'),
            FieldPanel('tags'),
            FieldPanel('categories', widget=forms.CheckboxSelectMultiple),
        ], heading="Blog information"),
        FieldPanel('intro'),
        FieldPanel('body'),
        FieldPanel('recette'),
        FieldPanel('aliment'),
        FieldPanel('forcealiment'),
        InlinePanel('gallery_images', label="Gallery images"),
    ]


class BlogPageGalleryImage(Orderable):
    page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='gallery_images')
    image = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.CASCADE, related_name='+'
    )
    caption = models.CharField(blank=True, max_length=250)

    panels = [
        ImageChooserPanel('image'),
        FieldPanel('caption'),
    ]


class BlogTagIndexPage(Page):

    def get_context(self, request):

        # Filter by tag
        tag = request.GET.get('tag')
        blogpages = BlogPage.objects.filter(tags__name=tag)

        # Update template context
        context = super().get_context(request)
        context['blogpages'] = blogpages
        return context

@register_snippet
class BlogCategory(models.Model):
    name = models.CharField(max_length=255)
    icon = models.ForeignKey(
        'wagtailimages.Image', null=True, blank=True,
        on_delete=models.SET_NULL, related_name='+'
    )

    panels = [
        FieldPanel('name'),
        ImageChooserPanel('icon'),
    ]

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'blog categories'

But when I try to add a new field 'cooker' like

cooker = models.CharField(max_length=250)

First stel is okay:

(monProjetWagtail:3.7)[dulo0814@louisiane monProjetWagtail]$ python manage.py makemigrations
Migrations for 'blog':
  blog/migrations/0018_auto_20200522_1106.py
    - Remove field autobio from blogpage
    - Add field cooker to blogpage

Second step is not okay:(

(monProjetWagtail:3.7)[dulo0814@louisiane monProjetWagtail]$ python manage.py migrate
System check identified some issues:

WARNINGS:
?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'
        HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/3.0/ref/databases/#mysql-sql-mode
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, home, sessions, taggit, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers
Running migrations:
  Applying blog.0013_blogpage_autorpost...Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
    output = self.handle(*args, **options)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 233, in handle
    fake_initial=fake_initial,
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, inmigrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in_migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, inapply_migration
    state = migration.apply(state, schema_editor)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards
    field,
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/db/backends/mysql/schema.py", line 80, in add_field
    super().add_field(model, field)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 450, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 223, in column_sql
    default_value = self.effective_default(field)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 303, in effective_default
    return field.get_db_prep_save(self._effective_default(field), self.connection)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 821,in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 816,in get_db_prep_value
    value = self.get_prep_value(value)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/wagtail/core/fields.py", line 111, in get_prep_value
    return json.dumps(self.stream_block.get_prep_value(value), cls=DjangoJSONEncoder)
  File "/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages/wagtail/core/blocks/stream_block.py", line 260,in get_prep_value
    return value.get_prep_value()
AttributeError: 'datetime.datetime' object has no attribute 'get_prep_value'
(monProjetWagtail:3.7)[dulo0814@louisiane monProjetWagtail]$

Can someone help me please:)?

Ps: I'm french

The error message shows that the error is on the migration 0013_blogpage_autorpost , not the 0018_auto_20200522_1106 migration you just created. Presumably you weren't running ./manage.py migrate after every makemigrations step (or you would have seen this error earlier).

The error is referring to a StreamField - it looks like you had a datetime object where there should have been a block. As there aren't any StreamFields in your models now, I guess this is a field that you added and subsequently removed (but it's still part of the migration history). My recommendation would be to delete all of the migration files in blog/migrations numbered 0013 and above, and then re-run ./manage.py makemigrations so that you have a new migration sequence without that error. (Normally, deleting migrations isn't a good idea, as it means that your database might end up in a state that doesn't match the code - but in this case I believe it should be safe, as the migrations from 0013 onward haven't been run yet.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM