문제

In this scenario, I have 2 or more models:

class Store(models.Model):
    name = models.CharField(max_length = 100)
    homepage = models.URLField(verify_exists = False)
    ....

class Product(models.Model):
    display = models.BooleanField(default = True)
    created = models.DateTimeField(auto_now_add = True)
    changed = models.DateTimeField(auto_now_add = True, auto_now = True)
    ....

These each need a different comment model/form. For instance:

  • the product comment I'd like to have some extra info like product rating, pros, cons, etc.
  • But for the store, I would like to have some fields like rate customer support, rate communication/response, boolean if shipping prices reasonable, etc.

Both those models would be subclassing the contrib Comments model so it is compatible with the existing admin and comments template tags.

However, it seems that the built-in comments settings from Django is fairly rigid, only allowing customisation of one model/form by using the get_model() and get_form() methods.

I've got it working properly in both cases using a different method, but it involves a great deal of code duplication and it's rather impractical if I were to add a 3rd or 4th type of comment subclass.

Does anyone know of a better way of doing this? I've tried searching StackOverflow but no results seem to resemble this use case.

도움이 되었습니까?

해결책

I ended up implementing an extra model which sits above the current Django contrib comments module.

The comments system is now much more flexible, allowing a variety of new functionality such as:

  • First and foremost, allows you to associate various comment models to specific target models
  • Link your comment models directly to the target model in ORM without any hacks like in the contrib comment module
  • Allows custom validation in forms and doesn't raise 500 if fields are invalid
  • Display comment previews in the current page, without having to redirect the user to a blank page
  • Easier to implement pre-post comment events WITHOUT using signals
  • Hooks into the contrib comment system, making it compatible with existing database/plugins/template tags/template filters
  • Maintains support for the comments "comment_was_posted" signal
  • Easy to theme. The model names are included in the form class names so you can specify styles for each forms.
  • Easy to override templates (See below)

This module is available at github if you're interested in helping with development and/or testing.

It is compatible with the contrib comments system, so many of the existing tags still work and you don't have to redo all your existing templates. Please see the documentation for further information.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top