开发者

Customizing django-comments

So, I'm using django.contrib.comments. I've installed it OK but rather than the unwieldy default comment form, I'd like to use a custom form template that just shows a textarea and submit button.

The rationale behind this is that user only see the form if they area already authenticated, and I'd like the keep the form simple and pick up their username etc automatically.

I've implemented a custom form, but am getting an error when I try to submit it.

Here's what I have in my template for the page with the comment开发者_运维技巧 form (entry is the object passed from the view):

{% load comments %}
{% render_comment_form for entry %}

And here's my HTML in /templates/comments/form.html:

{% if user.is_authenticated %}
    <p>Submit a comment:</p>
    <form action="/comments/post/" method="post">
    <textarea name="comment" id="id_comment" rows="2" style="width: 90%;"></textarea>
            <input type="hidden" name="options" value="{{ options }}" />
            <input type="hidden" name="target" value="{{ target }}" />
            <input type="hidden" name="gonzo" value="{{ hash }}" />
            <input type="hidden" name="next" value="{{ entry.get_absolute_url }}" /> 
             <span style="float:right;"><input type="submit" name="post" value="Add"></span>
    </form>
    {% else %}
        <p>Please <a href="/login/">log in</a> to post a comment.</p>
    {% endif %}

It renders okay initially, but when I try to submit the comment form, I get the following Django error:

Comment post not allowed (400)
Why:    Missing content_type or object_pk field.

Can anyone help?


The comment model uses a generic foreign key to map to the object for which the comment was made such as a blog entry. These are required hidden fields included in the standard comment form.

From django.contrib.comments.models

...
class CommentSecurityForm(forms.Form):
    """
    Handles the security aspects (anti-spoofing) for comment forms.
    """
    content_type  = forms.CharField(widget=forms.HiddenInput)
    object_pk     = forms.CharField(widget=forms.HiddenInput)
...

If you haven't changed the form class and only want to change the html template then you can include these fields by adding a for loop over all the hidden fields.

{% for hidden in form.hidden_fields %}
    {{ hidden }}
{% endfor %}


Fixed the problem by copying from Theju's app - in particular, see Joshua Works' comment on part 2.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜