简体   繁体   English

Django评论:无法设置内容类型

[英]Django-reviews: cannot set content-type

I'm using django-reviews (http://code.google.com/p/django-reviews/) and having trouble setting the content-type for a review. 我正在使用django-reviews(http://code.google.com/p/django-reviews/),并且无法设置评论的内容类型。 Simple example: 简单的例子:

def check_review(request): 
    if request.method == 'POST': 
        reviewed_item = get_object_or_404(MyModel, pk=request.POST['object_pk']) 
        review_form = ReviewForm(target_object=reviewed_item, data=request.POST) 
        review_form.content_type = ContentType.objects.get_for_model(MyModel) 

However the form's 'content_type' field has no value and the form has the error "(Hidden field content_type) This field is required." 但是,表单的“ content_type”字段没有值,并且表单具有错误“((隐藏字段content_type)此字段是必需的。”)。 I've tried to set the content_type multiple ways with no luck. 我尝试过多种方法来设置content_type,但是没有运气。 Any ideas? 有任何想法吗?

To clarify, I'm going with the assumption you see the form displayed, you fill it in the values and try to submit. 为了澄清,我假设您看到显示的表单,将其填写在值中并尝试提交。 At this point, you see form validation error indicating you need the hidden field filled in. Is that correct? 此时,您会看到表单验证错误,指示您需要填写隐藏字段。对吗?

If so, you need to set the content_type on the form before submitting. 如果是这样,则需要在提交之前在表单上设置content_type。 Normally I do something like this: 通常我会执行以下操作:

def check_review(request):
    if request.method == 'POST':
        reviewed_item = get_object_or_404(MyModel, pk=request.POST['object_pk'])
        review_form = ReviewForm(target_object=reviewed_item, data=request.POST)
        if review_form.is_valid():
            # do some processing here
    else:
        # We're just getting an unbound form
        reviewed_item = get_object_or_404(MyModel, pk=request.POST['object_pk'])
        review_form = ReviewForm(target_object=reviewed_item, data=request.POST)
        review_form.content_type = ContentType.objects.get_for_model(MyModel)
    # return with review_form in the template's context or what have you

I found that you can set form values with 我发现您可以使用

review_form.base_fields["content_type"] = ...

though this still didn't seem to work for content_type. 虽然这似乎仍然不适用于content_type。 This was actually a mistake on my part. 这实际上是我的错误。 I meant to instantiate a Review object after the form was validated and set the content_type on that object. 我的意思是在验证表单后实例化Review对象,并在该对象上设置content_type。 Much easier. 容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM