简体   繁体   中英

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. 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." I've tried to set the content_type multiple ways with no luck. 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. 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. 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. Much easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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