views:

158

answers:

1

I would like to add a prefix to each django comment form. I'm using multiply comment forms in the same page and depsite it's working well, i don't like having many input fields with the same id attribute like <input type="text" name="honeypot" id="id_honeypot" />.

So, is there a way to tell django do add a prefix to each form instance? I know i can do it with other forms when i create a form instance in this waynewform = CustomForm(prefix="a") but using Django's comment system, this part is handled by a comment template tag {% get_comment_form for [object] as [varname] %}.

Can I tell to the template tag to add a prefix?

A: 

Well, I have an idea. Add your custom comments form and override __init__. You can generate prefix from target_object and set it to self.prefix:

def __init__(self, target_object, data=None, initial=None):
    ...

Or better, override BaseForm.add_prefix:

def add_prefix(self, field_name):
    """
    Returns the field name with a prefix appended, if this Form has a
    prefix set.

    Subclasses may wish to override.
    """
    return self.prefix and ('%s-%s' % (self.prefix, field_name)) or field_name

Update: Yes, you're right. Prefix wouldn't work, the main reason is the code in contrib.comments.views.comments.post_comment. So I've reread your question and if you only need to change "id" attribute use BaseForm.auto_id:

class CustomCommentForm(CommentForm):
    def __init__(self, target_object, data=None, initial=None):
        super(CustomCommentForm, self).__init__(target_object, data, initial)
        idprefix = target_object.__class__.__name__.lower()
        self.auto_id = idprefix + "_%s"
alex vasi
I tried using add_prefix in this way < def add_prefix(self, field_name): self.prefix = "test" return self.prefix and ('%s-%s' % (self.prefix, field_name)) or field_name >and yes it renders the form well: < <input type="hidden" id="id_test-content_type" value="stream.activity" name="test-content_type"> > but now it raises me an error : < Comment post not allowed (400)Why: Missing content_type or object_pk field. > It seems it doesn't know how to use the prefix for fetching fields.Any idea?Thanks for reply!
Stefan Manastirliu
See update text.
alex vasi