3

I'm using Django 1.4 and django-CMS 2.3.

I have several applications with apphooks, and I want, in django-CMS, to be able to refer to an object of an application.

In order to make sustainable links, I'm trying to find a plugin using django-CMS menus or generic foreign keys.

If nothing like this exists, what is the best generic foreign key application? I just made a small plugin using django.contrib.contenttypes that limits the choice to models with a get_absolute_url method, but it is just awful.

Thanks.

1 Answer 1

3

I just happened across your question. I've recently implemented something similar for a couple of projects, here's what I did based on the work by Adam Alton described here: http://adamalton.co.uk/blog/displaying-django-genericforeignkey-as-single-form-field/

This is not a CMSPlugin, however, so, I know this doesn't directly answer the question, but its what I have and I hope it can help others looking for a similar solution.

As an overview, I have a "Banner" type defined in my models which represents a banner on the front page of my customers' sites. Each banner can be linked to other content. In these cases, the link destination could be a Django-CMS page, or one of many other types. All have the method get_absolute_url defined, although, I don't use introspection to determine this, I just implemented get_absolute_url on all the types that would appear here. Anyway, here goes:

First, here's the simple model for Banner:

class Banner(models.Model):
  short_name       = models.CharField(max_length=64, unique=True)
  html             = models.TextField()
  link_text        = models.CharField(max_length=128, default='Learn more')
  destination_type = models.ForeignKey(ContentType, null=True, blank=True,
    limit_choices_to={"model__in": ("Page", "Project", "Person", "Client")}
  )
  destination_id   = models.PositiveIntegerField(null=True, blank=True)
  destination      = generic.GenericForeignKey('destination_type', 'destination_id')
  published        = models.BooleanField(blank=True, default=False)

  def __unicode__(self):
    return self.short_name

Here's my forms.py:

import re
from django.forms import ModelForm, ChoiceField
from cms.models import Page
from django.contrib.contenttypes.models import ContentType

from apps.your_application.models import Project, Person, Client

class BannerAdminForm(ModelForm):
  class Meta:
    model = Banner
    fields = ("short_name", "html", "link_text", "destination", "link_hash", "published",)

  # GenericForeignKey form field, will hold combined object_type and object_id
  destination = ChoiceField(required=False)  # Note the 'required=False' here.

  def __init__(self, *args, **kwargs):
    super(BannerAdminForm, self).__init__(*args, **kwargs)

    # Combine object_type and object_id into a single 'destination' field
    # Get all the objects that we want the user to be able to choose from

    # Note: The user is going to locate these by name, so we should
    # alphabetize all of these

    available_objects  = list(Page.objects.all().order_by('title_set__title'))
    available_objects += list(Project.objects.all().order_by('title'))
    available_objects += list(Person.objects.all().order_by('name'))
    available_objects += list(Client.objects.all().order_by('name'))

    # Now create our list of choices for the <select> field
    object_choices = []
    object_choices.append(["", "--"])
    for obj in available_objects:
      type_class = ContentType.objects.get_for_model(obj.__class__)
      type_id = type_class.id
      obj_id = obj.id
      form_value = "type:%s-id:%s" % (type_id, obj_id)  # e.g."type:12-id:3"
      display_text = "%s : %s" % (str(type_class), str(obj))  # E.g. "Client : Apple, Inc."
      object_choices.append([form_value, display_text])

    self.fields['destination'].choices = object_choices

    # If there is an existing value, pre-select it
    if self.instance.destination:
      type_class = ContentType.objects.get_for_model(self.instance.destination.__class__)
      type_id = type_class.id
      obj_id = self.instance.destination.id
      current_value = "type:%s-id:%s" % (type_id, obj_id)
      self.fields['destination'].initial = current_value

  def save(self, *args, **kwargs):
    try:
      #get object_type and object_id values from combined destination field
      object_string = self.cleaned_data['destination']
      matches = re.match("type:(\d+)-id:(\d+)", object_string).groups()
      object_type_id = matches[0]  # get 45 from "type:45-id:38"
      object_id = matches[1]       # get 38 from "type:45-id:38"
      object_type = ContentType.objects.get(id=object_type_id)
      self.cleaned_data['destination_type'] = object_type_id
      self.cleaned_data['destination_id'] = object_id
      self.instance.destination_id = object_id
      self.instance.destination_type = object_type
    except:
      # If anything goes wrong, leave it blank,
      # This is also the case for when '--' is chosen
      # In the drop-down (tsk, tsk, bad code style =/)
      self.cleaned_data['destination_type'] = None
      self.cleaned_data['destination_id'] = None
      self.instance.destination_id = None
      self.instance.destination_type = None

    return super(BannerAdminForm, self).save(*args, **kwargs)

You can then get the URL of the destination object by calling {% if banner.destination %}{{ banner.destination.get_absolute_url }}{% endif %} in your templates.

Works well and shouldn't be too tough to use in a CMSPlugin.

This is what it looks like in Django Admin

EDIT: Actually, I've just implemented this exact same thing as a CMSPlugin Form. There is essential zero differences. Just remember to add the form to your plugin class in your cms_plugins.py file like so:

class CMSBannerPlugin(CMSPluginBase):
  form = BannerAdminForm  #   <==== Don't forget this part
  model = Banner
  name = _("Banner Plugin")
  render_template = "apps/your_application/_banner.html"

  def render(self, context, instance, placeholder):
    ...
    return context

plugin_pool.register_plugin(CMSBannerPlugin)
4
  • in your models.py generic.GenericForeignKey is from django.contrib.contenttypes.fields import GenericForeignKey ?
    – andilabs
    Jun 5, 2014 at 17:22
  • I was just looking on dev (1.7) version. docs.djangoproject.com/en/dev/ref/contrib/contenttypes
    – andilabs
    Jun 5, 2014 at 17:59
  • @mkoistinen This helped me a great deal. Why does it have to be ChoiceField(required=False)?
    – creimers
    Mar 9, 2015 at 23:34
  • @creimers Glad you found it useful. In my implementation, I needed it to be optional, but I guess it could be mandatory. Been awhile since I used this. I have release a generic, reusable CMS plugin for this at github.com/mkoistinen/djangocms-styledlink.
    – mkoistinen
    Mar 10, 2015 at 0:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.