django 댓글 : 모델을 확장하지 않고 사용자 URL을 제거하려고합니다. 어떻게?

StackOverflow https://stackoverflow.com/questions/1456267

문제

Django에서 댓글 앱 확장에 대한 문서를 완전히 이해하고 있으며 자동 기능을 고수하고 싶습니다. 하지만...

현재 앱에서는 댓글과 함께 "URL"을 제출할 수 없습니다.

존재 최소 침습적 기본 설정의 이 필드가 주석 양식으로 나타나는 것을 방지하려면 어떻게해야합니까??

django 1 또는 트렁크를 사용하고 가능한 많은 일반/내장 (일반 뷰, 기본 주석 설정 등)을 사용합니다. 지금까지 단일 일반 뷰 래퍼 만 있습니다).

도움이 되었습니까?

해결책

이것은 잘 문서화되어 있습니다 주석 프레임 워크 사용자 정의.

앱이 사용할 모든 것이 있습니다 get_form, 서브 클래스를 반환합니다 CommentForm URL 필드가 튀어 나왔습니다. 같은 것 :

class NoURLCommentForm(CommentForm):
    """
    A comment form which matches the default djanago.contrib.comments one, but
    doesn't have a URL field.

    """
NoURLCommentForm.base_fields.pop('url')

다른 팁

어떤 이유로 든 Smileychris의 게시물에 대해 언급 할 수 없으므로 여기에 게시하겠습니다. 그러나 나는 Smileychris의 반응만으로 오류가 발생했습니다. Commilform이 제거한 게시물 키를 찾을 것이므로 get_comment_create_data 함수를 덮어 쓰야합니다. 그래서 여기에 세 필드를 제거한 후 코드가 있습니다.

class SlimCommentForm(CommentForm):
"""
A comment form which matches the default djanago.contrib.comments one, but with 3 removed fields
"""
def get_comment_create_data(self):
    # Use the data of the superclass, and remove extra fields
    return dict(
        content_type = ContentType.objects.get_for_model(self.target_object),
        object_pk    = force_unicode(self.target_object._get_pk_val()),
        comment      = self.cleaned_data["comment"],
        submit_date  = datetime.datetime.now(),
        site_id      = settings.SITE_ID,
        is_public    = True,
        is_removed   = False,
    )


SlimCommentForm.base_fields.pop('url')
SlimCommentForm.base_fields.pop('email')
SlimCommentForm.base_fields.pop('name')

이것은 당신이 덮어 쓰고있는 함수입니다

def get_comment_create_data(self):
    """
    Returns the dict of data to be used to create a comment. Subclasses in
    custom comment apps that override get_comment_model can override this
    method to add extra fields onto a custom comment model.
    """
    return dict(
        content_type = ContentType.objects.get_for_model(self.target_object),
        object_pk    = force_unicode(self.target_object._get_pk_val()),
        user_name    = self.cleaned_data["name"],
        user_email   = self.cleaned_data["email"],
        user_url     = self.cleaned_data["url"],
        comment      = self.cleaned_data["comment"],
        submit_date  = datetime.datetime.now(),
        site_id      = settings.SITE_ID,
        is_public    = True,
        is_removed   = False,
    )

나의 빠르고 더러운 해결책 : 나는 '이메일'과 'URL'필드를 숨기고 '이 필드가 필요하다'오류를 제거하기위한 임의의 가치로 숨겨진 필드를 만들었습니다.

우아하지는 않지만 빠르며 CommentForm을 서브 클래스 할 필요가 없었습니다. 주석을 추가하는 모든 작업은 템플릿에서 수행되었습니다. 이는 다음과 같습니다 (경고 : 실제 코드의 단순화 된 버전이므로 테스트되지 않음) :

{% get_comment_form for entry as form %}

<form action="{% comment_form_target %}" method="post"> {% csrf_token %}

{% for field in form %}

    {% if field.name != 'email' and field.name != 'url' %}
        <p> {{field.label}} {{field}} </p>
    {% endif %}

{% endfor %}

    <input type="hidden" name="email" value="foo@foo.foo" />
    <input type="hidden" name="url" value="http://www.foofoo.com" />

    <input type="hidden" name="next" value='{{BASE_URL}}thanks_for_your_comment/' />
    <input type="submit" name="post" class="submit-post" value="Post">
</form>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top