diff --git a/CHANGELOG.txt b/CHANGELOG.txt index a0024b6a0..8b69d346a 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -5,7 +5,9 @@ Changelog ~~~~~~~~~~~~~~~~ * Added toolbar to allow logged-in users to add and edit pages from the site front-end * Support for alternative image processing backends such as Wand, via the WAGTAILIMAGES_BACKENDS setting + * Added support for generating static sites using django-medusa * Added custom Query set for Pages with some handy methods for querying pages + * Added 'wagtailforms' module for creating form pages on a site, and handling form submissions * Editor's guide documentation * Editor interface now outputs form media CSS / JS, to support custom widgets with assets * Migrations and user management now correctly handle custom AUTH_USER_MODEL settings @@ -24,6 +26,8 @@ Changelog * Fix: Page slugs are now validated on page edit * Fix: Filter objects are cached to avoid a database hit every time an {% image %} tag is compiled * Fix: Moving or changing a site root page no longer causes URLs for subpages to change to 'None' + * Fix: Eliminated raw SQL queries from wagtailcore / wagtailadmin, to ensure cross-database compatibility + * Fix: Snippets menu item is hidden for administrators if no snippet types are defined 0.2 (11.03.2014) ~~~~~~~~~~~~~~~~ diff --git a/CONTRIBUTORS.rst b/CONTRIBUTORS.rst index 38e89a8e1..3549e8407 100644 --- a/CONTRIBUTORS.rst +++ b/CONTRIBUTORS.rst @@ -25,6 +25,7 @@ Contributors * Miguel Vieira * Ben Emery * David Smith +* Ben Margolis Translators =========== diff --git a/docs/advanced_topics.rst b/docs/advanced_topics.rst new file mode 100644 index 000000000..7e23d8442 --- /dev/null +++ b/docs/advanced_topics.rst @@ -0,0 +1,17 @@ +Advanced Topics +~~~~~~~~~~~~~~~~ + +.. note:: + This documentation is currently being written. + +replacing image processing backend + +custom image processing tags? + +wagtail user bar custom CSS option? + +extending hallo editor plugins with editor_js() + +injecting any JS into page edit with editor_js() + +Custom content module (same level as docs or images) diff --git a/docs/building_your_site/djangodevelopers.rst b/docs/building_your_site/djangodevelopers.rst new file mode 100644 index 000000000..49f80c371 --- /dev/null +++ b/docs/building_your_site/djangodevelopers.rst @@ -0,0 +1,189 @@ +For Django developers +===================== + +.. note:: + This documentation is currently being written. + +Wagtail requires a little careful setup to define the types of content that you want to present through your website. The basic unit of content in Wagtail is the ``Page``, and all of your page-level content will inherit basic webpage-related properties from it. But for the most part, you will be defining content yourself, through the contruction of Django models using Wagtail's ``Page`` as a base. + +Wagtail organizes content created from your models in a tree, which can have any structure and combination of model objects in it. Wagtail doesn't prescribe ways to organize and interrelate your content, but here we've sketched out some strategies for organizing your models. + +The presentation of your content, the actual webpages, includes the normal use of the Django template system. We'll cover additional functionality that Wagtail provides at the template level later on. + +But first, we'll take a look at the ``Page`` class and model definitions. + + +The Page Class +~~~~~~~~~~~~~~ + +``Page`` uses Django's model interface, so you can include any field type and field options that Django allows. Wagtail provides some fields and editing handlers that simplify data entry in the Wagtail admin interface, so you may want to keep those in mind when deciding what properties to add to your models in addition to those already provided by ``Page``. + + +Built-in Properties of the Page Class +------------------------------------- + +Wagtail provides some properties in the ``Page`` class which are common to most webpages. Since you'll be subclassing ``Page``, you don't have to worry about implementing them. + +Public Properties +````````````````` + + ``title`` (string, required) + Human-readable title for the content + + ``slug`` (string, required) + Machine-readable URL component for this piece of content. The name of the page as it will appear in URLs e.g ``http://domain.com/blog/[my-slug]/`` + + ``seo_title`` (string) + Alternate SEO-crafted title which overrides the normal title for use in the ```` of a page + + ``search_description`` (string) + A SEO-crafted description of the content, used in both internal search indexing and for the meta description read by search engines + +The ``Page`` class actually has alot more to it, but these are probably the only built-in properties you'll need to worry about when creating templates for your models. + + +Anatomy of a Wagtail Model +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +So what does a Wagtail model definition look like? Here's a model representing a typical blog post: + +.. code-block:: python + + from django.db import models + + from wagtail.wagtailcore.models import Page + from wagtail.wagtailcore.fields import RichTextField + from wagtail.wagtailadmin.edit_handlers import FieldPanel + from wagtail.wagtailimages.edit_handlers import ImageChooserPanel + from wagtail.wagtailimages.models import Image + + class BlogPage(Page): + body = RichTextField() + date = models.DateField("Post date") + feed_image = models.ForeignKey( + 'wagtailimages.Image', + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name='+' + ) + + BlogPage.content_panels = [ + FieldPanel('title', classname="full title"), + FieldPanel('date'), + FieldPanel('body', classname="full"), + ] + + BlogPage.promote_panels = [ + FieldPanel('slug'), + FieldPanel('seo_title'), + FieldPanel('show_in_menus'), + FieldPanel('search_description'), + ImageChooserPanel('feed_image'), + ] + +To keep track of your ``Page``-derived models, it might be helpful to include "Page" as the last part of your classname. ``BlogPage`` defines three properties: ``body``, ``date``, and ``feed_image``. These are a mix of basic Django models (``DateField``), Wagtail fields (``RichTextField``), and a pointer to a Wagtail model (``Image``). + +Next, the ``content_panels`` and ``promote_panels`` lists define the capabilities and layout of the Wagtail admin page edit interface. The lists are filled with "panels" and "choosers", which will provide a fine-grain interface for inputting the model's content. The ``ImageChooserPanel``, for instance, lets one browse the image library, upload new images, and input image metadata. The ``RichTextField`` is the basic field for creating web-ready website rich text, including text formatting and embedded media like images and video. The Wagtail admin offers other choices for fields, Panels, and Choosers, with the option of creating your own to precisely fit your content without workarounds or other compromises. + +Your models may be even more complex, with methods overriding the built-in functionality of the ``Page`` to achieve webdev magic. Or, you can keep your models simple and let Wagtail's built-in functionality do the work. + +Now that we have a basic idea of how our content is defined, lets look at relationships between pieces of content. + + +Introduction to Trees +~~~~~~~~~~~~~~~~~~~~~ + +If you're unfamiliar with trees as an abstract data type, you might want to `review the concepts involved. `_ + +As a web developer, though, you probably already have a good understanding of trees as filesystem directories or paths. Wagtail pages can create the same structure, as each page in the tree has its own URL path, like so:: + + / + people/ + nien-nunb/ + laura-roslin/ + events/ + captain-picard-day/ + winter-wrap-up/ + +The Wagtail admin interface uses the tree to organize content for editing, letting you navigate up and down levels in the tree through its Explorer menu. This method of organization is a good place to start in thinking about your own Wagtail models. + + +Nodes and Leaves +---------------- + +It might be handy to think of the ``Page``-derived models you want to create as being one of two node types: parents and leaves. Wagtail isn't prescriptive in this approach, but it's a good place to start if you're not experienced in structuring your own content types. + + +Nodes +````` +Parent nodes on the Wagtail tree probably want to organize and display a browsable index of their descendents. A blog, for instance, needs a way to show a list of individual posts. + +A Parent node could provide its own function returning its descendant objects. + +.. code-block:: python + + class EventPageIndex(Page): + ... + def events(self): + # Get list of event pages that are descendants of this page + events = EventPage.objects.filter( + live=True, + path__startswith=self.path + ) + return events + +This example makes sure to limit the returned objects to pieces of content which make sense, specifically ones which have been published through Wagtail's admin interface (``live=True``) and are descendants of this node. Wagtail will allow the "illogical" placement of child nodes under a parent, so it's necessary for a parent model to index only those children which make sense. + + +Leaves +`````` +Leaves are the pieces of content itself, a page which is consumable, and might just consist of a bunch of properties. A blog page leaf might have some body text and an image. A person page leaf might have a photo, a name, and an address. + +It might be helpful for a leaf to provide a way to back up along the tree to a parent, such as in the case of breadcrumbs navigation. The tree might also be deep enough that a leaf's parent won't be included in general site navigation. + +The model for the leaf could provide a function that traverses the tree in the opposite direction and returns an appropriate ancestor: + +.. code-block:: python + + class BlogPage(Page): + ... + def blog_index(self): + # Find blog index in ancestors + for ancestor in reversed(self.get_ancestors()): + if isinstance(ancestor.specific, BlogIndexPage): + return ancestor + + # No ancestors are blog indexes, just return first blog index in database + return BlogIndexPage.objects.first() + +Since Wagtail doesn't limit what Page-derived classes can be assigned as parents and children, the reverse tree traversal needs to accommodate cases which might not be expected, such as the lack of a "logical" parent to a leaf. + + +Other Relationships +``````````````````` +Your ``Page``-derived models might have other interrelationships which extend the basic Wagtail tree or depart from it entirely. You could provide functions to navigate between siblings, such as a "Next Post" link on a blog page (``post->post->post``). It might make sense for subtrees to interrelate, such as in a discussion forum (``forum->post->replies``) Skipping across the hierarchy might make sense, too, as all objects of a certain model class might interrelate regardless of their ancestors (``events = EventPage.objects.all``). Since there's no restriction on the combination of model classes that can be used at any point in the tree, and it's largely up to the models to define their interrelations, the possibilities are really endless. + + +Anatomy of a Wagtail Request +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For going beyond the basics of model definition and interrelation, it might help to know how Wagtail handles requests and constructs responses. In short, it goes something like: + + #. Django gets a request and routes through Wagtail's URL dispatcher definitions + #. Starting from the root content piece, Wagtail traverses the page tree, letting the model for each piece of content along the path decide how to ``route()`` the next step in the path. + #. A model class decides that routing is done and it's now time to ``serve()`` content. + #. The model constructs a context, finds a template to pass it to, and renders the content. + #. The templates are rendered and the response object is sent back to the requester. + +You can apply custom behavior to this process by overriding the ``route()`` and ``serve()`` methods of the ``Page`` class in your own models. + + +Site +~~~~ + +Django's built-in admin interface provides the way to map a "site" (hostname or domain) to any node in the wagtail tree, using that node as the site's root. + +Access this by going to ``/django-admin/`` and then "Home › Wagtailcore › Sites." To try out a development site, add a single site with the hostname ``localhost`` at port ``8000`` and map it to one of the pieces of content you have created. + +Wagtail's developers plan to move the site settings into the Wagtail admin interface. diff --git a/docs/building_your_site/frontenddevelopers.rst b/docs/building_your_site/frontenddevelopers.rst new file mode 100644 index 000000000..033c64e9e --- /dev/null +++ b/docs/building_your_site/frontenddevelopers.rst @@ -0,0 +1,184 @@ +For Front End developers +======================== + +.. note:: + This documentation is currently being written. + +======================== +Overview +======================== + +Wagtail uses Django's templating language. For developers new to Django, start with Django's own template documentation: +https://docs.djangoproject.com/en/dev/topics/templates/ + +Python programmers new to Django/Wagtail may prefer more technical documentation: +https://docs.djangoproject.com/en/dev/ref/templates/api/ + +========================== +Displaying Pages +========================== + +Template Location +----------------- + +For each of your ``Page``-derived models, Wagtail will look for a template in the following location, relative to your project root:: + + project/ + app/ + templates/ + app/ + blog_index_page.html + models.py + +Class names are converted from camel case to underscores. For example, the template for model class ``BlogIndexPage`` would be assumed to be ``blog_index_page.html``. For more information, see the Django documentation for the `application directories template loader`_. + +.. _application directories template loader: https://docs.djangoproject.com/en/dev/ref/templates/api/ + + +Self +---- + +By default, the context passed to a model's template consists of two properties: ``self`` and ``request``. ``self`` is the model object being displayed. ``request`` is the normal Django request object. So, to include the title of a ``Page``, use ``{{ self.title }}``. + +======================== +Static files (css, js, images) +======================== + + + +Images +~~~~~~~~~~ + +Images uploaded to Wagtail go into the image library and from there are added to pages via the :doc:`page editor interface `. + +Unlike other CMS, adding images to a page does not involve choosing a "version" of the image to use. Wagtail has no predefined image "formats" or "sizes". Instead the template developer defines image manipulation to occur *on the fly* when the image is requested, via a special syntax within the template. + +Images from the library **must** be requested using this syntax, but images in your codebase can be added via conventional means e.g ``img`` tags. Only images from the library can be manipulated on the fly. + +Read more about the image manipulation syntax here :ref:`Images tag `. + + +======================== +Template tags & filters +======================== + +In addition to Django's standard tags and filters, Wagtail provides some of it's own, which can be ``load``-ed `as you would any other `_ + +.. _image-tag: +Images (tag) +~~~~~~~~~~~~ + +The syntax for displaying/manipulating an image is thus:: + + {% image [image] [method]-[dimension(s)] %} + +For example:: + + {% image self.photo width-400 %} + + + {% image self.photo fill-80x80 %} + +The ``image`` is the Django object refering to the image. If your page model defined a field called "photo" then ``image`` would probably be ``self.photo``. The ``method`` defines which resizing algorithm to use and ``dimension(s)`` provides height and/or width values (as ``[width|height]`` or ``[width]x[height]``) to refine that algorithm. + +Note that a space separates ``image`` and ``method``, but not ``method`` and ``dimensions``: a hyphen between ``method`` and ``dimensions`` is mandatory. Multiple dimensions must be separated by an ``x``. + +The available ``method`` s are: + +.. glossary:: + ``max`` + (takes two dimensions) + + Fit **within** the given dimensions. + + The longest edge will be reduced to the equivalent dimension size defined. e.g A portrait image of width 1000, height 2000, treated with the ``max`` dimensions ``1000x500`` (landscape) would result in the image shrunk so the *height* was 500 pixels and the width 250. + + ``min`` + (takes two dimensions) + + **Cover** the given dimensions. + + This may result in an image slightly **larger** than the dimensions you specify. e.g A square image of width 2000, height 2000, treated with the ``min`` dimensions ``500x200`` (landscape) would have it's height and width changed to 500, i.e matching the width required, but greater than the height. + + ``width`` + (takes one dimension) + + Reduces the width of the image to the dimension specified. + + ``height`` + (takes one dimension) + + Resize the height of the image to the dimension specified.. + + ``fill`` + (takes two dimensions) + + Resize and **crop** to fill the **exact** dimensions. + + This can be particularly useful for websites requiring square thumbnails of arbitrary images. e.g A landscape image of width 2000, height 1000, treated with ``fill`` dimensions ``200x200`` would have it's height reduced to 200, then it's width (ordinarily 400) cropped to 200. + + **The crop always aligns on the centre of the image.** + +.. Note:: + Wagtail *does not allow deforming or stretching images*. Image dimension ratios will always be kept. Wagtail also *does not support upscaling*. Small images forced to appear at larger sizes will "max out" at their their native dimensions. + + +To request the "original" version of an image, it is suggested you rely on the lack of upscalling support by requesting an image much larger than it's maximum dimensions. e.g to insert an image who's dimensions are uncertain/unknown, at it's maximum size, try: ``{% image self.image width-10000 %}``. This assumes the image is unlikely to be larger than 10000px wide. + +Rich text (filter) +~~~~~~~~~~~~~~~~~~ + +This filter is required for use with any ``RichTextField``. It will expand internal shorthand references to embeds and links made in the Wagtail editor into fully-baked HTML ready for display. **Note that the template tag loaded differs from the name of the filter.** + +.. code-block:: django + + {% load rich_text %} + ... + {{ body|richtext }} + +Internal links (tag) +~~~~~~~~~~~~~~~~~~~~ + +**pageurl** + +Takes a ``Page``-derived object and returns its URL as relative (``/foo/bar/``) if it's within the same site as the current page, or absolute (``http://example.com/foo/bar/``) if not. + +.. code-block:: django + + {% load pageurl %} + ... + + +**slugurl** + +Takes a ``slug`` string and returns the URL for the ``Page``-derived object with that slug. Like ``pageurl``, will try to provide a relative link if possible, but will default to an absolute link if on a different site. + +.. code-block:: django + + {% load slugurl %} + ... + + + + + +Static files (tag) +~~~~~~~~~~~~~~ + + +Misc +~~~~~~~~~~ + + + +======================== +Wagtail User Bar +======================== + +This tag provides a Wagtail icon and flyout menu on the top-right of a page for a logged-in user with editing capabilities, with the option of editing the current Page-derived object or adding a new sibling object. + +.. code-block:: django + + {% load wagtailuserbar %} + ... + {% wagtailuserbar %} diff --git a/docs/building_your_site.rst b/docs/building_your_site/index.rst similarity index 59% rename from docs/building_your_site.rst rename to docs/building_your_site/index.rst index b506f67f2..fb336e18b 100644 --- a/docs/building_your_site.rst +++ b/docs/building_your_site/index.rst @@ -1,6 +1,15 @@ Building your site ================== +.. note:: + Documentation currently incomplete and in draft status + Serafeim Papastefanos has written a comprehensive tutorial on creating a site from scratch in Wagtail; for the time being, this is our recommended resource: -`spapas.github.io/2014/02/13/wagtail-tutorial/ `_ \ No newline at end of file +`spapas.github.io/2014/02/13/wagtail-tutorial/ `_ + +.. toctree:: + :maxdepth: 3 + + djangodevelopers + frontenddevelopers diff --git a/docs/editing_api.rst b/docs/editing_api.rst new file mode 100644 index 000000000..2985a1229 --- /dev/null +++ b/docs/editing_api.rst @@ -0,0 +1,202 @@ + +Editing API +=========== + +.. note:: + This documentation is currently being written. + + +Wagtail provides a highly-customizable editing interface consisting of several components: + + * **Fields** — built-in content types to augment the basic types provided by Django. + * **Panels** — the basic editing blocks for fields, groups of fields, and related object clusters + * **Choosers** — interfaces for finding related objects in a ForeignKey relationship + +Configuring your models to use these components will shape the Wagtail editor to your needs. Wagtail also provides an API for injecting custom CSS and Javascript for further customization, including extending the hallo.js rich text editor. + +There is also an Edit Handler API for creating your own Wagtail editor components. + + +Defining Panels +~~~~~~~~~~~~~~~ + +A "panel" is the basic editing block in Wagtail. Wagtail will automatically pick the appropriate editing widget for most Django field types, you just need to add a panel for each field you want to show in the Wagtail page editor, in the order you want them to appear. + +There are three types of panels: + + ``FieldPanel( field_name, classname=None )`` + This is the panel used for basic Django field types. ``field_name`` is the name of the class property used in your model definition. ``classname`` is a string of optional CSS classes given to the panel which are used in formatting and scripted interactivity. By default, panels are formatted as inset fields. The CSS class ``full`` can be used to format the panel so it covers the full width of the Wagtail page editor. The CSS class ``title`` can be used to mark a field as the source for auto-generated slug strings. + + ``MultiFieldPanel( panel_list, heading )`` + This panel condenses several ``FieldPanel`` s or choosers, from a list or tuple, under a single ``heading`` string. + + ``InlinePanel( base_model, relation_name, panels=None, label='', help_text='' )`` + This panel allows for the creation of a "cluster" of related objects over a join to a separate model, such as a list of related links or slides to an image carousel. This is a very powerful, but tricky feature which will take some space to cover, so we'll skip over it for now. For a full explaination on the usage of ``InlinePanel``, see :ref:`inline_panels`. + +Wagtail provides a tabbed interface to help organize panels. ``content_panels`` is the main tab, used for the meat of your model content. The other, ``promote_panels``, is suggested for organizing metadata about the content, such as SEO information and other machine-readable information. Since you're writing the panel definitions, you can organize them however you want. + +Let's look at an example of a panel definition: + +.. code-block:: python + + COMMON_PANELS = ( + FieldPanel('slug'), + FieldPanel('seo_title'), + FieldPanel('show_in_menus'), + FieldPanel('search_description'), + ) + + ... + + class ExamplePage( Page ): + # field definitions omitted + ... + + ExamplePage.content_panels = [ + FieldPanel('title', classname="full title"), + FieldPanel('body', classname="full"), + FieldPanel('date'), + ImageChooserPanel('splash_image'), + DocumentChooserPanel('free_download'), + PageChooserPanel('related_page'), + ] + + ExamplePage.promote_panels = [ + MultiFieldPanel(COMMON_PANELS, "Common page configuration"), + ] + + + + + +Built-in Fields and Choosers +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Django's field types are automatically recognized and provided with an appropriate widget for input. Just define that field the normal Django way and pass the field name into ``FieldPanel()`` when defining your panels. Wagtail will take care of the rest. + +Here are some Wagtail-specific types that you might include as fields in your models. + + +Rich Text (HTML) +---------------- + +Wagtail provides a general-purpose WYSIWYG editor for creating rich text content (HTML) and embedding media such as images, video, and documents. To include this in your models, use the ``RichTextField()`` function when defining a model field: + +.. code-block:: python + + from wagtail.wagtailcore.fields import RichTextField + ... + class BookPage(Page): + book_text = RichTextField() + + + +If you're interested in extending the capabilities of the Wagtail editor, See :ref:`extending_wysiwyg`. + + +Images +------ + +.. code-block:: python + + from wagtail.wagtailimages.models import Image + + feed_image = models.ForeignKey( + 'wagtailimages.Image', + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name='+' + ) + + +Documents +--------- + +.. code-block:: python + + from wagtail.wagtaildocs.models import Document + + link_document = models.ForeignKey( + 'wagtaildocs.Document', + null=True, + blank=True, + related_name='+' + ) + + +Pages and Page-derived Models +----------------------------- + +.. code-block:: python + + from wagtail.wagtailcore.models import Page + + page = models.ForeignKey( + 'wagtailcore.Page', + related_name='+', + null=True, + blank=True + ) + +Can also use more specific models. + + +Snippets (and Basic Django Models?) +-------- + +Snippets are not not subclasses, so you must include the model class directly. A chooser is provided which takes the snippet class. + +.. code-block:: python + + advert = models.ForeignKey( + 'demo.Advert', + related_name='+' + ) + + + + + + + + + + + + + + +PageChooserPanel +~~~~~~~~~~~~~~~~ + +ImageChooserPanel +~~~~~~~~~~~~~~~~~ + +DocumentChooserPanel +~~~~~~~~~~~~~~~~~~~~ + +SnippetChooserPanel +~~~~~~~~~~~~~~~~~~~ + + +.. _inline_panels: + +Inline Panels and Model Clusters +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``django-modelcluster`` module allows for streamlined relation of extra models to a Wagtail page. + + +.. _extending_wysiwyg: + +Extending the WYSIWYG Editor (hallo.js) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + + +Edit Handler API +~~~~~~~~~~~~~~~~ + + + diff --git a/docs/editor_manual/index.rst b/docs/editor_manual/index.rst index 4562844e7..b7b5c84f7 100644 --- a/docs/editor_manual/index.rst +++ b/docs/editor_manual/index.rst @@ -1,9 +1,10 @@ Using Wagtail: an Editor's guide ================================ -This section of the documentation is written for the users of a Wagtail-powered site. That is, the content editors, moderators and administrators who will be running things on a day-to-day basis. +.. note:: + Documentation currently incomplete and in draft status -**NOTE:** This section of the documentation is currently in draft status. +This section of the documentation is written for the users of a Wagtail-powered site. That is, the content editors, moderators and administrators who will be running things on a day-to-day basis. .. toctree:: :maxdepth: 3 diff --git a/docs/form_builder.rst b/docs/form_builder.rst new file mode 100644 index 000000000..9aa220e19 --- /dev/null +++ b/docs/form_builder.rst @@ -0,0 +1,69 @@ +Form builder +============ + +The `wagtailforms` module allows you to set up single-page forms, such as a 'Contact us' form, as pages of a Wagtail site. It provides a set of base models that site implementors can extend to create their own 'Form' page type with their own site-specific templates. Once a page type has been set up in this way, editors can build forms within the usual page editor, consisting of any number of fields. Form submissions are stored for later retrieval through a new 'Forms' section within the Wagtail admin interface; in addition, they can be optionally e-mailed to an address specified by the editor. + + +Usage +~~~~~ + +Add 'wagtail.wagtailforms' to your INSTALLED_APPS: + +.. code:: python + + INSTALLED_APPS = [ + ... + 'wagtail.wagtailforms', + ] + +Within the models.py of one of your apps, create a model that extends wagtailforms.models.AbstractEmailForm: + + +.. code:: python + + from wagtail.wagtailforms.models import AbstractEmailForm, AbstractFormField + + class FormField(AbstractFormField): + page = ParentalKey('FormPage', related_name='form_fields') + + class FormPage(AbstractEmailForm): + intro = RichTextField(blank=True) + thank_you_text = RichTextField(blank=True) + + FormPage.content_panels = [ + FieldPanel('title', classname="full title"), + FieldPanel('intro', classname="full"), + InlinePanel(FormPage, 'form_fields', label="Form fields"), + FieldPanel('thank_you_text', classname="full"), + MultiFieldPanel([ + FieldPanel('to_address', classname="full"), + FieldPanel('from_address', classname="full"), + FieldPanel('subject', classname="full"), + ], "Email") + ] + +AbstractEmailForm defines the fields 'to_address', 'from_address' and 'subject', and expects form_fields to be defined. Any additional fields are treated as ordinary page content - note that FormPage is responsible for serving both the form page itself and the landing page after submission, so the model definition should include all necessary content fields for both of those views. + +If you do not want your form page type to offer form-to-email functionality, you can inherit from AbstractForm instead of AbstractEmailForm, and omit the 'to_address', 'from_address' and 'subject' fields from the content_panels definition. + +You now need to create two templates named form_page.html and form_page_landing.html (where 'form_page' is the underscore-formatted version of the class name). form_page.html differs from a standard Wagtail template in that it is passed a variable 'form', containing a Django form object, in addition to the usual 'self' variable. A very basic template for the form would thus be: + +.. code:: html + + {% load pageurl rich_text %} + + + {{ self.title }} + + +

{{ self.title }}

+ {{ self.intro|richtext }} +
+ {% csrf_token %} + {{ form.as_p }} + +
+ + + +form_page_landing.html is a regular Wagtail template, displayed after the user makes a successful form submission. diff --git a/docs/gettingstarted.rst b/docs/gettingstarted.rst index e4d2d6484..a46ea9664 100644 --- a/docs/gettingstarted.rst +++ b/docs/gettingstarted.rst @@ -4,7 +4,7 @@ Getting Started On Ubuntu ~~~~~~~~~ -If you have a fresh instance of Ubuntu 13.04 or 13.10, you can install Wagtail, +If you have a fresh instance of Ubuntu 13.04 or later, you can install Wagtail, along with a demonstration site containing a set of standard templates and page types, in one step. As the root user:: @@ -102,12 +102,17 @@ Required dependencies ===================== - `pip `_ +- `libjpeg `_ +- `libxml2 `_ +- `libxslt `_ +- `zlib `_ Optional dependencies ===================== - `PostgreSQL`_ - `Elasticsearch`_ +- `Redis`_ Installation ============ @@ -137,6 +142,7 @@ with a regular Django project. .. _the Wagtail codebase: https://github.com/torchbox/wagtail .. _PostgreSQL: http://www.postgresql.org .. _Elasticsearch: http://www.elasticsearch.org +.. _Redis: http://redis.io/ _`Remove the demo app` ~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/index.rst b/docs/index.rst index dbfe91f33..abbb7fdbe 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -9,10 +9,16 @@ It supports Django 1.6.2+ on Python 2.6 and 2.7. Django 1.7 and Python 3 support :maxdepth: 3 gettingstarted - building_your_site + building_your_site/index + editing_api + snippets wagtail_search + form_builder + model_recipes + advanced_topics deploying performance + static_site_generation contributing support roadmap diff --git a/docs/model_recipes.rst b/docs/model_recipes.rst new file mode 100644 index 000000000..db88daf7c --- /dev/null +++ b/docs/model_recipes.rst @@ -0,0 +1,176 @@ + +Model Recipes +============= + +Overriding the serve() Method +----------------------------- + +Wagtail defaults to serving ``Page``-derived models by passing ``self`` to a Django HTML template matching the model's name, but suppose you wanted to serve something other than HTML? You can override the ``serve()`` method provided by the ``Page`` class and handle the Django request and response more directly. + +Consider this example from the Wagtail demo site's ``models.py``, which serves an ``EventPage`` object as an iCal file if the ``format`` variable is set in the request: + +.. code-block:: python + + class EventPage(Page): + ... + def serve(self, request): + if "format" in request.GET: + if request.GET['format'] == 'ical': + # Export to ical format + response = HttpResponse( + export_event(self, 'ical'), + content_type='text/calendar', + ) + response['Content-Disposition'] = 'attachment; filename=' + self.slug + '.ics' + return response + else: + # Unrecognised format error + message = 'Could not export event\n\nUnrecognised format: ' + request.GET['format'] + return HttpResponse(message, content_type='text/plain') + else: + # Display event page as usual + return super(EventPage, self).serve(request) + +``serve()`` takes a Django request object and returns a Django response object. Wagtail returns a ``TemplateResponse`` object with the template and context which it generates, which allows middleware to function as intended, so keep in mind that a simpler response object like a ``HttpResponse`` will not receive these benefits. + +With this strategy, you could use Django or Python utilities to render your model in JSON or XML or any other format you'd like. + + +Adding Endpoints with Custom route() Methods +-------------------------------------------- + +Wagtail routes requests by iterating over the path components (separated with a forward slash ``/``), finding matching objects based on their slug, and delegating further routing to that object's model class. The Wagtail source is very instructive in figuring out what's happening. This is the default ``route()`` method of the ``Page`` class: + +.. code-block:: python + + class Page(...): + + ... + + def route(self, request, path_components): + if path_components: + # request is for a child of this page + child_slug = path_components[0] + remaining_components = path_components[1:] + + # find a matching child or 404 + try: + subpage = self.get_children().get(slug=child_slug) + except Page.DoesNotExist: + raise Http404 + + # delegate further routing + return subpage.specific.route(request, remaining_components) + + else: + # request is for this very page + if self.live: + # use the serve() method to render the request if the page is published + return self.serve(request) + else: + # the page matches the request, but isn't published, so 404 + raise Http404 + +The contract is pretty simple. ``route()`` takes the current object (``self``), the ``request`` object, and a list of the remaining ``path_components`` from the request URL. It either continues delegating routing by calling ``route()`` again on one of its children in the Wagtail tree, or ends the routing process by serving something -- either normally through the ``self.serve()`` method or by raising a 404 error. + +By overriding the ``route()`` method, we could create custom endpoints for each object in the Wagtail tree. One use case might be using an alternate template when encountering the ``print/`` endpoint in the path. Another might be a REST API which interacts with the current object. Just to see what's involved, lets make a simple model which prints out all of its child path components. + +First, ``models.py``: + +.. code-block:: python + + from django.shortcuts import render + + ... + + class Echoer(Page): + + def route(self, request, path_components): + if path_components: + return render(request, self.template, { + 'self': self, + 'echo': ' '.join(path_components), + }) + else: + if self.live: + return self.serve(request) + else: + raise Http404 + + Echoer.content_panels = [ + FieldPanel('title', classname="full title"), + ] + + Echoer.promote_panels = [ + MultiFieldPanel(COMMON_PANELS, "Common page configuration"), + ] + +This model, ``Echoer``, doesn't define any properties, but does subclass ``Page`` so objects will be able to have a custom title and slug. The template just has to display our ``{{ echo }}`` property. We're skipping the ``serve()`` method entirely, but you could include your render code there to stay consistent with Wagtail's conventions. + +Now, once creating a new ``Echoer`` page in the Wagtail admin titled "Echo Base," requests such as:: + + http://127.0.0.1:8000/echo-base/tauntaun/kennel/bed/and/breakfast/ + +Will return:: + + tauntaun kennel bed and breakfast + + +Tagging +------- + +Wagtail provides tagging capability through the combination of two django modules, ``taggit`` and ``modelcluster``. ``taggit`` provides a model for tags which is extended by ``modelcluster``, which in turn provides some magical database abstraction which makes drafts and revisions possible in Wagtail. It's a tricky recipe, but the net effect is a many-to-many relationship between your model and a tag class reserved for your model. + +Using an example from the Wagtail demo site, here's what the tag model and the relationship field looks like in ``models.py``: + +.. code-block:: python + + from modelcluster.fields import ParentalKey + from modelcluster.tags import ClusterTaggableManager + from taggit.models import Tag, TaggedItemBase + ... + class BlogPageTag(TaggedItemBase): + content_object = ParentalKey('demo.BlogPage', related_name='tagged_items') + ... + class BlogPage(Page): + ... + tags = ClusterTaggableManager(through=BlogPageTag, blank=True) + + BlogPage.promote_panels = [ + ... + FieldPanel('tags'), + ] + +Wagtail's admin provides a nice interface for inputting tags into your content, with typeahead tag completion and friendly tag icons. + +Now that we have the many-to-many tag relationship in place, we can fit in a way to render both sides of the relation. Here's more of the Wagtail demo site ``models.py``, where the index model for ``BlogPage`` is extended with logic for filtering the index by tag: + +.. code-block:: python + + class BlogIndexPage(Page): + ... + def serve(self, request): + # Get blogs + blogs = self.blogs + + # Filter by tag + tag = request.GET.get('tag') + if tag: + blogs = blogs.filter(tags__name=tag) + + return render(request, self.template, { + 'self': self, + 'blogs': blogs, + }) + +Here, ``blogs.filter(tags__name=tag)`` invokes a reverse Django queryset filter on the ``BlogPageTag`` model to optionally limit the ``BlogPage`` objects sent to the template for rendering. Now, lets render both sides of the relation by showing the tags associated with an object and a way of showing all of the objects associated with each tag. This could be added to the ``blog_page.html`` template: + +.. code-block:: django + + {% for tag in self.tags.all %} +
{{ tag }} + {% endfor %} + +Iterating through ``self.tags.all`` will display each tag associated with ``self``, while the link(s) back to the index make use of the filter option added to the ``BlogIndexPage`` model. A Django query could also use the ``tagged_items`` related name field to get ``BlogPage`` objects associated with a tag. + +This is just one possible way of creating a taxonomy for Wagtail objects. With all of the components for a taxonomy available through Wagtail, you should be able to fulfill even the most exotic taxonomic schemes. diff --git a/docs/roadmap.rst b/docs/roadmap.rst index c94692fac..bdc711470 100644 --- a/docs/roadmap.rst +++ b/docs/roadmap.rst @@ -10,7 +10,7 @@ https://raw.github.com/torchbox/wagtail/master/CHANGELOG.txt In summary: - * February 2013: Reduced dependencies, basic documentation, translations, tests + * February 2014: Reduced dependencies, basic documentation, translations, tests What's next ~~~~~~~~~~~ @@ -19,12 +19,10 @@ The `issue list `_ gives a detailed * More and better tests (>80% `coverage `_) * Better documentation: simple setup guides for all levels of user, a manual for editors and administrators, in-depth intstructions for Django developers. - * A form builder * Move site section permissions out of Django admin * Improved image handling: intelligent cropping, animated gif support * Block-level editing UI (see `Sir Trevor `_) * Site settings management - * Edit bird for logged-in visitors * Support for an HTML content type * Simple inline stats diff --git a/docs/snippets.rst b/docs/snippets.rst new file mode 100644 index 000000000..14d62b793 --- /dev/null +++ b/docs/snippets.rst @@ -0,0 +1,140 @@ +Snippets +======== + +Snippets are pieces of content which do not necessitate a full webpage to render. They could be used for making secondary content, such as headers, footers, and sidebars, editable in the Wagtail admin. Snippets are models which do not inherit the ``Page`` class and are thus not organized into the Wagtail tree, but can still be made editable by assigning panels and identifying the model as a snippet with ``register_snippet()``. + +Snippets are not searchable or orderable in the Wagtail admin, so decide carefully if the content type you would want to build into a snippet might be more suited to a page. + +Snippet Models +-------------- + +Here's an example snippet from the Wagtail demo website: + +.. code-block:: python + + from django.db import models + + from wagtail.wagtailadmin.edit_handlers import FieldPanel + from wagtail.wagtailsnippets.models import register_snippet + + ... + + class Advert(models.Model): + url = models.URLField(null=True, blank=True) + text = models.CharField(max_length=255) + + panels = [ + FieldPanel('url'), + FieldPanel('text'), + ] + + def __unicode__(self): + return self.text + + register_snippet(Advert) + +The ``Advert`` model uses the basic Django model class and defines two properties: text and url. The editing interface is very close to that provided for ``Page``-derived models, with fields assigned in the panels property. Snippets do not use multiple tabs of fields, nor do they provide the "save as draft" or "submit for moderation" features. + +``register_snippet(Advert)`` tells Wagtail to treat the model as a snippet. The ``panels`` list defines the fields to show on the snippet editing page. It's also important to provide a string representation of the class through ``def __unicode__(self):`` so that the snippet objects make sense when listed in the Wagtail admin. + +Including Snippets in Template Tags +----------------------------------- + +The simplest way to make your snippets available to templates is with a template tag. This is mostly done with vanilla Django, so perhaps reviewing Django's documentation for `django custom template tags`_ will be more helpful. We'll go over the basics, though, and make note of any considerations to make for Wagtail. + +First, add a new python file to a ``templatetags`` folder within your app. The demo website, for instance uses the path ``wagtaildemo/demo/templatetags/demo_tags.py``. We'll need to load some Django modules and our app's models and ready the ``register`` decorator: + +.. _django custom template tags: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/ + +.. code-block:: python + + from django import template + from demo.models import * + + register = template.Library() + + ... + + # Advert snippets + @register.inclusion_tag('demo/tags/adverts.html', takes_context=True) + def adverts(context): + return { + 'adverts': Advert.objects.all(), + 'request': context['request'], + } + +``@register.inclusion_tag()`` takes two variables: a template and a boolean on whether that template should be passed a request context. It's a good idea to include request contexts in your custom template tags, since some Wagtail-specific template tags like ``pageurl`` need the context to work properly. The template tag function could take arguments and filter the adverts to return a specific model, but for brevity we'll just use ``Advert.objects.all()``. + +Here's what's in the template used by the template tag: + +.. code-block:: django + + {% for advert in adverts %} +

+ + {{ advert.text }} + +

+ {% endfor %} + +Then in your own page templates, you can include your snippet template tag with: + +.. code-block:: django + + {% block content %} + + ... + + {% adverts %} + + {% endblock %} + +Binding Pages to Snippets +------------------------- + +An alternate strategy for including snippets might involve explicitly binding a specific page object to a specific snippet object. Lets add another snippet class to see how that might work: + +.. code-block:: python + + from django.db import models + + from wagtail.wagtailcore.models import Page + from wagtail.wagtailadmin.edit_handlers import PageChooserPanel + from wagtail.wagtailsnippets.models import register_snippet + from wagtail.wagtailsnippets.edit_handlers import SnippetChooserPanel + + from modelcluster.fields import ParentalKey + + ... + + class AdvertPlacement(models.Model): + page = ParentalKey('wagtailcore.Page', related_name='advert_placements') + advert = models.ForeignKey('demo.Advert', related_name='+') + + class Meta: + verbose_name = "Advert Placement" + verbose_name_plural = "Advert Placements" + + panels = [ + PageChooserPanel('page'), + SnippetChooserPanel('advert', Advert), + ] + + def __unicode__(self): + return self.page.title + " -> " + self.advert.text + + register_snippet(AdvertPlacement) + +The class ``AdvertPlacement`` has two properties, ``page`` and ``advert``, which point to other models. Wagtail provides a ``PageChooserPanel`` and ``SnippetChooserPanel`` to let us make painless selection of those properties in the Wagtail admin. Note also the ``Meta`` class, which you can stock with the ``verbose_name`` and ``verbose_name_plural`` properties to override the snippet labels in the Wagtail admin. The text representation of the class has also gotten fancy, using both properties to construct a compound label showing the relationship it forms between a page and an Advert. + +With this snippet in place, we can use the reverse ``related_name`` lookup label ``advert_placements`` to iterate over any placements within our template files. In the template for a ``Page``-derived model, we could include the following: + +.. code-block:: django + + {% if self.advert_placements %} + {% for advert_placement in self.advert_placements.all %} +

{{ advert_placement.advert.text }}

+ {% endfor %} + {% endif %} + + diff --git a/docs/static_site_generation.rst b/docs/static_site_generation.rst new file mode 100644 index 000000000..a9379cd67 --- /dev/null +++ b/docs/static_site_generation.rst @@ -0,0 +1,83 @@ +Generating a static site +======================== + +This document describes how to render your Wagtail site into static HTML files on your local filesystem, Amazon S3 or Google App Engine, using `django medusa`_ and the ``wagtail.contrib.wagtailmedusa`` module. + + +Installing django-medusa +~~~~~~~~~~~~~~~~~~~~~~~~ + +First, install django medusa from pip: + +.. code:: + + pip install django-medusa + + +Then add ``django_medusa`` and ``wagtail.contrib.wagtailmedusa`` to ``INSTALLED_APPS``: + +.. code:: python + + INSTALLED_APPS = [ + ... + 'django_medusa', + 'wagtail.contrib.wagtailmedusa', + ] + + +Replacing GET parameters with custom routing +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Pages which require GET parameters (e.g. for pagination) don't generate suitable filenames for generated HTML files so they need to be changed to use custom routing instead. + +For example, let's say we have a Blog Index which uses pagination. We can override the ``route`` method to make it respond on urls like '/page/1', and pass the page number through to the ``serve`` method: + +.. code:: python + + class BlogIndex(Page): + ... + + def serve(self, request, page=1): + ... + + def route(self, request, path_components): + if self.live and len(path_components) == 2 and path_components[0] == 'page': + try: + return self.serve(request, page=int(path_components[1])) + except (TypeError, ValueError): + pass + + return super(BlogIndex, self).route(request, path_components) + + +Rendering pages which use custom routing +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For page types that override the ``route`` method, we need to let django medusa know which URLs it responds on. This is done by overriding the ``get_static_site_paths`` method to make it yield one string per URL path. + +For example, the BlogIndex above would need to yield one URL for each page of results: + +.. code:: python + + def get_static_site_paths(self): + # Get page count + page_count = ... + + # Yield a path for each page + for page in range(page_count): + yield '/%d/' % (page + 1) + + # Yield from superclass + for path in super(BlogIndex, self).get_static_site_paths(): + yield path + + +Rendering +~~~~~~~~~ + +To render a site, run ``./manage.py staticsitegen``. This will render the entire website and place the HTML in a folder called 'medusa_output'. The static and media folders need to be copied into this folder manually after the rendering is complete. This feature inherits django-medusa's ability to render your static site to Amazon S3 or Google App Engine; see the `medusa docs `_ for configuration details. + +To test, open the 'medusa_output' folder in a terminal and run ``python -m SimpleHTTPServer``. + + +.. _django medusa: https://github.com/mtigas/django-medusa diff --git a/docs/wagtail_search.rst b/docs/wagtail_search.rst index 1bef60724..fff462349 100644 --- a/docs/wagtail_search.rst +++ b/docs/wagtail_search.rst @@ -1,7 +1,226 @@ Search ====== -Wagtail can degrade to a database-backed text search, but we strongly recommend `Elasticsearch`_. If you prefer not to run an Elasticsearch server in development or production, there are many hosted services available, including `Searchly`_, who offer a free account suitable for testing and development. To use Searchly: +Wagtail provides a very comprehensive, extensible, and flexible search interface. In addition, it provides ways to promote search results through "Editor's Picks." Wagtail also collects simple statistics on queries made through the search interface. + +Default Page Search +------------------- + +Wagtail provides a default frontend search interface which indexes the ``title`` field common to all ``Page``-derived models. Lets take a look at all the components of the search interface. + +The most basic search functionality just needs a search box which submits a request. Since this will be reused throughout the site, lets put it in ``mysite/includes/search_box.html`` and then use ``{% include ... %}`` to weave it into templates: + +.. code-block:: django + +
+ + +
+ +The form is submitted to the url of the ``wagtailsearch_search`` view, with the search terms variable ``q``. The view will use its own (very) basic search results template. + +Lets use our own template for the results, though. First, in your project's ``settings.py``, define a path to your template: + +.. code-block:: python + + WAGTAILSEARCH_RESULTS_TEMPLATE = 'mysite/search_results.html' + +Next, lets look at the template itself: + +.. code-block:: django + + {% extends "mysite/base.html" %} + {% load pageurl %} + + {% block title %}Search{% if search_results %} Results{% endif %}{% endblock %} + + {% block search_box %} + {% include "mysite/includes/search_box.html" with query_string=query_string only %} + {% endblock %} + + {% block content %} +

Search Results{% if request.GET.q %} for {{ request.GET.q }}{% endif %}

+
    + {% for result in search_results %} +
  • +

    {{ result.specific }}

    + {% if result.specific.search_description %} + {{ result.specific.search_description|safe }} + {% endif %} +
  • + {% empty %} +
  • No results found
  • + {% endfor %} +
+ {% endblock %} + +The search view provides a context with a few useful variables. + + ``query_string`` + The terms (string) used to make the search. + + ``search_results`` + A collection of Page objects matching the query. The ``specific`` property of ``Page`` will give the most-specific subclassed model object for the Wagtail page. For instance, if an ``Event`` model derived from the basic Wagtail ``Page`` were included in the search results, you could use ``specific`` to access the custom properties of the ``Event`` model (``result.specific.date_of_event``). + + ``is_ajax`` + Boolean. This returns Django's ``request.is_ajax()``. + + ``query`` + A Wagtail ``Query`` object matching the terms. The ``Query`` model provides several class methods for viewing the statistics of all queries, but exposes only one property for single objects, ``query.hits``, which tracks the number of time the search string has been used over the lifetime of the site. ``Query`` also joins to the Editor's Picks functionality though ``query.editors_picks``. See :ref:`editors-picks`. + +Editor's Picks +-------------- + +Editor's Picks are a way of explicitly linking relevant content to search terms, so results pages can contain curated content instead of being at the mercy of the search algorithm. In a template using the search results view, editor's picks can be accessed through the variable ``query.editors_picks``. To include editor's picks in your search results template, use the following properties. + +``query.editors_picks.all`` + This gathers all of the editor's picks objects relating to the current query, in order according to their sort order in the Wagtail admin. You can then iterate through them using a ``{% for ... %}`` loop. Each editor's pick object provides these properties: + + ``editors_pick.page`` + The page object associated with the pick. Use ``{% pageurl editors_pick.page %}`` to generate a URL or provide other properties of the page object. + + ``editors_pick.description`` + The description entered when choosing the pick, perhaps explaining why the page is relevant to the search terms. + +Putting this all together, a block of your search results template displaying Editor's Picks might look like this: + +.. code-block:: django + + {% with query.editors_picks.all as editors_picks %} + {% if editors_picks %} +
+

Editors picks

+ +
+ {% endif %} + {% endwith %} + +Asyncronous Search with JSON and AJAX +------------------------------------- + +Wagtail's provides JSON search results when queries are made to the ``wagtailsearch_suggest`` view. To take advantage of it, we need a way to make that URL available to a static script. Instead of hard-coding it, lets set a global variable in our ``base.html``: + +.. code-block:: django + + + +Lets also add a simple interface for the search with a ```` element to gather search terms and a ``
`` to display the results: + +.. code-block:: html + +
+

Search

+ +
+
+ +Finally, we'll use JQuery to make the aynchronous requests and handle the interactivity: + +.. code-block:: guess + + $(function() { + + // cache the elements + var searchBox = $('#json-search'), + resultsBox = $('#json-results'); + // when there's something in the input box, make the query + searchBox.on('input', function() { + if( searchBox.val() == ''){ + resultsBox.html(''); + return; + } + // make the request to the Wagtail JSON search view + $.ajax({ + url: wagtailJSONSearchURL + "?q=" + searchBox.val(), + dataType: "json" + }) + .done(function(data) { + console.log(data); + if( data == undefined ){ + resultsBox.html(''); + return; + } + // we're in business! let's format the results + var htmlOutput = ''; + data.forEach(function(element, index, array){ + htmlOutput += '

' + element.title + '

'; + }); + // and display them + resultsBox.html(htmlOutput); + }) + .error(function(data){ + console.log(data); + }); + }); + + }); + +Results are returned as a JSON object with this structure: + +.. code-block:: guess + + { + [ + { + title: "Lumpy Space Princess", + url: "/oh-my-glob/" + }, + { + title: "Lumpy Space", + url: "/no-smooth-posers/" + }, + ... + ] + } + +What if you wanted access to the rest of the results context or didn't feel like using JSON? Wagtail also provides a generalized AJAX interface where you can use your own template to serve results asyncronously. + +The AJAX interface uses the same view as the normal HTML search, ``wagtailsearch_search``, but will serve different results if Django classifies the request as AJAX (``request.is_ajax()``). Another entry in your project settings will let you override the template used to serve this response: + +.. code-block:: python + + WAGTAILSEARCH_RESULTS_TEMPLATE_AJAX = 'myapp/includes/search_listing.html' + +In this template, you'll have access to the same context variablies provided to the HTML template. You could provide a template in JSON format with extra properties, such as ``query.hits`` and editor's picks, or render an HTML snippet that can go directly into your results ``
``. If you need more flexibility, such as multiple formats/templates based on differing requests, you can set up a custom search view. + +.. _editors-picks: + + +Indexing Custom Fields & Custom Search Views +-------------------------------------------- + +This functionality is still under active development to provide a streamlined interface, but take a look at ``wagtail/wagtail/wagtailsearch/views/frontend.py`` if you are interested in coding custom search views. + + +Search Backends +--------------- + +Wagtail can degrade to a database-backed text search, but we strongly recommend `Elasticsearch`_. + +.. _Elasticsearch: http://www.elasticsearch.org/ + + +Default DB Backend +`````````````````` +The default DB search backend uses Django's ``__icontains`` filter. + + +Elasticsearch Backend +````````````````````` +If you prefer not to run an Elasticsearch server in development or production, there are many hosted services available, including `Searchly`_, who offer a free account suitable for testing and development. To use Searchly: - Sign up for an account at `dashboard.searchly.com/users/sign\_up`_ - Use your Searchly dashboard to create a new index, e.g. 'wagtaildemo' @@ -10,6 +229,9 @@ Wagtail can degrade to a database-backed text search, but we strongly recommend your local settings - Run ``./manage.py update_index`` -.. _Elasticsearch: http://www.elasticsearch.org/ .. _Searchly: http://www.searchly.com/ -.. _dashboard.searchly.com/users/sign\_up: https://dashboard.searchly.com/users/sign_up \ No newline at end of file +.. _dashboard.searchly.com/users/sign\_up: https://dashboard.searchly.com/users/sign_up + +Rolling Your Own +```````````````` +Wagtail search backends implement the interface defined in ``wagtail/wagtail/wagtailsearch/backends/base.py``. At a minimum, the backend's ``search()`` method must return a collection of objects or ``model.objects.none()``. For a fully-featured search backend, examine the Elasticsearch backend code in ``elasticsearch.py``. diff --git a/runtests.py b/runtests.py index ab7bc37c3..1577d73b5 100755 --- a/runtests.py +++ b/runtests.py @@ -80,6 +80,7 @@ if not settings.configured: 'wagtail.wagtailembeds', 'wagtail.wagtailsearch', 'wagtail.wagtailredirects', + 'wagtail.wagtailforms', 'wagtail.tests', ], diff --git a/scripts/install/debian.sh b/scripts/install/debian.sh index 93f513d16..d29d5acdc 100644 --- a/scripts/install/debian.sh +++ b/scripts/install/debian.sh @@ -1,5 +1,5 @@ -# Production-configured Wagtail installation -# (secure services/account for full production use). +# Production-configured Wagtail installation. +# BUT, SECURE SERVICES/ACCOUNT FOR FULL PRODUCTION USE! # Tested on Debian 7.0. # Tom Dyson and Neal Todd @@ -42,6 +42,7 @@ aptitude -y install openjdk-7-jre-headless curl -O https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.0.0.deb dpkg -i elasticsearch-1.0.0.deb rm elasticsearch-1.0.0.deb +perl -pi -e"s/# network.host: 192.168.0.1/network.host: 127.0.0.1/" /etc/elasticsearch/elasticsearch.yml update-rc.d elasticsearch defaults 95 10 service elasticsearch start diff --git a/scripts/install/ubuntu.sh b/scripts/install/ubuntu.sh index 9f60e2e8e..c713cefa9 100644 --- a/scripts/install/ubuntu.sh +++ b/scripts/install/ubuntu.sh @@ -1,5 +1,5 @@ -# Production-configured Wagtail installation -# (secure services/account for full production use). +# Production-configured Wagtail installation. +# BUT, SECURE SERVICES/ACCOUNT FOR FULL PRODUCTION USE! # Tested on Ubuntu 13.04 and 13.10. # Tom Dyson and Neal Todd @@ -40,6 +40,7 @@ aptitude -y install openjdk-7-jre-headless curl -O https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.0.0.deb dpkg -i elasticsearch-1.0.0.deb rm elasticsearch-1.0.0.deb +perl -pi -e"s/# network.host: 192.168.0.1/network.host: 127.0.0.1/" /etc/elasticsearch/elasticsearch.yml update-rc.d elasticsearch defaults 95 10 service elasticsearch start diff --git a/setup.py b/setup.py index e8da542bc..8a85f618c 100644 --- a/setup.py +++ b/setup.py @@ -51,6 +51,7 @@ setup( "Pillow>=2.3.0", "beautifulsoup4>=4.3.2", "lxml>=3.3.0", + 'unicodecsv>=0.9.4', 'Unidecode>=0.04.14', "BeautifulSoup==3.2.1", # django-compressor gets confused if we have lxml but not BS3 installed ], diff --git a/tox.ini b/tox.ini index 329c1c407..11b8bb3a2 100644 --- a/tox.ini +++ b/tox.ini @@ -3,7 +3,6 @@ dj16= Django>=1.6,<1.7 pyelasticsearch==0.6.1 elasticutils==0.8.2 - unittest2 [tox] envlist = diff --git a/wagtail/contrib/__init__.py b/wagtail/contrib/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/wagtail/contrib/wagtailmedusa/__init__.py b/wagtail/contrib/wagtailmedusa/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/wagtail/contrib/wagtailmedusa/models.py b/wagtail/contrib/wagtailmedusa/models.py new file mode 100644 index 000000000..e69de29bb diff --git a/wagtail/contrib/wagtailmedusa/renderers.py b/wagtail/contrib/wagtailmedusa/renderers.py new file mode 100644 index 000000000..950e13a14 --- /dev/null +++ b/wagtail/contrib/wagtailmedusa/renderers.py @@ -0,0 +1,24 @@ +from django_medusa.renderers import StaticSiteRenderer +from wagtail.wagtailcore.models import Site +from wagtail.wagtaildocs.models import Document + + +class PageRenderer(StaticSiteRenderer): + def get_paths(self): + # Get site + # TODO: Find way to get this to work with other sites + site = Site.objects.filter(is_default_site=True).first() + if site is None: + return [] + + # Return list of paths + return site.root_page.get_static_site_paths() + + +class DocumentRenderer(StaticSiteRenderer): + def get_paths(self): + # Return list of paths to documents + return (doc.url for doc in Document.objects.all()) + + +renderers = [PageRenderer, DocumentRenderer] diff --git a/wagtail/tests/fixtures/test.json b/wagtail/tests/fixtures/test.json index 0a0fc0528..625c5618b 100644 --- a/wagtail/tests/fixtures/test.json +++ b/wagtail/tests/fixtures/test.json @@ -23,7 +23,7 @@ "model": "wagtailcore.page", "fields": { "title": "Welcome to the Wagtail test site!", - "numchild": 1, + "numchild": 3, "show_in_menus": false, "live": true, "depth": 2, @@ -164,6 +164,57 @@ } }, +{ + "pk": 8, + "model": "wagtailcore.page", + "fields": { + "title": "Contact us", + "numchild": 0, + "show_in_menus": true, + "live": true, + "depth": 3, + "content_type": ["tests", "formpage"], + "path": "000100010003", + "url_path": "/home/contact-us/", + "slug": "contact-us" + } +}, +{ + "pk": 8, + "model": "tests.formpage", + "fields": { + } +}, + +{ + "pk": 1, + "model": "tests.formfield", + "fields": { + "sort_order": 1, + "label": "Your email", + "field_type": "email", + "required": true, + "choices": "", + "default_value": "", + "help_text": "", + "page": 8 + } +}, +{ + "pk": 2, + "model": "tests.formfield", + "fields": { + "sort_order": 2, + "label": "Your message", + "field_type": "multiline", + "required": true, + "choices": "", + "default_value": "", + "help_text": "", + "page": 8 + } +}, + { "pk": 1, "model": "wagtailcore.site", @@ -201,6 +252,19 @@ ] } }, +{ + "pk": 5, + "model": "auth.group", + "fields": { + "name": "Site-wide editors", + "permissions": [ + ["access_admin", "wagtailadmin", "admin"], + ["add_image", "wagtailimages", "image"], + ["change_image", "wagtailimages", "image"], + ["delete_image", "wagtailimages", "image"] + ] + } +}, { "pk": 1, "model": "wagtailcore.grouppagepermission", @@ -237,6 +301,15 @@ "permission_type": "publish" } }, +{ + "pk": 5, + "model": "wagtailcore.grouppagepermission", + "fields": { + "group": ["Site-wide editors"], + "page": 2, + "permission_type": "edit" + } +}, { "pk": 1, @@ -308,5 +381,42 @@ "password": "md5$seasalt$1e9bf2bf5606aa5c39852cc30f0f6f22", "email": "inactiveuser@example.com" } +}, +{ + "pk": 5, + "model": "auth.user", + "fields": { + "username": "siteeditor", + "first_name": "", + "last_name": "", + "is_active": true, + "is_superuser": false, + "is_staff": false, + "groups": [ + ["Site-wide editors"] + ], + "user_permissions": [], + "password": "md5$seasalt$1e9bf2bf5606aa5c39852cc30f0f6f22", + "email": "siteeditor@example.com" + } +}, + +{ + "pk": 1, + "model": "wagtailforms.formsubmission", + "fields": { + "form_data": "{\"your-email\": \"old@example.com\", \"your-message\": \"this is a really old message\"}", + "page": 8, + "submit_time": "2013-01-01T12:00:00.000Z" + } +}, +{ + "pk": 2, + "model": "wagtailforms.formsubmission", + "fields": { + "form_data": "{\"your-email\": \"new@example.com\", \"your-message\": \"this is a fairly new message\"}", + "page": 8, + "submit_time": "2014-01-01T12:00:00.000Z" + } } ] diff --git a/wagtail/tests/models.py b/wagtail/tests/models.py index 9124cb253..844fb836f 100644 --- a/wagtail/tests/models.py +++ b/wagtail/tests/models.py @@ -1,10 +1,12 @@ from django.db import models +from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from modelcluster.fields import ParentalKey from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel, PageChooserPanel from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtaildocs.edit_handlers import DocumentChooserPanel +from wagtail.wagtailforms.models import AbstractEmailForm, AbstractFormField EVENT_AUDIENCE_CHOICES = ( @@ -187,12 +189,66 @@ class EventIndex(Page): intro = RichTextField(blank=True) ajax_template = 'tests/includes/event_listing.html' - def get_context(self, request): + def get_events(self): + return self.get_children().live().type(EventPage) + + def get_paginator(self): + return Paginator(self.get_events(), 4) + + def get_context(self, request, page=1): + # Pagination + paginator = self.get_paginator() + try: + events = paginator.page(page) + except PageNotAnInteger: + events = paginator.page(1) + except EmptyPage: + events = paginator.page(paginator.num_pages) + + # Update context context = super(EventIndex, self).get_context(request) - context['events'] = EventPage.objects.filter(live=True) + context['events'] = events return context + def route(self, request, path_components): + if self.live and len(path_components) == 1: + try: + return self.serve(request, page=int(path_components[0])) + except (TypeError, ValueError): + pass + + return super(EventIndex, self).route(request, path_components) + + def get_static_site_paths(self): + # Get page count + page_count = self.get_paginator().num_pages + + # Yield a path for each page + for page in range(page_count): + yield '/%d/' % (page + 1) + + # Yield from superclass + for path in super(EventIndex, self).get_static_site_paths(): + yield path + EventIndex.content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('intro', classname="full"), ] + + +class FormField(AbstractFormField): + page = ParentalKey('FormPage', related_name='form_fields') + +class FormPage(AbstractEmailForm): + pass + +FormPage.content_panels = [ + FieldPanel('title', classname="full title"), + InlinePanel(FormPage, 'form_fields', label="Form fields"), + MultiFieldPanel([ + FieldPanel('to_address', classname="full"), + FieldPanel('from_address', classname="full"), + FieldPanel('subject', classname="full"), + ], "Email") +] diff --git a/wagtail/tests/templates/tests/form_page.html b/wagtail/tests/templates/tests/form_page.html new file mode 100644 index 000000000..5fbd2ae9f --- /dev/null +++ b/wagtail/tests/templates/tests/form_page.html @@ -0,0 +1,15 @@ +{% load pageurl %} + + + + {{ self.title }} + + +

{{ self.title }}

+
+ {% csrf_token %} + {{ form.as_p }} + +
+ + diff --git a/wagtail/tests/templates/tests/form_page_landing.html b/wagtail/tests/templates/tests/form_page_landing.html new file mode 100644 index 000000000..e29a6a942 --- /dev/null +++ b/wagtail/tests/templates/tests/form_page_landing.html @@ -0,0 +1,11 @@ +{% load pageurl %} + + + + {{ self.title }} + + +

{{ self.title }}

+

Thank you for your feedback.

+ + diff --git a/wagtail/tests/utils.py b/wagtail/tests/utils.py index 11cdb369d..7b6557a78 100644 --- a/wagtail/tests/utils.py +++ b/wagtail/tests/utils.py @@ -1,9 +1,20 @@ from django.contrib.auth.models import User +# We need to make sure that we're using the same unittest library that Django uses internally +# Otherwise, we get issues with the "SkipTest" and "ExpectedFailure" exceptions being recognised as errors +try: + # Firstly, try to import unittest from Django + from django.utils import unittest +except ImportError: + # Django doesn't include unittest + # We must be running on Django 1.7+ which doesn't support Python 2.6 so + # the standard unittest library should be unittest2 + import unittest + def login(client): # Create a user User.objects.create_superuser(username='test', email='test@email.com', password='password') # Login - client.login(username='test', password='password') \ No newline at end of file + client.login(username='test', password='password') diff --git a/wagtail/wagtailadmin/static/wagtailadmin/js/core.js b/wagtail/wagtailadmin/static/wagtailadmin/js/core.js index e5895e34f..380c3d179 100644 --- a/wagtail/wagtailadmin/static/wagtailadmin/js/core.js +++ b/wagtail/wagtailadmin/static/wagtailadmin/js/core.js @@ -128,7 +128,7 @@ $(function(){ $(window.headerSearch.termInput).trigger('focus'); function search () { - var workingClasses = "working icon icon-spinner"; + var workingClasses = "icon-spinner"; $(window.headerSearch.termInput).parent().addClass(workingClasses); search_next_index++; diff --git a/wagtail/wagtailadmin/static/wagtailadmin/js/page-editor.js b/wagtail/wagtailadmin/static/wagtailadmin/js/page-editor.js index 6c58974a2..2dd97125f 100644 --- a/wagtail/wagtailadmin/static/wagtailadmin/js/page-editor.js +++ b/wagtail/wagtailadmin/static/wagtailadmin/js/page-editor.js @@ -1,3 +1,15 @@ +var halloPlugins = { + 'halloformat': {}, + 'halloheadings': {formatBlocks: ["p", "h2", "h3", "h4", "h5"]}, + 'hallolists': {}, + 'hallohr': {}, + 'halloreundo': {}, + 'hallowagtaillink': {}, +}; +function registerHalloPlugin(name, opts) { + halloPlugins[name] = (opts || {}); +} + function makeRichTextEditable(id) { var input = $('#' + id); var richText = $('
').html(input.val()); @@ -19,17 +31,7 @@ function makeRichTextEditable(id) { richText.hallo({ toolbar: 'halloToolbarFixed', toolbarcssClass: 'testy', - plugins: { - 'halloformat': {}, - 'halloheadings': {formatBlocks: ["p", "h2", "h3", "h4", "h5"]}, - 'hallolists': {}, - 'hallohr': {}, - 'halloreundo': {}, - 'hallowagtailimage': {}, - 'hallowagtailembeds': {}, - 'hallowagtaillink': {}, - 'hallowagtaildoclink': {} - } + plugins: halloPlugins }).bind('hallomodified', function(event, data) { input.val(data.content); if (!removeStylingPending) { diff --git a/wagtail/wagtailadmin/static/wagtailadmin/scss/components/formatters.scss b/wagtail/wagtailadmin/static/wagtailadmin/scss/components/formatters.scss index 150611f8f..97e915f36 100644 --- a/wagtail/wagtailadmin/static/wagtailadmin/scss/components/formatters.scss +++ b/wagtail/wagtailadmin/static/wagtailadmin/scss/components/formatters.scss @@ -181,4 +181,9 @@ a.tag:hover{ .unlist{ @include unlist(); +} + +/* utility class to allow things to be scrollable if their contents can't wrap more nicely */ +.overflow{ + overflow:auto; } \ No newline at end of file diff --git a/wagtail/wagtailadmin/static/wagtailadmin/scss/components/forms.scss b/wagtail/wagtailadmin/static/wagtailadmin/scss/components/forms.scss index 9ef27297c..29c44b4f3 100644 --- a/wagtail/wagtailadmin/static/wagtailadmin/scss/components/forms.scss +++ b/wagtail/wagtailadmin/static/wagtailadmin/scss/components/forms.scss @@ -21,22 +21,13 @@ legend{ @include visuallyhidden(); } -.fields li{ - padding-top:0.5em; - padding-bottom:0.5em; -} - -.field{ - padding:0 0 0.6em 0; -} - label{ font-weight:bold; color:$color-grey-1; font-size:1.1em; display:block; padding:0 0 0.8em 0; - line-height:1em; + line-height:1.3em; .checkbox &, .radio &{ @@ -47,10 +38,10 @@ label{ input, textarea, select, .richtext, .tagit{ @include border-radius(6px); @include border-box(); - font-family:Open Sans,Arial,sans-serif; width:100%; - border:1px dashed $color-input-border; - padding:1.2em; + font-family:Open Sans,Arial,sans-serif; + border:1px solid $color-input-border; + padding:0.9em 1.2em; background-color:$color-fieldset-hover; -webkit-appearance: none; color:$color-text-input; @@ -76,10 +67,44 @@ input, textarea, select, .richtext, .tagit{ } } -input[type=radio],input[type=checkbox]{ +/* select boxes */ +.typed_choice_field .input{ + position:relative; + + select{ + outline:none; + } + + &:after{ + @include border-radius(0 6px 6px 0); + z-index:0; + position:absolute; + right:1px; + top:1px; + height:95%; + width:1.5em; + font-family:wagtail; + content:"q"; + border:1px solid $color-input-border; + border-width:0 0 0 1px; + text-align:center; + line-height:1.4em; + font-size:3em; + pointer-events:none; + color:$color-grey-3; + background-color:$color-fieldset-hover; + margin:0px 1px 0 0; + } + + .ie &:after{ + display:none; + } +} + +/* radio and check boxes */ +input[type=radio], input[type=checkbox]{ @include border-radius(0); cursor:pointer; - float:left; border:0; } @@ -350,18 +375,15 @@ button.icon{ .help, .error-message{ font-size:0.85em; font-weight:normal; - margin:0 0 0.5em 0; + margin:0.5em 0 0 0; +} +.error-message{ + color:$color-red; } .help{ color:$color-grey-2; } -/* permanently show checkbox/radio help as they have no focus state */ -.boolean_field .help, .radio .help{ - opacity:1; -} - - fieldset:hover > .help, .field.focused + .help, .field:focus + .help, @@ -380,18 +402,77 @@ li.focused > .help{ font-size:13px; } -.error-message{ - margin:0; - color:$color-red; - clear:both; -} - .error input, .error textarea, .error select, .error .tagit{ border-color:$color-red; background-color:$color-input-error-bg; } +/* Layouts for particular kinds of of fields */ + +/* permanently show checkbox/radio help as they have no focus state */ +.boolean_field .help, .radio .help{ + opacity:1; +} +.iconfield { + position:relative; + + input:not([type=radio]), input:not([type=checkbox]), input:not([type=submit]), input:not([type=button]){ + padding-left:2.5em; + } + + &:before, &:after{ + font-family:wagtail; + position:absolute; + top:0.4em; + font-size:1.4em; + color:$color-grey-3; + } + &:before{ + left:0.5em; + } + &:after{ + right:0.5em; + } + + /* special case for search spinners */ + &.icon-spinner:after{ + color:$color-teal; + opacity:0.8; + font-size:20px; + width:20px; + height:20px; + line-height:23px; + text-align:center; + top:0.3em; + + } +} + +.fields li{ + padding-top:0.5em; + padding-bottom:1.2em; +} + +.field-content .input li{ + label{ + width:auto; + float:none; + } +} + +.input{ + clear:both; +} + /* field sizing */ + +.field-small{ + input, textarea, select, .richtext, .tagit{ + @include border-radius(3px); + padding:0.4em 1em; + } +} + .field{ &.col1, &.col2, @@ -453,7 +534,7 @@ ul.inline li:first-child, li.inline:first-child{ display:block; float:left; color:$color-grey-3; - line-height:0.85em; + line-height:1em; font-size:2.5em; margin-right:0.3em; } @@ -495,7 +576,6 @@ ul.inline li:first-child, li.inline:first-child{ .unchosen, .chosen{ &:before{ content:"b"; - margin-left:-0.1em; /* this glyphs appear to have left padding, counteracted here */ } } } @@ -568,112 +648,6 @@ ul.tagit li.tagit-choice-editable{ } } - -/* search bars (search integrated into header area) */ -.search-bar{ - margin-top:-2em; - padding-top:1em; - padding-bottom:1em; - margin-bottom:2em; - - &.full-width{ - @include nice-padding(); - background-color:$color-header-bg; - border-bottom:1px solid $color-grey-4; - } - - label{ - display:none; - } - - .fields{ - position:relative; - clear:both; - - .field input{ - padding-left:3em; - - &:focus{ - background-color:white; - } - } - .field:before, .field:after{ - font-family:wagtail; - position:absolute; - top:1em; - font-size:25px; - - } - .field:before{ - left:0.5em; - content:"f"; - color:$color-grey-3; - } - .field:after{ - color:$color-teal; - opacity:0.8; - font-size:20px; - width:20px; - height:20px; - line-height:23px; - text-align:center; - top:0.3em; - right:0.5em; - } - } - .submit{ - display:none; - position:absolute; - right:0; - top:0; - input{ - padding:1.55em 2em; - } - } - .taglist{ - font-size:0.9em; - line-height:2.4em; - h3{ - display:inline; - } - a{ - white-space: nowrap - } - } - - &.small{ - margin:0; - padding:0; - .fields{ - li{ - padding:0; - } - .field{ - padding:0; - } - .field input{ - padding:0.4em 1.4em 0.4em 2em; - - &:focus{ - background-color:white; - } - } - .field:before{ - font-size:1.1rem; - top:0.45em; - } - - } - } -} - -/* mozilla specific hack */ -@-moz-document url-prefix() { - .search-bar .fields .field:after{ - line-height:20px; - } -} - /* Transitions */ fieldset, input, textarea, select{ @include transition(background-color 0.2s ease); @@ -686,11 +660,22 @@ input[type=submit], input[type=reset], input[type=button], .button, button{ } @media screen and (min-width: $breakpoint-mobile){ - .help{ - opacity:1; - } - .fields{ - max-width:800px; + label{ + @include column(2); + padding-top:1.2em; + padding-left:0; + + .model_multiple_choice_field &, + .boolean_field &, + .model_choice_field &, + .image_field &, + .file_field &{ + padding-top:0; + } + + .boolean_field &{ + padding-bottom:0; + } } input[type=submit], input[type=reset], input[type=button], .button, button{ @@ -706,4 +691,20 @@ input[type=submit], input[type=reset], input[type=button], .button, button{ } } } + + .help{ + opacity:1; + } + .fields{ + max-width:800px; + } + + .field{ + @include row(); + } + + .field-content{ + @include column(10); + padding-right:0; + } } \ No newline at end of file diff --git a/wagtail/wagtailadmin/static/wagtailadmin/scss/components/header.scss b/wagtail/wagtailadmin/static/wagtailadmin/scss/components/header.scss new file mode 100644 index 000000000..849420ae0 --- /dev/null +++ b/wagtail/wagtailadmin/static/wagtailadmin/scss/components/header.scss @@ -0,0 +1,156 @@ +header{ + padding-top:1em; + padding-bottom:1em; + background-color: $color-header-bg; + margin-bottom:2em; + color:white; + + h1, h2{ + margin:0; + color:white; + } + + h1{ + padding:0.2em 0; + + &.icon:before{ + width:1em; + display:none; + margin-right:0.4em; + font-size:1.5em; + } + } + + .col{ + float:left; + margin-right:2em; + } + .left{ + float:left; + + .hasform &:first-child{ + padding-bottom:0.5em; + float:none; + } + } + .right{ + text-align:right; + float:right; + } + + /* For case where content below header should merge with it */ + &.merged{ + margin-bottom:0; + } + &.tab-merged, &.no-border{ + border:0; + } + &.merged.no-border{ + padding-bottom:0; + } + &.no-v-padding{ + padding-top:0; + padding-bottom:0; + } + /* + &.hasform h1{ + margin-top:0.2em; + } + */ + .button{ + background-color:$color-teal-darker; + &:hover{ + background-color:$color-teal-dark; + } + } + + /* necessary on mobile only to make way for hamburger menu */ + &.nice-padding{ + padding-left:4em; + } + + label{ + @include visuallyhidden(); + } + + input[type=text], select{ + border-width:0; + + &:focus{ + background-color:white; + } + } + + .fields{ + margin-top:-0.5em; + li{ + padding-bottom:0; + } + .field{ + padding:0; + } + } + + .field-content{ + width:auto; + padding:0; + } +} + +/* mozilla specific hack */ +@-moz-document url-prefix() { + .iconfield.icon-spinner:after{ + line-height:20px; + } +} + +.page-explorer header{ + margin-bottom:0; + padding-bottom:0em; +} + + +@media screen and (min-width: $breakpoint-mobile){ + header{ + padding-top:1.5em; + padding-bottom:1.5em; + + .left{ + float:left; + margin-right:0; + + &:first-child{ + padding-bottom:0; + float:left; + } + } + .second{ + clear:none; + + .right, .left{ + float:right; + } + } + + h1.icon:before{ + display:inline-block; + } + + .col3{ + @include column(3); + } + .col3.addbutton{ + width:auto; + } + .col6{ + @include column(6); + } + .col9{ + @include column(9); + } + .breadcrumb{ + margin-left:-($desktop-nice-padding); + margin-right:-($desktop-nice-padding); + } + } +} \ No newline at end of file diff --git a/wagtail/wagtailadmin/static/wagtailadmin/scss/components/icons.scss b/wagtail/wagtailadmin/static/wagtailadmin/scss/components/icons.scss index a1aa3cca0..7fb3320dd 100644 --- a/wagtail/wagtailadmin/static/wagtailadmin/scss/components/icons.scss +++ b/wagtail/wagtailadmin/static/wagtailadmin/scss/components/icons.scss @@ -231,14 +231,20 @@ .icon-collapse-up:before{ content:"6"; } +.icon-date:before{ + content:"7"; +} +.icon-success:before{ + content:"9"; +} .icon-help:before{ content:"?"; } .icon-warning:before{ content:"!"; } -.icon-success:before{ - content:"9"; +.icon-form:before{ + content:"$"; } .icon-date:before{ content:"7"; diff --git a/wagtail/wagtailadmin/static/wagtailadmin/scss/core.scss b/wagtail/wagtailadmin/static/wagtailadmin/scss/core.scss index 2d77d7628..80beb7f5f 100644 --- a/wagtail/wagtailadmin/static/wagtailadmin/scss/core.scss +++ b/wagtail/wagtailadmin/static/wagtailadmin/scss/core.scss @@ -11,6 +11,7 @@ @import "components/listing.scss"; @import "components/messages.scss"; @import "components/formatters.scss"; +@import "components/header.scss"; @import "fonts.scss"; @@ -115,7 +116,7 @@ img{ } .nav-wrapper{ - @include box-shadow(inset -2px 0px 10px 0px rgba(0, 0, 0, 0.5)); + @include box-shadow(inset -5px 0px 5px -3px rgba(0, 0, 0, 0.3)); position:relative; background: $color-grey-1; margin-left: -100%; @@ -385,88 +386,6 @@ body.explorer-open { } } -header{ - padding-top:1em; - padding-bottom:1em; - background-color: $color-header-bg; - margin-bottom:2em; - color:white; - - h1, h2{ - margin:0; - color:white; - } - - h1{ - padding:0.2em 0; - - &.icon:before{ - width:1em; - display:none; - margin-right:0.4em; - font-size:1.5em; - } - } - - .col{ - float:left; - margin-right:2em; - } - .left{ - float:left; - - .hasform &:first-child{ - padding-bottom:0.5em; - float:none; - } - } - .search-bar input{ - @include border-radius(3px); - width:auto; - border-width:0; - } - .right{ - text-align:right; - float:right; - } - - /* For case where content below header should merge with it */ - &.merged{ - margin-bottom:0; - } - &.tab-merged, &.no-border{ - border:0; - } - &.merged.no-border{ - padding-bottom:0; - } - &.no-v-padding{ - padding-top:0; - padding-bottom:0; - } - /* - &.hasform h1{ - margin-top:0.2em; - } - */ - .button{ - background-color:$color-teal-darker; - &:hover{ - background-color:$color-teal-dark; - } - } - /* necessary on mobile only to make way for hamburger menu */ - &.nice-padding{ - padding-left:4em; - } -} - -.page-explorer header{ - margin-bottom:0; - padding-bottom:0em; -} - - footer{ @include row(); @include border-radius(3px 3px 0 0); @@ -832,48 +751,6 @@ footer, .logo{ } } - header{ - padding-top:1.5em; - padding-bottom:1.5em; - - .left{ - float:left; - margin-right:0; - - &:first-child{ - padding-bottom:0; - float:left; - } - } - .second{ - clear:none; - - .right, .left{ - float:right; - } - } - - h1.icon:before{ - display:inline-block; - } - - .col3{ - @include column(3); - } - .col3.addbutton{ - width:auto; - } - .col6{ - @include column(6); - } - .col9{ - @include column(9); - } - .breadcrumb{ - margin-left:-($desktop-nice-padding); - margin-right:-($desktop-nice-padding); - } - } footer{ width:80%; margin-left:50px; @@ -900,13 +777,8 @@ footer, .logo{ .wrapper{ max-width:$breakpoint-desktop-larger; } - .nav-wrapper{ - @include box-shadow(inset -6px 0px 4px 0px rgba(0, 0, 0, 0.2)); - - .inner{ - background:$color-grey-1; - @include box-shadow(inset -6px 0px 4px 0px rgba(0, 0, 0, 0.2)); - } + .nav-wrapper .inner{ + background:$color-grey-1; } footer{ diff --git a/wagtail/wagtailadmin/static/wagtailadmin/scss/fonts/wagtail.svg b/wagtail/wagtailadmin/static/wagtailadmin/scss/fonts/wagtail.svg index dcfa5a08c..f25359ec6 100755 --- a/wagtail/wagtailadmin/static/wagtailadmin/scss/fonts/wagtail.svg +++ b/wagtail/wagtailadmin/static/wagtailadmin/scss/fonts/wagtail.svg @@ -6,6 +6,7 @@ +<<<<<<< HEAD @@ -71,4 +72,72 @@ - \ No newline at end of file + +======= + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +>>>>>>> master diff --git a/wagtail/wagtailadmin/static/wagtailadmin/scss/layouts/login.scss b/wagtail/wagtailadmin/static/wagtailadmin/scss/layouts/login.scss index a8164272d..3e158e51f 100644 --- a/wagtail/wagtailadmin/static/wagtailadmin/scss/layouts/login.scss +++ b/wagtail/wagtailadmin/static/wagtailadmin/scss/layouts/login.scss @@ -82,7 +82,7 @@ form{ .field{ padding:0; } - .field.icon:before{ + .iconfield:before{ display:none; } @@ -168,24 +168,29 @@ form{ font-size:4em; } - .field.icon:before{ - display:inline-block; - position: absolute; - color:$color-grey-4; - border: 2px solid $color-grey-4; - border-radius: 100%; - width: 1em; - padding: 0.3em; - left: $desktop-nice-padding; - margin-top: -1em; - top: 50%; - } - .full{ margin:0px (-$desktop-nice-padding); - input{ - padding-left:($desktop-nice-padding + 50px); + .iconfield{ + &:before{ + display:inline-block; + position: absolute; + color:$color-grey-4; + border: 2px solid $color-grey-4; + border-radius: 100%; + width: 1em; + padding: 0.3em; + left: $desktop-nice-padding; + margin-top: -1.1rem; + top: 50%; + font-size:1.3rem; + } + + input{ + padding-left:($desktop-nice-padding + 50px); + } } + + } } \ No newline at end of file diff --git a/wagtail/wagtailadmin/static/wagtailadmin/scss/layouts/page-editor.scss b/wagtail/wagtailadmin/static/wagtailadmin/scss/layouts/page-editor.scss index e7fa55c7c..c9a22b3ac 100644 --- a/wagtail/wagtailadmin/static/wagtailadmin/scss/layouts/page-editor.scss +++ b/wagtail/wagtailadmin/static/wagtailadmin/scss/layouts/page-editor.scss @@ -148,7 +148,6 @@ display:block; float:none; - .help{ display:none; } @@ -343,6 +342,10 @@ footer .preview{ @include column(10); padding-left:0; padding-right:0; + + fieldset{ + width:100%; + } } .object-help{ @@ -371,6 +374,12 @@ footer .preview{ .field{ padding:0; } + .field-content{ + display: block; + float: none; + width: auto; + padding: inherit; + } } .multiple{ @include column(10); @@ -381,5 +390,12 @@ footer .preview{ &.empty .add{ margin:0 0 0 -50px; } + + &.single-field label{ + display: block; + float: none; + width: auto; + padding:auto; + } } } diff --git a/wagtail/wagtailadmin/static/wagtailadmin/scss/userbar.scss b/wagtail/wagtailadmin/static/wagtailadmin/scss/userbar.scss index 84b99b537..af9e20195 100644 --- a/wagtail/wagtailadmin/static/wagtailadmin/scss/userbar.scss +++ b/wagtail/wagtailadmin/static/wagtailadmin/scss/userbar.scss @@ -87,11 +87,13 @@ li, .home{ .action{ @include transition(background-color 0.2s ease, color 0.2s ease); background-color:$color-teal; - color:white; + color:$color-teal; &:before{ margin-right:0.4em; vertical-align:middle; + font-size:1.7em; + color:white; } &:hover{ diff --git a/wagtail/wagtailadmin/static/wagtailadmin/scss/variables.scss b/wagtail/wagtailadmin/static/wagtailadmin/scss/variables.scss index 3533bd876..4c06efec8 100644 --- a/wagtail/wagtailadmin/static/wagtailadmin/scss/variables.scss +++ b/wagtail/wagtailadmin/static/wagtailadmin/scss/variables.scss @@ -42,7 +42,7 @@ $color-grey-5: #fafafa; $color-thead-bg: $color-grey-5; $color-header-bg: $color-teal; // #ff6a58; $color-fieldset-hover: $color-grey-5; -$color-input-border: $color-grey-3; +$color-input-border: $color-grey-4; $color-input-focus: #f4fcfc; $color-input-error-bg: #feedee; $color-button: $color-teal; diff --git a/wagtail/wagtailadmin/tasks.py b/wagtail/wagtailadmin/tasks.py index 3d6f3e8f1..59779d36b 100644 --- a/wagtail/wagtailadmin/tasks.py +++ b/wagtail/wagtailadmin/tasks.py @@ -85,3 +85,16 @@ def send_notification(page_revision_id, notification, excluded_user_id): # Send email send_mail(email_subject, email_content, from_email, email_addresses) + + +@task +def send_email_task(email_subject, email_content, email_addresses, from_email=None): + if not from_email: + if hasattr(settings, 'WAGTAILADMIN_NOTIFICATION_FROM_EMAIL'): + from_email = settings.WAGTAILADMIN_NOTIFICATION_FROM_EMAIL + elif hasattr(settings, 'DEFAULT_FROM_EMAIL'): + from_email = settings.DEFAULT_FROM_EMAIL + else: + from_email = 'webmaster@localhost' + + send_mail(email_subject, email_content, from_email, email_addresses) diff --git a/wagtail/wagtailadmin/templates/wagtailadmin/edit_handlers/field_panel_field.html b/wagtail/wagtailadmin/templates/wagtailadmin/edit_handlers/field_panel_field.html index 602efa583..472cae0b2 100644 --- a/wagtail/wagtailadmin/templates/wagtailadmin/edit_handlers/field_panel_field.html +++ b/wagtail/wagtailadmin/templates/wagtailadmin/edit_handlers/field_panel_field.html @@ -1,18 +1,23 @@
- {% if field_type != "boolean_field" %}{{ field.label_tag }}{% endif %} - {% block form_field %} - {{ field }} - {% endblock %} - {% if field_type = "boolean_field" %}{{ field.label_tag }}{% endif %} + {{ field.label_tag }} +
+
+ {% block form_field %} + {{ field }} + {% endblock %} + +
+ {% if field.help_text %} +

{{ field.help_text }}

+ {% endif %} + + {% if field.errors %} +

+ {% for error in field.errors %} + {{ error }} + {% endfor %} +

+ {% endif %} +
-{% if field.errors %} -

- {% for error in field.errors %} - {{ error }} - {% endfor %} -

-{% endif %} -{% if field.help_text %} -

{{ field.help_text }}

-{% endif %} diff --git a/wagtail/wagtailadmin/templates/wagtailadmin/login.html b/wagtail/wagtailadmin/templates/wagtailadmin/login.html index 9cb28ed86..012dd32f8 100644 --- a/wagtail/wagtailadmin/templates/wagtailadmin/login.html +++ b/wagtail/wagtailadmin/templates/wagtailadmin/login.html @@ -28,15 +28,19 @@
  • -
    +
    {{ form.username.label_tag }} - {{ form.username }} +
    + {{ form.username }} +
  • -
    +
    {{ form.password.label_tag }} - {{ form.password }} +
    + {{ form.password }} +
    {% if show_password_reset %}

    {% trans "Forgotten it?" %}

    diff --git a/wagtail/wagtailadmin/templates/wagtailadmin/pages/_editor_css.html b/wagtail/wagtailadmin/templates/wagtailadmin/pages/_editor_css.html index 9c6e832e8..2e140c89c 100644 --- a/wagtail/wagtailadmin/templates/wagtailadmin/pages/_editor_css.html +++ b/wagtail/wagtailadmin/templates/wagtailadmin/pages/_editor_css.html @@ -4,11 +4,6 @@ CSS declarations to be included on the 'create page' and 'edit page' views {% endcomment %} -{% comment %} - TODO: have a mechanism for sub-apps to specify their own declarations - - ideally wagtailadmin shouldn't have to know anything at all about wagtailimages and friends -{% endcomment %} - {% compress css %} diff --git a/wagtail/wagtailadmin/templates/wagtailadmin/pages/_editor_js.html b/wagtail/wagtailadmin/templates/wagtailadmin/pages/_editor_js.html index 6efaecf12..37d600f07 100644 --- a/wagtail/wagtailadmin/templates/wagtailadmin/pages/_editor_js.html +++ b/wagtail/wagtailadmin/templates/wagtailadmin/pages/_editor_js.html @@ -4,6 +4,11 @@ Javascript declarations to be included on the 'create page' and 'edit page' views {% endcomment %} + {% compress js %} @@ -14,21 +19,9 @@ - - - - {% comment %} - TODO: use the insert_editor_js hook to inject things like image-chooser.js and hallo-wagtailimage.js - from their respective apps such as wagtailimages - - ideally wagtailadmin shouldn't have to know anything at all about wagtailimages. - TODO: a method of injecting these sorts of things on demand when the modal is spawned. - {% endcomment %} - - - {% hook_output 'insert_editor_js' %} @@ -41,19 +34,10 @@ {% comment %} Additional js from widgets media. Allows for custom widgets in admin panel. - Can be used for TODO above (including image-choser.js at wagtailimages) {% endcomment %} {{ edit_handler.form.media.js }} ', + ((settings.STATIC_URL, filename) for filename in js_files) + ) + return js_includes + format_html( + """ + + """, + urlresolvers.reverse('wagtaildocs_chooser') + ) +hooks.register('insert_editor_js', editor_js) diff --git a/wagtail/wagtailembeds/embeds.py b/wagtail/wagtailembeds/embeds.py index d66c5ebcc..f8ab35f16 100644 --- a/wagtail/wagtailembeds/embeds.py +++ b/wagtail/wagtailembeds/embeds.py @@ -152,6 +152,17 @@ def get_embed(url, max_width=None, finder=None): finder = get_default_finder() embed_dict = finder(url, max_width) + # Make sure width and height are valid integers before inserting into database + try: + embed_dict['width'] = int(embed_dict['width']) + except (TypeError, ValueError): + embed_dict['width'] = None + + try: + embed_dict['height'] = int(embed_dict['height']) + except (TypeError, ValueError): + embed_dict['height'] = None + # Create database record embed, created = Embed.objects.get_or_create( url=url, diff --git a/wagtail/wagtailembeds/tests.py b/wagtail/wagtailembeds/tests.py index e3ac82d2b..b1eefdb17 100644 --- a/wagtail/wagtailembeds/tests.py +++ b/wagtail/wagtailembeds/tests.py @@ -8,6 +8,20 @@ class TestEmbeds(TestCase): def setUp(self): self.hit_count = 0 + def dummy_finder(self, url, max_width=None): + # Up hit count + self.hit_count += 1 + + # Return a pretend record + return { + 'title': "Test: " + url, + 'type': 'video', + 'thumbnail_url': '', + 'width': max_width if max_width else 640, + 'height': 480, + 'html': "

    Blah blah blah

    ", + } + def test_get_embed(self): embed = get_embed('www.test.com/1234', max_width=400, finder=self.dummy_finder) @@ -31,20 +45,23 @@ class TestEmbeds(TestCase): embed = get_embed('www.test.com/4321', finder=self.dummy_finder) self.assertEqual(self.hit_count, 3) - def dummy_finder(self, url, max_width=None): - # Up hit count - self.hit_count += 1 - - # Return a pretend record + def dummy_finder_invalid_width(self, url, max_width=None): + # Return a record with an invalid width return { 'title': "Test: " + url, 'type': 'video', 'thumbnail_url': '', - 'width': max_width if max_width else 640, + 'width': '100%', 'height': 480, 'html': "

    Blah blah blah

    ", } + def test_invalid_width(self): + embed = get_embed('www.test.com/1234', max_width=400, finder=self.dummy_finder_invalid_width) + + # Width must be set to None + self.assertEqual(embed.width, None) + class TestChooser(TestCase): def setUp(self): diff --git a/wagtail/wagtailembeds/wagtail_hooks.py b/wagtail/wagtailembeds/wagtail_hooks.py index 0db627881..89c5e66a5 100644 --- a/wagtail/wagtailembeds/wagtail_hooks.py +++ b/wagtail/wagtailembeds/wagtail_hooks.py @@ -1,4 +1,7 @@ +from django.conf import settings from django.conf.urls import include, url +from django.core import urlresolvers +from django.utils.html import format_html from wagtail.wagtailadmin import hooks from wagtail.wagtailembeds import urls @@ -9,3 +12,18 @@ def register_admin_urls(): url(r'^embeds/', include(urls)), ] hooks.register('register_admin_urls', register_admin_urls) + + +def editor_js(): + return format_html(""" + + + """, + settings.STATIC_URL, + 'wagtailembeds/js/hallo-plugins/hallo-wagtailembeds.js', + urlresolvers.reverse('wagtailembeds_chooser') + ) +hooks.register('insert_editor_js', editor_js) diff --git a/wagtail/wagtailforms/__init__.py b/wagtail/wagtailforms/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/wagtail/wagtailforms/forms.py b/wagtail/wagtailforms/forms.py new file mode 100644 index 000000000..f17023a77 --- /dev/null +++ b/wagtail/wagtailforms/forms.py @@ -0,0 +1,87 @@ +import django.forms +from django.utils.datastructures import SortedDict + + +class BaseForm(django.forms.Form): + def __init__(self, *args, **kwargs): + kwargs.setdefault('label_suffix', '') + return super(BaseForm, self).__init__(*args, **kwargs) + + +class FormBuilder(): + formfields = SortedDict() + + def __init__(self, fields): + for field in fields: + options = self.get_options(field) + f = getattr(self, "create_"+field.field_type+"_field")(field, options) + self.formfields[field.clean_name] = f + + def get_options(self, field): + options = {} + options['label'] = field.label + options['help_text'] = field.help_text + options['required'] = field.required + options['initial'] = field.default_value + return options + + def create_singleline_field(self, field, options): + # TODO: This is a default value - it may need to be changed + options['max_length'] = 255 + return django.forms.CharField(**options) + + def create_multiline_field(self, field, options): + return django.forms.CharField(widget=django.forms.Textarea, **options) + + def create_date_field(self, field, options): + return django.forms.DateField(**options) + + def create_datetime_field(self, field, options): + return django.forms.DateTimeField(**options) + + def create_email_field(self, field, options): + return django.forms.EmailField(**options) + + def create_url_field(self, field, options): + return django.forms.URLField(**options) + + def create_number_field(self, field, options): + return django.forms.DecimalField(**options) + + def create_dropdown_field(self, field, options): + options['choices'] = map( + lambda x: (x.strip(), x.strip()), + field.choices.split(',') + ) + return django.forms.ChoiceField(**options) + + def create_radio_field(self, field, options): + options['choices'] = map( + lambda x: (x.strip(), x.strip()), + field.choices.split(',') + ) + return django.forms.ChoiceField(widget=django.forms.RadioSelect, **options) + + def create_checkboxes_field(self, field, options): + options['choices'] = [(x.strip(), x.strip()) for x in field.choices.split(',')] + options['initial'] = [x.strip() for x in field.default_value.split(',')] + return django.forms.MultipleChoiceField( + widget=django.forms.CheckboxSelectMultiple, **options + ) + + def create_checkbox_field(self, field, options): + return django.forms.BooleanField(**options) + + def get_form_class(self): + return type('WagtailForm', (BaseForm,), self.formfields) + + +class SelectDateForm(django.forms.Form): + date_from = django.forms.DateField( + required=False, + widget=django.forms.DateInput(attrs={'placeholder': 'Date from'}) + ) + date_to = django.forms.DateField( + required=False, + widget=django.forms.DateInput(attrs={'placeholder': 'Date to'}) + ) diff --git a/wagtail/wagtailforms/migrations/0001_initial.py b/wagtail/wagtailforms/migrations/0001_initial.py new file mode 100644 index 000000000..80cbdb2b6 --- /dev/null +++ b/wagtail/wagtailforms/migrations/0001_initial.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +from south.utils import datetime_utils as datetime +from south.db import db +from south.v2 import SchemaMigration +from django.db import models + +from wagtail.wagtailcore.compat import AUTH_USER_MODEL, AUTH_USER_MODEL_NAME + + +class Migration(SchemaMigration): + + depends_on = ( + ("wagtailcore", "0002_initial_data"), + ) + + def forwards(self, orm): + # Adding model 'FormSubmission' + db.create_table(u'wagtailforms_formsubmission', ( + (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), + ('form_data', self.gf('django.db.models.fields.TextField')()), + ('page', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['wagtailcore.Page'])), + ('submit_time', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), + )) + db.send_create_signal(u'wagtailforms', ['FormSubmission']) + + + def backwards(self, orm): + # Deleting model 'FormSubmission' + db.delete_table(u'wagtailforms_formsubmission') + + + models = { + u'auth.group': { + 'Meta': {'object_name': 'Group'}, + u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), + 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) + }, + u'auth.permission': { + 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, + 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), + u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) + }, + AUTH_USER_MODEL: { + 'Meta': {'object_name': AUTH_USER_MODEL_NAME}, + 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), + 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), + u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), + 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), + 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), + 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) + }, + u'contenttypes.contenttype': { + 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, + 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) + }, + u'wagtailcore.page': { + 'Meta': {'object_name': 'Page'}, + 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'pages'", 'to': u"orm['contenttypes.ContentType']"}), + 'depth': ('django.db.models.fields.PositiveIntegerField', [], {}), + 'has_unpublished_changes': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'live': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), + 'numchild': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), + 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_pages'", 'null': 'True', 'to': u"orm['%s']" % AUTH_USER_MODEL}), + 'path': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), + 'search_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), + 'seo_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), + 'show_in_menus': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), + 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), + 'url_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}) + }, + u'wagtailforms.formsubmission': { + 'Meta': {'object_name': 'FormSubmission'}, + 'form_data': ('django.db.models.fields.TextField', [], {}), + u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'page': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['wagtailcore.Page']"}), + 'submit_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) + } + } + + complete_apps = ['wagtailforms'] \ No newline at end of file diff --git a/wagtail/wagtailforms/migrations/__init__.py b/wagtail/wagtailforms/migrations/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/wagtail/wagtailforms/models.py b/wagtail/wagtailforms/models.py new file mode 100644 index 000000000..75f0eceee --- /dev/null +++ b/wagtail/wagtailforms/models.py @@ -0,0 +1,200 @@ +from django.db import models +from django.shortcuts import render +from django.utils.translation import ugettext_lazy as _ +from django.utils.text import slugify + +from unidecode import unidecode +import json +import re + +from wagtail.wagtailcore.models import Page, Orderable, UserPagePermissionsProxy, get_page_types +from wagtail.wagtailadmin.edit_handlers import FieldPanel +from wagtail.wagtailadmin import tasks + +from .forms import FormBuilder + + +FORM_FIELD_CHOICES = ( + ('singleline', _('Single line text')), + ('multiline', _('Multi-line text')), + ('email', _('Email')), + ('number', _('Number')), + ('url', _('URL')), + ('checkbox', _('Checkbox')), + ('checkboxes', _('Checkboxes')), + ('dropdown', _('Drop down')), + ('radio', _('Radio buttons')), + ('date', _('Date')), + ('datetime', _('Date/time')), +) + + +HTML_EXTENSION_RE = re.compile(r"(.*)\.html") + + +class FormSubmission(models.Model): + """Data for a Form submission.""" + + form_data = models.TextField() + page = models.ForeignKey(Page) + + submit_time = models.DateTimeField(auto_now_add=True) + + def get_data(self): + return json.loads(self.form_data) + + def __unicode__(self): + return self.form_data + + +class AbstractFormField(Orderable): + """Database Fields required for building a Django Form field.""" + + label = models.CharField( + max_length=255, + help_text=_('The label of the form field') + ) + field_type = models.CharField(max_length=16, choices=FORM_FIELD_CHOICES) + required = models.BooleanField(default=True) + choices = models.CharField( + max_length=512, + blank=True, + help_text=_('Comma seperated list of choices. Only applicable in checkboxes, radio and dropdown.') + ) + default_value = models.CharField( + max_length=255, + blank=True, + help_text=_('Default value. Comma seperated values supported for checkboxes.') + ) + help_text = models.CharField(max_length=255, blank=True) + + @property + def clean_name(self): + # unidecode will return an ascii string while slugify wants a + # unicode string on the other hand, slugify returns a safe-string + # which will be converted to a normal str + return str(slugify(unicode(unidecode(self.label)))) + + panels = [ + FieldPanel('label'), + FieldPanel('help_text'), + FieldPanel('required'), + FieldPanel('field_type', classname="formbuilder-type"), + FieldPanel('choices', classname="formbuilder-choices"), + FieldPanel('default_value', classname="formbuilder-default"), + ] + + class Meta: + abstract = True + ordering = ['sort_order'] + + +_FORM_CONTENT_TYPES = None + +def get_form_types(): + global _FORM_CONTENT_TYPES + if _FORM_CONTENT_TYPES is None: + _FORM_CONTENT_TYPES = [ + ct for ct in get_page_types() + if issubclass(ct.model_class(), AbstractForm) + ] + return _FORM_CONTENT_TYPES + + +def get_forms_for_user(user): + """Return a queryset of form pages that this user is allowed to access the submissions for""" + editable_pages = UserPagePermissionsProxy(user).editable_pages() + return editable_pages.filter(content_type__in=get_form_types()) + + +class AbstractForm(Page): + """A Form Page. Pages implementing a form should inhert from it""" + + form_builder = FormBuilder + is_abstract = True # Don't display me in "Add" + + def __init__(self, *args, **kwargs): + super(AbstractForm, self).__init__(*args, **kwargs) + if not hasattr(self, 'landing_page_template'): + template_wo_ext = re.match(HTML_EXTENSION_RE, self.template).group(1) + self.landing_page_template = template_wo_ext + '_landing.html' + + class Meta: + abstract = True + + def get_form_parameters(self): + return {} + + def process_form_submission(self, form): + # remove csrf_token from form.data + form_data = dict( + i for i in form.data.items() + if i[0] != 'csrfmiddlewaretoken' + ) + + FormSubmission.objects.create( + form_data=json.dumps(form_data), + page=self, + ) + + def serve(self, request): + fb = self.form_builder(self.form_fields.all()) + form_class = fb.get_form_class() + form_params = self.get_form_parameters() + + if request.method == 'POST': + form = form_class(request.POST, **form_params) + + if form.is_valid(): + self.process_form_submission(form) + # If we have a form_processing_backend call its process method + if hasattr(self, 'form_processing_backend'): + form_processor = self.form_processing_backend() + form_processor.process(self, form) + + # render the landing_page + # TODO: It is much better to redirect to it + return render(request, self.landing_page_template, { + 'self': self, + }) + else: + form = form_class(**form_params) + + return render(request, self.template, { + 'self': self, + 'form': form, + }) + + def get_page_modes(self): + return [ + ('form', 'Form'), + ('landing', 'Landing page'), + ] + + def show_as_mode(self, mode): + if mode == 'landing': + return render(self.dummy_request(), self.landing_page_template, { + 'self': self, + }) + else: + return super(AbstractForm, self).show_as_mode(mode) + + +class AbstractEmailForm(AbstractForm): + """A Form Page that sends email. Pages implementing a form to be send to an email should inherit from it""" + is_abstract = True # Don't display me in "Add" + + to_address = models.CharField(max_length=255, blank=True, help_text=_("Optional - form submissions will be emailed to this address")) + from_address = models.CharField(max_length=255, blank=True) + subject = models.CharField(max_length=255, blank=True) + + def process_form_submission(self, form): + super(AbstractEmailForm, self).process_form_submission(form) + + if self.to_address: + content = '\n'.join([x[1].label + ': ' + form.data.get(x[0]) for x in form.fields.items()]) + tasks.send_email_task.delay(self.subject, content, [self.to_address], self.from_address,) + + + class Meta: + abstract = True diff --git a/wagtail/wagtailforms/static/wagtailforms/js/page-editor.js b/wagtail/wagtailforms/static/wagtailforms/js/page-editor.js new file mode 100644 index 000000000..8e7398133 --- /dev/null +++ b/wagtail/wagtailforms/static/wagtailforms/js/page-editor.js @@ -0,0 +1,3 @@ +$(function(){ + +}); \ No newline at end of file diff --git a/wagtail/wagtailforms/templates/wagtailforms/index.html b/wagtail/wagtailforms/templates/wagtailforms/index.html new file mode 100644 index 000000000..c5ccc1aa4 --- /dev/null +++ b/wagtail/wagtailforms/templates/wagtailforms/index.html @@ -0,0 +1,15 @@ +{% extends "wagtailadmin/base.html" %} +{% load i18n %} +{% block titletag %}{% trans "Forms" %}{% endblock %} +{% block bodyclass %}menu-forms{% endblock %} +{% block content %} + {% trans "Forms" as forms_str %} + {% trans "Pages" as select_form_str %} + {% include "wagtailadmin/shared/header.html" with title=forms_str subtitle=select_form_str icon="form" %} + +
    +
    + {% include "wagtailforms/results_forms.html" %} +
    +
    +{% endblock %} diff --git a/wagtail/wagtailforms/templates/wagtailforms/index_submissions.html b/wagtail/wagtailforms/templates/wagtailforms/index_submissions.html new file mode 100644 index 000000000..a1b45f6d0 --- /dev/null +++ b/wagtail/wagtailforms/templates/wagtailforms/index_submissions.html @@ -0,0 +1,68 @@ +{% extends "wagtailadmin/base.html" %} +{% load i18n %} +{% load localize %} +{% block titletag %}{% blocktrans with form_title=form_page.title|capfirst %}Submissions of {{ form_title }}{% endblocktrans %}{% endblock %} +{% block bodyclass %}menu-snippets{% endblock %} +{% block extra_js %} + {% get_localized_datepicker_js %} + {% get_date_format_override as format_override %} + + +{% endblock %} +{% block content %} +
    +
    +
    +
    +
    +

    + {% blocktrans with form_title=form_page.title|capfirst %}Form data {{ form_title }}{% endblocktrans %} +

    +
    + +
    +
    + +
    +
    +
    +
    +
    + {% if submissions %} + {% include "wagtailforms/list_submissions.html" %} + + {% include "wagtailadmin/shared/pagination_nav.html" with items=submissions is_searching=False linkurl='-' %} + {# Here we pass an invalid non-empty URL name as linkurl to generate pagination links with the URL path omitted #} + {% else %} +

    {% blocktrans with title=form_page.title %}There have been no submissions of the '{{ title }}' form.{% endblocktrans %}

    + {% endif %} +
    +{% endblock %} diff --git a/wagtail/wagtailforms/templates/wagtailforms/list_forms.html b/wagtail/wagtailforms/templates/wagtailforms/list_forms.html new file mode 100644 index 000000000..b1958f5b2 --- /dev/null +++ b/wagtail/wagtailforms/templates/wagtailforms/list_forms.html @@ -0,0 +1,23 @@ +{% load i18n %} + + + + + + + + + + + {% for fp in form_pages %} + + + + + {% endfor %} + +
    {% trans "Title" %}{% trans "Origin" %}
    +

    {{ fp|capfirst }}

    +
    + {{ fp.content_type.name |capfirst }} ({{ fp.content_type.app_label }}.{{ fp.content_type.model }}) +
    \ No newline at end of file diff --git a/wagtail/wagtailforms/templates/wagtailforms/list_submissions.html b/wagtail/wagtailforms/templates/wagtailforms/list_submissions.html new file mode 100644 index 000000000..38b4185c7 --- /dev/null +++ b/wagtail/wagtailforms/templates/wagtailforms/list_submissions.html @@ -0,0 +1,27 @@ +{% load i18n %} +
    + + + + + + + + {% for heading in data_headings %} + + {% endfor %} + + + + {% for row in data_rows %} + + {% for cell in row %} + + {% endfor %} + + {% endfor %} + +
    {% trans "Submission Date" %}{{ heading }}
    + {{ cell }} +
    +
    diff --git a/wagtail/wagtailforms/templates/wagtailforms/results_forms.html b/wagtail/wagtailforms/templates/wagtailforms/results_forms.html new file mode 100644 index 000000000..6cf198553 --- /dev/null +++ b/wagtail/wagtailforms/templates/wagtailforms/results_forms.html @@ -0,0 +1,8 @@ +{% load i18n %} +{% if form_pages %} + {% include "wagtailforms/list_forms.html" %} + + {% include "wagtailadmin/shared/pagination_nav.html" with items=form_pages linkurl="wagtailforms_index" %} +{% else %} +

    {% trans "No form pages have been created." %}

    +{% endif %} diff --git a/wagtail/wagtailforms/tests.py b/wagtail/wagtailforms/tests.py new file mode 100644 index 000000000..8ec2ee5c3 --- /dev/null +++ b/wagtail/wagtailforms/tests.py @@ -0,0 +1,63 @@ +from django.test import TestCase + +from wagtail.wagtailcore.models import Page +from wagtail.wagtailforms.models import FormSubmission + +class TestFormSubmission(TestCase): + fixtures = ['test.json'] + + def test_get_form(self): + response = self.client.get('/contact-us/') + self.assertContains(response, """""") + self.assertNotContains(response, "Thank you for your feedback") + + def test_post_invalid_form(self): + response = self.client.post('/contact-us/', { + 'your-email': 'bob', 'your-message': 'hello world' + }) + self.assertNotContains(response, "Thank you for your feedback") + self.assertContains(response, "Enter a valid email address.") + + def test_post_valid_form(self): + response = self.client.post('/contact-us/', { + 'your-email': 'bob@example.com', 'your-message': 'hello world' + }) + self.assertNotContains(response, "Your email") + self.assertContains(response, "Thank you for your feedback") + + form_page = Page.objects.get(url_path='/home/contact-us/') + + self.assertTrue(FormSubmission.objects.filter(page=form_page, form_data__contains='hello world').exists()) + + +class TestFormsBackend(TestCase): + fixtures = ['test.json'] + + def test_cannot_see_forms_without_permission(self): + form_page = Page.objects.get(url_path='/home/contact-us/') + + self.client.login(username='eventeditor', password='password') + response = self.client.get('/admin/forms/') + self.assertFalse(form_page in response.context['form_pages']) + + def test_can_see_forms_with_permission(self): + form_page = Page.objects.get(url_path='/home/contact-us/') + + self.client.login(username='siteeditor', password='password') + response = self.client.get('/admin/forms/') + self.assertTrue(form_page in response.context['form_pages']) + + def test_can_get_submissions(self): + form_page = Page.objects.get(url_path='/home/contact-us/') + + self.client.login(username='siteeditor', password='password') + + response = self.client.get('/admin/forms/submissions/%d/' % form_page.id) + self.assertEqual(len(response.context['data_rows']), 2) + + response = self.client.get('/admin/forms/submissions/%d/?date_from=01%%2F01%%2F2014' % form_page.id) + self.assertEqual(len(response.context['data_rows']), 1) + + response = self.client.get('/admin/forms/submissions/%d/?date_from=01%%2F01%%2F2014&action=CSV' % form_page.id) + data_line = response.content.split("\n")[1] + self.assertTrue('new@example.com' in data_line) diff --git a/wagtail/wagtailforms/urls.py b/wagtail/wagtailforms/urls.py new file mode 100644 index 000000000..e3f6bf6a8 --- /dev/null +++ b/wagtail/wagtailforms/urls.py @@ -0,0 +1,9 @@ +from django.conf.urls import patterns, url + + +urlpatterns = patterns( + 'wagtail.wagtailforms.views', + url(r'^$', 'index', name='wagtailforms_index'), + url(r'^submissions/(\d+)/$', 'list_submissions', name='wagtailforms_list_submissions'), + +) diff --git a/wagtail/wagtailforms/views.py b/wagtail/wagtailforms/views.py new file mode 100644 index 000000000..2174642c6 --- /dev/null +++ b/wagtail/wagtailforms/views.py @@ -0,0 +1,104 @@ +import datetime +import unicodecsv + +from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger +from django.core.exceptions import PermissionDenied +from django.http import HttpResponse +from django.shortcuts import get_object_or_404, render +from django.contrib.auth.decorators import permission_required + +from wagtail.wagtailcore.models import Page +from wagtail.wagtailforms.models import FormSubmission, get_forms_for_user +from wagtail.wagtailforms.forms import SelectDateForm + + +@permission_required('wagtailadmin.access_admin') +def index(request): + p = request.GET.get("p", 1) + + form_pages = get_forms_for_user(request.user) + + paginator = Paginator(form_pages, 20) + + try: + form_pages = paginator.page(p) + except PageNotAnInteger: + form_pages = paginator.page(1) + except EmptyPage: + form_pages = paginator.page(paginator.num_pages) + + return render(request, 'wagtailforms/index.html', { + 'form_pages': form_pages, + }) + + +@permission_required('wagtailadmin.access_admin') +def list_submissions(request, page_id): + form_page = get_object_or_404(Page, id=page_id).specific + + if not get_forms_for_user(request.user).filter(id=page_id).exists(): + raise PermissionDenied + + data_fields = [ + (field.clean_name, field.label) + for field in form_page.form_fields.all() + ] + + submissions = FormSubmission.objects.filter(page=form_page) + + select_date_form = SelectDateForm(request.GET) + if select_date_form.is_valid(): + date_from = select_date_form.cleaned_data.get('date_from') + date_to = select_date_form.cleaned_data.get('date_to') + # careful: date_to should be increased by 1 day since the submit_time + # is a time so it will always be greater + if date_to: + date_to += datetime.timedelta(days=1) + if date_from and date_to: + submissions = submissions.filter(submit_time__range=[date_from, date_to]) + elif date_from and not date_to: + submissions = submissions.filter(submit_time__gte=date_from) + elif not date_from and date_to: + submissions = submissions.filter(submit_time__lte=date_to) + + if request.GET.get('action') == 'CSV': + # return a CSV instead + response = HttpResponse(content_type='text/csv; charset=utf-8') + response['Content-Disposition'] = 'attachment;filename=export.csv' + writer = unicodecsv.writer(response, encoding='utf-8') + + header_row = ['Submission date'] + [label for name, label in data_fields] + + writer.writerow(header_row) + for s in submissions: + data_row = [s.submit_time] + form_data = s.get_data() + for name, label in data_fields: + data_row.append(form_data.get(name)) + writer.writerow(data_row) + return response + + p = request.GET.get('p', 1) + paginator = Paginator(submissions, 20) + + try: + submissions = paginator.page(p) + except PageNotAnInteger: + submissions = paginator.page(1) + except EmptyPage: + submissions = paginator.page(paginator.num_pages) + + data_headings = [label for name, label in data_fields] + data_rows = [] + for s in submissions: + form_data = s.get_data() + data_row = [s.submit_time] + [form_data.get(name) for name, label in data_fields] + data_rows.append(data_row) + + return render(request, 'wagtailforms/index_submissions.html', { + 'form_page': form_page, + 'select_date_form': select_date_form, + 'submissions': submissions, + 'data_headings': data_headings, + 'data_rows': data_rows + }) diff --git a/wagtail/wagtailforms/wagtail_hooks.py b/wagtail/wagtailforms/wagtail_hooks.py new file mode 100644 index 000000000..277fc6e73 --- /dev/null +++ b/wagtail/wagtailforms/wagtail_hooks.py @@ -0,0 +1,28 @@ +from django.core import urlresolvers +from django.conf import settings +from django.conf.urls import include, url +from django.utils.translation import ugettext_lazy as _ + +from wagtail.wagtailadmin import hooks +from wagtail.wagtailadmin.menu import MenuItem + +from wagtail.wagtailforms import urls +from wagtail.wagtailforms.models import get_forms_for_user + +def register_admin_urls(): + return [ + url(r'^forms/', include(urls)), + ] +hooks.register('register_admin_urls', register_admin_urls) + +def construct_main_menu(request, menu_items): + # show this only if the user has permission to retrieve submissions for at least one form + if get_forms_for_user(request.user).exists(): + menu_items.append( + MenuItem(_('Forms'), urlresolvers.reverse('wagtailforms_index'), classnames='icon icon-form', order=700) + ) +hooks.register('construct_main_menu', construct_main_menu) + +def editor_js(): + return """""" % settings.STATIC_URL +hooks.register('insert_editor_js', editor_js) diff --git a/wagtail/wagtailimages/models.py b/wagtail/wagtailimages/models.py index f0be0fe4d..24fd1f0bf 100644 --- a/wagtail/wagtailimages/models.py +++ b/wagtail/wagtailimages/models.py @@ -4,7 +4,7 @@ import os.path from taggit.managers import TaggableManager from django.core.files import File -from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist, ValidationError +from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.db import models from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @@ -17,6 +17,8 @@ from unidecode import unidecode from wagtail.wagtailadmin.taggable import TagSearchable from wagtail.wagtailimages.backends import get_image_backend +from .utils import validate_image_format + class AbstractImage(models.Model, TagSearchable): title = models.CharField(max_length=255, verbose_name=_('Title') ) @@ -34,12 +36,7 @@ class AbstractImage(models.Model, TagSearchable): filename = prefix[:-1] + dot + extension return os.path.join(folder_name, filename) - def file_extension_validator(ffile): - extension = ffile.name.split(".")[-1].lower() - if extension not in ["gif", "jpg", "jpeg", "png"]: - raise ValidationError(_("Not a valid image format. Please use a gif, jpeg or png file instead.")) - - file = models.ImageField(verbose_name=_('File'), upload_to=get_upload_to, width_field='width', height_field='height', validators=[file_extension_validator]) + file = models.ImageField(verbose_name=_('File'), upload_to=get_upload_to, width_field='width', height_field='height', validators=[validate_image_format]) width = models.IntegerField(editable=False) height = models.IntegerField(editable=False) created_at = models.DateTimeField(auto_now_add=True) diff --git a/wagtail/wagtailimages/tests.py b/wagtail/wagtailimages/tests.py index 9c4ce6ea9..00d1245e6 100644 --- a/wagtail/wagtailimages/tests.py +++ b/wagtail/wagtailimages/tests.py @@ -4,9 +4,7 @@ from django.contrib.auth.models import User, Group, Permission from django.core.urlresolvers import reverse from django.core.files.uploadedfile import SimpleUploadedFile -import unittest2 as unittest - -from wagtail.tests.utils import login +from wagtail.tests.utils import login, unittest from wagtail.wagtailimages.models import get_image_model from wagtail.wagtailimages.templatetags import image_tags diff --git a/wagtail/wagtailimages/utils.py b/wagtail/wagtailimages/utils.py new file mode 100644 index 000000000..2f0c0e676 --- /dev/null +++ b/wagtail/wagtailimages/utils.py @@ -0,0 +1,28 @@ +import os + +from PIL import Image + +from django.core.exceptions import ValidationError +from django.utils.translation import ugettext_lazy as _ + + +def validate_image_format(f): + # Check file extension + extension = os.path.splitext(f.name)[1].lower()[1:] + + if extension == 'jpg': + extension = 'jpeg' + + if extension not in ['gif', 'jpeg', 'png']: + raise ValidationError(_("Not a valid image. Please use a gif, jpeg or png file with the correct file extension.")) + + if not f.closed: + # Open image file + file_position = f.tell() + f.seek(0) + image = Image.open(f) + f.seek(file_position) + + # Check that the internal format matches the extension + if image.format.upper() != extension.upper(): + raise ValidationError(_("Not a valid %s image. Please use a gif, jpeg or png file with the correct file extension.") % (extension.upper())) diff --git a/wagtail/wagtailimages/wagtail_hooks.py b/wagtail/wagtailimages/wagtail_hooks.py index f14d22904..51492d404 100644 --- a/wagtail/wagtailimages/wagtail_hooks.py +++ b/wagtail/wagtailimages/wagtail_hooks.py @@ -1,5 +1,7 @@ +from django.conf import settings from django.conf.urls import include, url from django.core import urlresolvers +from django.utils.html import format_html, format_html_join from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailadmin import hooks @@ -21,3 +23,23 @@ def construct_main_menu(request, menu_items): MenuItem(_('Images'), urlresolvers.reverse('wagtailimages_index'), classnames='icon icon-image', order=300) ) hooks.register('construct_main_menu', construct_main_menu) + + +def editor_js(): + js_files = [ + 'wagtailimages/js/hallo-plugins/hallo-wagtailimage.js', + 'wagtailimages/js/image-chooser.js', + ] + js_includes = format_html_join('\n', '', + ((settings.STATIC_URL, filename) for filename in js_files) + ) + return js_includes + format_html( + """ + + """, + urlresolvers.reverse('wagtailimages_chooser') + ) +hooks.register('insert_editor_js', editor_js) diff --git a/wagtail/wagtailsearch/tests/test_backends.py b/wagtail/wagtailsearch/tests/test_backends.py index b8b6ee3b1..bd4a64926 100644 --- a/wagtail/wagtailsearch/tests/test_backends.py +++ b/wagtail/wagtailsearch/tests/test_backends.py @@ -2,7 +2,7 @@ from django.test import TestCase from django.test.utils import override_settings from django.conf import settings from django.core import management -import unittest2 as unittest +from wagtail.tests.utils import unittest from wagtail.wagtailsearch import models, get_search_backend from wagtail.wagtailsearch.backends.db import DBSearch from wagtail.wagtailsearch.backends import InvalidSearchBackendError diff --git a/wagtail/wagtailsearch/tests/test_queries.py b/wagtail/wagtailsearch/tests/test_queries.py index 2ff2945de..7086d46f4 100644 --- a/wagtail/wagtailsearch/tests/test_queries.py +++ b/wagtail/wagtailsearch/tests/test_queries.py @@ -1,9 +1,8 @@ from django.test import TestCase from django.core import management from wagtail.wagtailsearch import models -from wagtail.tests.utils import login +from wagtail.tests.utils import login, unittest from StringIO import StringIO -import unittest2 as unittest class TestHitCounter(TestCase): diff --git a/wagtail/wagtailsnippets/permissions.py b/wagtail/wagtailsnippets/permissions.py index 57441f356..5a730909b 100644 --- a/wagtail/wagtailsnippets/permissions.py +++ b/wagtail/wagtailsnippets/permissions.py @@ -19,10 +19,12 @@ def user_can_edit_snippet_type(user, content_type): def user_can_edit_snippets(user): """ true if user has any permission related to any content type registered as a snippet type """ + snippet_content_types = get_snippet_content_types() if user.is_active and user.is_superuser: - return True + # admin can edit snippets iff any snippet types exist + return bool(snippet_content_types) - permissions = Permission.objects.filter(content_type__in=get_snippet_content_types()).select_related('content_type') + permissions = Permission.objects.filter(content_type__in=snippet_content_types).select_related('content_type') for perm in permissions: permission_name = "%s.%s" % (perm.content_type.app_label, perm.codename) if user.has_perm(permission_name): diff --git a/wagtail/wagtailsnippets/tests.py b/wagtail/wagtailsnippets/tests.py index 0ba40fac9..782fe9087 100644 --- a/wagtail/wagtailsnippets/tests.py +++ b/wagtail/wagtailsnippets/tests.py @@ -5,7 +5,7 @@ when you run "manage.py test". Replace this with more appropriate tests for your application. """ -import unittest2 as unittest +from wagtail.tests.utils import unittest from django.test import TestCase diff --git a/wagtail/wagtailsnippets/wagtail_hooks.py b/wagtail/wagtailsnippets/wagtail_hooks.py index 35468f7d8..3745d1a51 100644 --- a/wagtail/wagtailsnippets/wagtail_hooks.py +++ b/wagtail/wagtailsnippets/wagtail_hooks.py @@ -1,5 +1,7 @@ +from django.conf import settings from django.conf.urls import include, url from django.core import urlresolvers +from django.utils.html import format_html from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailadmin import hooks @@ -22,3 +24,15 @@ def construct_main_menu(request, menu_items): MenuItem(_('Snippets'), urlresolvers.reverse('wagtailsnippets_index'), classnames='icon icon-snippet', order=500) ) hooks.register('construct_main_menu', construct_main_menu) + + +def editor_js(): + return format_html(""" + + + """, + settings.STATIC_URL, + 'wagtailsnippets/js/snippet-chooser.js', + urlresolvers.reverse('wagtailsnippets_choose_generic') + ) +hooks.register('insert_editor_js', editor_js)