开发者

Add a prefix do Django comment form

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?


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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜