Template file not created after adding Page Class to models.py - wagtail

So I'm trying to get started with Wagtail, following the 10 minute guide but I'm having a problem creating A basic blog.
So after modifying blog/models.py:
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel
class BlogIndexPage(Page):
intro = RichTextField(blank=True)
content_panels = Page.content_panels + [
FieldPanel('intro', classname="full")
]
And running makemigrations and migrate:
$ python manage.py makemigrations
Migrations for 'blog':
blog/migrations/0001_initial.py:
- Create model BlogIndexPage
$ python manage.py migrate
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.0001_initial... OK
The default template (blog/templates/blog/blog_index_page.html) is nowhere to be found. From what I understand, this file should be created automatically:
Since the model is called BlogIndexPage, the default template name (unless we override it) will be blog/templates/blog/blog_index_page.html:
Or perhaps I'm missing something?
Wagtail uses normal Django templates to render each page type. It automatically generates a template filename from the model name by separating capital letters with underscores (e.g. HomePage becomes home_page.html)

This is the expected behaviour. The template file / directory isn't created automatically on creating the page model - you have to add it yourself.

Related

Wagtail many-to-many links between different Page models

Does anyone have or know of a recipe (sample code and/or instructions) on setting up many-to-many relationships between different Page models? If I have PersonPage and SitePage models, how do I connect the pages (a person can work at multiple sites and a site can have multiple people working there)?
Here's what I've found related to, but not directly on, this topic—
Wagtail docs: from a search for "many-to-many" the only hit is in the section on the taggit module (Recipes page).
Wagtail docs: the only reference to the ParentalManyToManyField is a demo of how it can be used to create M2Ms between pages and categories (Tutorial)
This 2015 post on M2M relationships in Wagtail (it's referenced in an SO 'answer' to basically the same question I'm asking here). Although it doesn't discuss page-page relationships the approach presented might be adapted to work. My modified imitation failed with various errors depending on how I tried to set up the InlinePanel call — but the sample code from the post fails in just the same ways, so either it wasn't tested or it's been made obsolete in 2.x.
class PersonPage(Page):
pass
PersonPage.content_panels = [
InlinePanel('ps_links', label='PS Links'),
]
class PersonSitePageLink():
spage = models.ForeignKey('SitePage', on_delete=models.SET_NULL, related_name='sites')
ppage = ParentalKey('PersonPage', related_name='ps_links', on_delete=models.SET_NULL,)
panels = [
FieldPanel('spage')
]
class SitePage(Page):
pass
This technique works fine for relating a Page model to itself, but expanding it to encompass two distinct models creates two parallel but unconnected sets of relationships (you can pick arbitrary Bug pages to link to any Plant page, or vice versa, but the Plants you picked don't show when you edit Bugs). I see why in the code, I think, but I don't see how to make a single M2M connection between the two pages.
class PlantPage(Page):
related_bugs = ParentalManyToManyField('BugPage', blank=True)
content_panels = Page.content_panels + [
FieldPanel('related_bugs'),
]
class BugPage(Page):
related_plants = ParentalManyToManyField('PlantPage', blank=True)
content_panels = Page.content_panels + [
FieldPanel('related_plants'),
]
This one also only talks about intra-page model (rather than inter-page model) M2Ms. (It is pre-ParentalManyToManyField and in fact only available from the Wayback Machine.)
I hope this helps, I took inspiration from this article about moving from ParentalManyToManyField to a central model that 'links' each page from this AccordBox article.
It turns out that InlinePanel does not fully support ParentalManyToManyField, hence the issues you were running into.
I was able to implement a refined approach to your option one above and it should solve your problem.
A reminder that all Page models already extend ClusterableModel so there is no need to add that to any models you create.
Overview
Create a new 'relation' that extends models.Model which will be the relation between these two page models.
Each field within this new model will be the two page types via the model-cluster ParentalKey each with a logical related_name set that is the OTHER side of the relationship.
No need to set panels on this model as we will declare the panels individually via the panels kwarg to InlinePanel - see the InlinePanel docs.
Finally, each individual Page's content_panels has an InlinePanel added that refers to the central relation model indirectly via that model's related_name, adding the other side reference to PageChooserPanel.
Example Code
from modelcluster.fields import ParentalKey
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, PageChooserPanel
class PersonPageSitePageRelation(models.Model):
person = ParentalKey('app.PersonPage', on_delete=models.CASCADE, related_name='sites')
site = ParentalKey('app.SitePage', on_delete=models.CASCADE, related_name='people')
# Optional: some additional fields (e.g. 'note') for this relation
# Important: NOT setting any `panels` here, will be set individually for each 'direction'
class Meta:
unique_together = ('person', 'site')
class PersonPage(Page):
# ... fields (note: `sites` does NOT need to be declared as a field)
# Now we add an `InlinePanel` that will connect to the parental connection to PersonPageSitePageRelation via the related name `sites`, but the panels available will be the PersonPageSitePageRelation's field `site`
content_panels = Page.content_panels + [
# ... other FieldPanel etc
InlinePanel('sites', label='Related Sites', [PageChooserPanel('site')]),
]
class SitePage(Page):
# ... fields (note: `people` does NOT need to be declared as a field)
# Now we add an `InlinePanel` that will connect to the parental connection to PersonPageSitePageRelation via the related name `people`, but the panels available will be the PersonPageSitePageRelation's field `person`
content_panels = Page.content_panels + [
# ... other FieldPanel etc
InlinePanel('people', label='Related People', panels=[PageChooserPanel('person')]),
]
Further Reading
Read about Django Modelcluster - which is the library that ParentalKey comes from.

How to manage third party app migrations with custom WAGTAILIMAGES_IMAGE_MODEL

Situation
I have a custom image and rendition model, and have followed the wagtail v2.4 guide to implement them:
class AccreditedImage(AbstractImage):
"""
AccreditedImage - Customised image model with optional caption and accreditation
"""
caption = models.CharField(max_length=255, blank=True)
accreditation = models.CharField(max_length=255, blank=True, null=True)
admin_form_fields = Image.admin_form_fields + (
'caption',
'accreditation',
)
class Meta:
verbose_name = 'Accredited image'
verbose_name_plural = 'Accredited images'
def __str__(self):
credit = ' ({})'.format(self.accreditation) if (self.accreditation is not None) and (len(self.accreditation) > 0) else ''
return '{}{}'.format(self.title, credit)
class AccreditedRendition(AbstractRendition):
"""
AccreditedRendition - stores renditions for the AccreditedImage model
"""
image = models.ForeignKey(AccreditedImage, on_delete=models.CASCADE, related_name='renditions')
class Meta:
unique_together = (('image', 'filter_spec', 'focal_point_key'),)
verbose_name = 'Accredited Image Rendition'
verbose_name_plural = 'Accredited Image Renditions'
In settings I have:
WAGTAILIMAGES_IMAGE_MODEL = 'cms.AccreditedImage'
But, I have two third party plugins installed: puput and wagtail_events, each of which use a foreign key to wagtail images.
When I run `manage.py makemigrations, additional migrations are created in the puput and wagtail_events site_packages folders to handle the change in FK. The migrations look like this:
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('puput', '0005_blogpage_main_color'),
]
operations = [
migrations.AlterField(
model_name='blogpage',
name='header_image',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='cms.AccreditedImage', verbose_name='Header image'),
),
migrations.AlterField(
model_name='entrypage',
name='header_image',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='cms.AccreditedImage', verbose_name='Header image'),
),
]
The Problem
If I actually apply these migrations, then puput or wagtail_events releases a new version, then the migration history becomes corrupted - e.g. my autogenerated 0006* migration on puput and their new 0006* migration fork the history
The Question
Is there a way of overcoming this? Or a recommended practice for what to do?
At this point I'm in very early beta, so I could dump the entire DB and start again if the recommended strategy is to set this up from the outset to avoid the issue.
Thanks for any help, folks!
Answer 1 - if you have control over your third party libraries
The initial migration in the third party library should define a swappable dependency, for example:
from wagtail.images import get_image_model_string
dependencies = [
migrations.swappable_dependency(get_image_model_string()),
]
operations = [
migrations.CreateModel(
name='ThirdPartyModel',
fields=[
...
('image', models.ForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, to=get_image_model_string())),
],
...
),
This is not automatically created by makemigrations. get_image_model_string needs to be used like this in every migration affecting that FK, made through the entire migration history of the library.
If you change the setting at some point in the project, you will still need to do a data migration ('Migrate an existing swappable dependency' might help), but this solves the forking problem described above if starting clean.
It has the drawback of requiring control over the third party library. I'm not holding my breath for a project like puput to go back and alter their early migration history to allow for a swappable image model (puput's initial migration hard-codes wagtailimages.Image). But I've implemented this for wagtail_events (my own project) to save other people this hassle.
Answer 2 - if you don't have control
Ugh. I've been working on this a while and all candidate solutions are all pretty horrible. I considered getting my custom image class to impersonate wagtail.images.model.Image via the db_table meta attributes, and even by creating another app which essentially duplicates wagtail images. It's all either a lot of work or super hacky.
I've chosen to take over migrations manually using the MIGRATION_MODULES setting.
For my scenario, I've taken the entire migration history of puput and copied all the files into a separate folder, root/custom_puput_migrations/. I set
MIGRATION_MODULES = {
'puput': 'custom_puput_migrations'
}
WAGTAILIMAGES_IMAGE_MODEL = 'otherapp.AccreditedImage'
Then I pull the ol' switcharoo by editing 0001_initial.py in that folder to refer to the model via the setting, rather than by hard coding:
...
from wagtail.images import get_image_model_string
class Migration(migrations.Migration):
dependencies = [
...
migrations.swappable_dependency(get_image_model_string())
]
operations = [
migrations.CreateModel(
name='BlogPage',
fields=[
...
('header_image', models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, verbose_name='Header image', blank=True, to=get_image_model_string(), null=True)),
],
...
Drawbacks
1) The actual table relation created is not strictly determined by the migration file, but by the setting, which could change independently. If you prefer to avoid this, you could instead simply hard-code your referred model in the custom migration.
2) This approach leaves you pretty vulnerable to developers upgrading the library version requirement without realising that they also have to manually copy across the migrations files. I suggest a check (f/ex ensuring that the number of files in the default migrations folder is the same as the number of files in the custom one) before allowing the app to boot, to ensure your development and production databases all run on the same set of migrations.

Error when previewing Wagtail page and getting related inlines

I'm getting errors when previewing Wagtail pages, but they're fine when published and viewed live. My set-up is something like this:
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.core.models import Orderable, Page
from wagtail.snippets.models import register_snippet
#register_snippet
class Author(models.Model):
name = models.CharField(max_length=255, blank=False)
class ArticleAuthorRelationship(Orderable, models.Model):
author = models.ForeignKey('Author',
on_delete=models.CASCADE,
related_name='articles')
page = ParentalKey('ArticlePage',
on_delete=models.CASCADE,
related_name='authors')
class ArticlePage(Page):
def get_authors(self):
"""Returns a list of Author objects associated with this article."""
return [a.author for a in self.authors.all().order_by('author__name')]
In a template for an ArticlePage I call self.get_authors() to get a list of authors. This works fine if the article is 'live', or if I call the same method on the object in the shell, but when previewing the page I get this:
File "/Users/phil/Projects/myproject/myapp/articles/models/pages.py", line 551, in get_authors
return [a.author for a in self.authors.all().order_by('author__name')]
File "/Users/phil/.local/share/virtualenvs/myproject-zPWVWoxf/lib/python3.6/site-packages/modelcluster/queryset.py", line 467, in order_by
sort_by_fields(results, fields)
File "/Users/phil/.local/share/virtualenvs/myproject-zPWVWoxf/lib/python3.6/site-packages/modelcluster/utils.py", line 19, in sort_by_fields
items.sort(key=lambda x: (getattr(x, key) is not None, getattr(x, key)), reverse=reverse)
File "/Users/phil/.local/share/virtualenvs/myproject-zPWVWoxf/lib/python3.6/site-packages/modelcluster/utils.py", line 19, in <lambda>
items.sort(key=lambda x: (getattr(x, key) is not None, getattr(x, key)), reverse=reverse)
AttributeError: 'ArticleAuthorRelationship' object has no attribute 'author__name'
I'm stumped - I don't understand what's different about previewing a Wagtail page compared to viewing it normally. Something odd in modelcluster?
Yes, this is a limitation of the django-modelcluster module. In order for Django queryset methods such as order_by to work on in-memory relations that don't match the real database state (which is the case when previewing, as well as a few other situations such as viewing old revisions), modelcluster has to "fake" the operations that would normally be done through a SQL query. There are some limitations to how well the "faking" works, and some operations (such as raw SQL queries) will realistically never be possible.
The lack of support for order_by through a foreign key is a known limitation: https://github.com/wagtail/django-modelcluster/issues/45
Until this is fixed, a workaround would be to surround the query in a try/except AttributeError block and fall back on the unordered list.

Wagtail Custom Pages?

I'm totally new to Wagtail/ Django.
Here's what I am trying to achieve:
I'd like to have an ability in the backend of my Wagtail CMS install to create 'pages' or 'posts' that follow a strict template.
The template would have custom fields like 'header' and aim content' etc.
I'm sure that this is possible, I'd just be interested to know how I'd go about achieving this?
For example, does anyone know if Wagtail has a plugin or other to enable this?
Thanks for all help/ direction.
You want to create pages and posts that follow a strict template: that's exactly what Django and Wagtail let you do. But there's one catch: Wagtail takes this a step further and lets you move entire sections of a page — these are called Streamfields. It's an amazing feature, to be honest.
Here's an example to get you started (note: this is untested and not linted)
# -*- coding: utf-8 -*-
"""Basic Page model."""
from django.db import models
from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, StreamFieldPanel
from wagtail.core.fields import StreamField
from wagtail.core.models import Page
from your_custom_app.streams import streamfields
class BasicPage(Page):
"""A basic page class."""
template = "templates/pages/basic_page.html"
parent_page_type = ["pages.HomePage", "pages.BasicPage"]
subpage_types = ["pages.BasicPage"]
header = models.CharField(max_length=100)
content = StreamField(
('streamfield_name', streamfields.CustomStreamfield()),
# ... More streams
null=True,
blank=True,
)
# Other additional fields you want on your page.
# Panels are how you lay out your pages in the /admin/
content_panels = [
FieldPanel("title", classname="full title"),
FieldPanel("header"),
# FieldPanel("other_fields"),
StreamFieldPanel("content"),
]
settings_panels = Page.settings_panels + [] # Custom settings panel
promote_panels = Page.promote_panels + [] # Custom promote panel
class Meta:
"""Meta information."""
verbose_name = "Basic Page"
verbose_name_plural = "Basic Pages"
You can also download and setup the Wagtail Bakery Demo, it has a lot of great examples in it.

Django Dynamic model register in admin

I'm using django 1.11 and I tried to to create django dynamic models by referring this link https://code.djangoproject.com/wiki/DynamicModels , by executing each and every step it runs without any issue, but How can I see this created table in django admin panel?
action.py
from django.db import models
from django.contrib import admin
def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None):
"""
Create specified model
"""
class Meta:
# Using type('Meta', ...) gives a dictproxy error during model creation
pass
if app_label:
# app_label must be set using the Meta inner class
setattr(Meta, 'app_label', app_label)
# Update Meta with any options that were provided
if options is not None:
for key, value in options.iteritems():
setattr(Meta, key, value)
# Set up a dictionary to simulate declarations within a class
attrs = {'__module__': module, 'Meta': Meta}
# Add in any fields that were provided
if fields:
attrs.update(fields)
# Create the class, which automatically triggers ModelBase processing
model = type(name, (models.Model,), attrs)
# Create an Admin class if admin options were provided
if admin_opts is not None:
print admin_opts
class Admin(admin.ModelAdmin):
pass
for key, value in admin_opts:
setattr(Admin, key, value)
admin.site.register(model, Admin)
return model
In Console:
from action import create_model
from django.db import models
fields = {
'first_name': models.CharField(max_length=255),
'last_name': models.CharField(max_length=255),
'__str__': lambda self: '%s %s' (self.first_name, self.last_name),
}
options = {
'ordering': ['last_name', 'first_name'],
'verbose_name': 'valued customer',
}
admin_opts = {}
model = create_model('Person', fields,
options=options,
admin_opts=admin_opts,
app_label='form',
module='project.app.model',
)
I can see no. of fields by
len(model._meta.fields)
But I have no idea of, how to register the created model in admin, and what parameter will come inside admin_opts = {} , how can i do makemigrations and migrate,how can I access this model in views.py, from where i will import this model .Can you guys please help me for this , it will be very useful for me and Thanks in advance.
with connection.schema_editor() as editor:
editor.create_model(Model)
This is from github source code , try it instead of sql_model_create and I try to success in my project,and it's true..
I have worked hard for a long time because I don't find django-dynamic-model in "django 1.10".
I think you forgot to execute this function.
def install(model):
from django.core.management import sql, color
from django.db import connection
# Standard syncdb expects models to be in reliable locations,
# so dynamic models need to bypass django.core.management.syncdb.
# On the plus side, this allows individual models to be installed
# without installing the entire project structure.
# On the other hand, this means that things like relationships and
# indexes will have to be handled manually.
# This installs only the basic table definition.
# disable terminal colors in the sql statements
style = color.no_style()
cursor = connection.cursor()
statements, pending = sql.sql_model_create(model, style)
for sql in statements:
cursor.execute(sql)

Resources