【问题标题】:'str' object has no attribute 'relative_url'“str”对象没有属性“relative_url”
【发布时间】:2016-09-20 22:21:14
【问题描述】:

在 wagtail 中加载模板标签时,我收到错误消息“str”对象没有属性“relative_url”。

这是我的标签代码:

from django import template
from home.models import *

register = template.Library()

@register.inclusion_tag('home/subscribe_form.html')
def test_vdcristo():
    return {}

这是我的 html 模板代码:

{% load wagtailcore_tags  vdecristo_tags %}
    <form action="{% pageurl page %}" method="POST">
     {% csrf_token %}
    <div class="shop-subscribe bg-color-green margin-bottom-40">
        <div class="container">
                <div class="row">
                    <div class="col-md-8 md-margin-bottom-20">
                            <h2>Subscribase para mantenerse<strong> informado</strong></h2>
                    </div>




                    <div class="col-md-4">
                            <div class="input-group">


                             <input type="text" class="form-control" placeholder="Correo Electronico..." {{ form.subscribase }}>
                                    <span class="input-group-btn">
                                            <button class="btn" type="submit"><i class="fa fa-envelope-o"></i></button>
                                    </span>

                            </div>

                                {{ form.subscribase.errors }}
                        </div>
                </div>
        </div><!--/end container-->
    </div>

 </form>

如果我删除该行:

<form action="{% pageurl page %}" method="POST">

表单内容已加载,但当然不会发布。有人可以帮我弄清楚如何解决这个问题吗?

【问题讨论】:

    标签: django django-forms tags django-templates wagtail


    【解决方案1】:

    这是失败的,因为您的模板代码引用了变量 pageform,但您没有从标记代码中传递它们。 (我希望在这里看到的错误是 'NoneType' object has no attribute 'relative_url' - 您的错误表明您将字符串作为 page 变量传递。)

    实现这项工作的一种可能方法:

    @register.inclusion_tag('home/subscribe_form.html')
    def test_vdcristo():
        # Look up the relevant form page by slug; replace FormPage and 'subscribe-now'
        # as appropriate for your site
        page = FormPage.objects.get(slug='subscribe-now')
        return {
            'page': page,
            'form': page.get_form(),
        }
    

    【讨论】:

    • 我现在在加载 test_vdcristo 标记时收到错误消息 KeyError at /radio/ 'request'。还有什么建议吗?
    • 您可能需要从父模板的上下文中检索 'request' 变量 - 请参阅 docs.djangoproject.com/en/1.9/howto/custom-template-tags/… 上有关 'takes_context' 的部分 - 并在您的变量列表中传递 'request': context['request']'回来了。
    • 传递 'request': context['request'] 解决了这个问题。谢谢!
    【解决方案2】:

    你应该使用

    {% url url_name %}
    

    (注意:url,而不是 pageurl)并在 urls 中定义了一个名为 page 的 url。

    【讨论】:

    • 这对于 Django 来说通常是正确的,但在 Wagtail 中,{% pageurl ... %} 是当您希望 URL 对应于 Wagtail 页面对象时使用的适当标签。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2019-03-25
    • 2017-05-13
    • 2014-04-28
    • 2015-05-15
    • 2019-06-20
    相关资源
    最近更新 更多