DDiran
DDiran

Reputation: 573

Issue with Page model when overriding serve()

I followed the instructions on the Wagtail Form Example on Github to create standard Django forms outside of Wagtail. This worked perfectly, however there is a new issue now.

On the pages where there are forms, the standard Page-related template code in base.html no longer works, namely:

        {% block title %}
            {% if self.seo_title %}{{ self.seo_title }}{% else %}{{ self.title }}{% endif %}
        {% endblock %}
        {% block title_suffix %}
            {% with self.get_site.site_name as site_name %}
                {% if site_name %}| {{ site_name }}{% endif %}
            {% endwith %}
        {% endblock %}

My serve() method override is as follows:

class MyPage(Page):
# My Code

    def serve(self, request):
        from .forms import MyForm

        if request.method == 'POST':

            form = MyForm(request.POST)

            if form.is_valid():
                my_data = form.save()

                return render(request, 'my_other_template.html', {
                        'page': self,
                        'my_data': my_data,
                    })

        else:
            form = MyForm()

        return render(request, 'my_template.html', {
            'page': self,
            'form': form,
        })

Any ideas on what's going wrong?

Upvotes: 0

Views: 447

Answers (1)

gasman
gasman

Reputation: 25227

You are using the variable self in your template code, but there is no self context variable being passed in the call to render - only page and form.

Using self in templates is discouraged, as it's incompatible with some template engines such as Jinja2. You should use page instead:

    {% if page.seo_title %}{{ page.seo_title }}{% else %}{{ page.title }}{% endif %}

Alternatively, if you don't want to update your template code, you can pass self in the call to render:

    return render(request, 'my_template.html', {
        'self': self,
        'page': self,
        'form': form,
    })

Upvotes: 1

Related Questions