Links Framework¶
Widgy core also provides a linking framework that allows any model to point to
any other model without really knowing which models are available for linking.
This is the mechanism by which Page Builder’s
Button
can link to Widgy
Mezzanine’s WidgyPage
without
even knowing that WidgyPage
exists. There are two components to the links
framework, LinkField
and the link registry.
Model Field¶
-
class
widgy.models.links.
LinkField
[source]¶ LinkField
is a subclass ofdjango.contrib.contenttypes.generic.GenericForeignKey
. If you want to add a link to any model, you can just add aLinkField
to it.from django.db import models from widgy.models import links class MyModel(models.Model): title = models.Charfield(max_length=255) link = links.LinkField()
LinkField
will automatically add the two required fields for GenericForeignKey, theContentType
ForeignKey and the PositiveIntegerField. If you need to override this, you can pass in thect_field
andfk_field
options that GenericForeignKey takes.
Note
Unfortunately, because Django currently lacks support for composite fields,
if you need to display the LinkField
in a form, there are a couple
of things you need to do.
- Your Form class needs to mixin the
LinkFormMixin
. - You need to explicitly define a
LinkFormField
on your Form class.
Hopefully in future iterations of Django, these steps will be obsoleted.
Registry¶
If you want to expose your model to the link framework to allow things to link to it, you need to do two things.
You need to register your model with the links registry.
from django.db import models from widgy.models import links class Blog(models.Model): # ... links.register(Blog)
The
register()
function also works as a class decorator.from django.db import models from widgy.models import links @links.register class Blog(models.Model): # ...
You need to make sure that your model defines a
get_absolute_url
method.