Skip to main content
 首页 » 编程设计

python之向 django-cms 添加自定义占位符

2024年10月25日37zdz8207

我正在尝试创建自定义占位符以在网站上添加管理员可编辑的部分。 Django-cms' documentation对于添加它要做什么是非常通用的。

占位符存在于名为联系人 的单独应用中,该应用已添加到settings.py 文件

这是我到目前为止的代码(跳过导入以减少冗长):

模型.py

class ContactsPlaceholder(models.Model): 
    phone = models.CharField(max_length=100) 
    email = models.CharField(max_length=100) 
    address = models.TextField(max_length=700) 
    # your fields 
    my_placeholder = PlaceholderField('contacts_contactsplaceholder') 
    # your methods 
 
    def __unicode__(self): 
        return "Contacts Placeholder" 

views.py

def contacts(request): 
  # Load the the contacts from db 
  contactsfields = ContactsField.objects.all() 
  contacts_placeholder = ContactsPlaceholder.objects.all()  
  context = {"contactsfields" : contactsfields, "contacts_placeholder" : contacts_placeholder} 
  return render(request, "../templates/contacts.html", context)  
 
def contacts_placeholder_detail(request, id): # is this really useful? 
  object = get_object_or_404(ContactsPlaceholder, id=id) 
  return render_to_response('../templates/contacts_placeholder_detail.html', { 
      'object': object, 
  }, context_instance=RequestContext(request)) 

contacts.html

{% extends "base.html" %} 
{% load cms_tags %} 
{% block content %} 
<div> 
  <h1>Contacts</h1> 
 
  {% placeholder "contacts_placeholder" or %} 
   <p>Placeholder is empty</p> 
  {% endplaceholder %} 
</div> 
{% endblock content %} 

最后,admin.py

class ContactsPlaceholderAdmin(PlaceholderAdminMixin, admin.ModelAdmin): 
    # Editable fields 
    frontend_editable_fields = ("phone", "email", "address") 
    # Form fields order and sections 
    fieldsets = [ 
        (None,{"fields" : ["phone", "email", "address"]}) 
    ] 
 
admin.site.register(ContactsPlaceholder, ContactsPlaceholderAdmin) 

使用此配置,运行后

python manage.py syncdb
I do get "Placeholder is empty" in the html response, and of course the placeholder is not editable using the standard frontend editor, which was the desired behaviour.

Going to 127.0.0.1:8000/admin/ i can see the "Contacts Placeholder" table, however when I click it or try to add items I do get the following error:

OperationalError at /us/admin/contacts/contactsplaceholder/ 
no such column: contacts_contactsplaceholder.phone 

请您参考如下方法:

如果contacts() View 通过应用程序钩子(Hook)呈现,然后使用 {% placeholder "contacts_placeholder" %}在模板中将不起作用。

在通过 AppHook 连接到 CMS 的应用程序中使用占位符时,您必须使用 {% static_placeholder "MyPlaceholder" %}而不是通常的 {% Placeholder "MyPlaceholder" %}

如果您有一个应用程序或插件,您在其中创建了一个 PlaceholderField,那么在呈现它的模板中,您需要以下标记;

{% render_placeholder instance.placeholderfieldname %}