beatonma / django-wm

Automatic Webmention functionality for Django models
https://beatonma.org/webmentions_tester/
GNU General Public License v3.0
12 stars 2 forks source link

Mentions for models without a `slug` field #40

Closed campegg closed 1 year ago

campegg commented 1 year ago

More of a question than an issue: I have a couple of legacy models that do not have a slug field, and am wondering if it is possible to enable mentions for them. I have tried defining a slug in the model:

@property
def slug(self):
    return self.id

… but it doesn't seem to work; I get:

File "[_PATH TO DJANGO..._]/venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1709, in names_to_path
    raise FieldError(
        django.core.exceptions.FieldError: Cannot resolve keyword 'slug' into field. Choices are: [_MODEL FIELD NAMES..._]
    )

Is there a way I can work around this?

beatonma commented 1 year ago

Hey,

For now you should be able to set slug = None on your model to prevent inheriting it from MentionableMixin. You will also need to override the resolve_from_url_kwargs classmethod.

e.g.

# models.py
class Article(MentionableMixin, models.Model):
    title = models.CharField(max_length=64)
    content = models.TextField()

    slug = None

    def all_text(self) -> str:
        return self.content

    def get_absolute_url(self) -> str:
        return reverse("article", args=[self.pk])

    @classmethod
    def resolve_from_url_kwargs(cls, article_id: int, **url_kwargs) -> "Article":
        return Article.objects.get(pk=article_id)

# urls.py
urlpatterns = [
    path(
        "article/<int:article_id>/",
        ArticleView.as_view(),
        name="article",
        kwargs={
            "model_name": "sample_app.Article",
        },
    ),
]

The slug field will likely be removed from MentionableMixin in the next major release as it is no longer required (since 2.3.0) and only used to provide the default resolve_from_url_kwargs implementation.

campegg commented 1 year ago

Thanks @beatonma — much appreciated!