django comment system - content_type

40 views
Skip to first unread message

Adam Teale

unread,
Apr 22, 2014, 4:54:29 PM4/22/14
to django...@googlegroups.com
Hi Guys,

I'm attempting to replace the django.contrib comment app's "post_comment" using a view in views.py.

I have it working but I would like to check that I am doing it in an ok django friendly way.

The content_type that the request.POST['content_type'] returns is:

`myapp.mymodel`

When I try to use this as a content_type using: `"ContentType.objects.get_for_model(request.POST['content_type']).pk`
I get an error:

    'unicode' object has no attribute '_meta' 

Obviously it needs to be an object model - I need it to return an instance of *mymodel* so that I can add it to the Comment object and save it.

To get this to work I have used :

    myappStr = string.split(myapp.mymodel,'.')[0]   
    mymodelStr = string.split(myapp.mymodel,'.')[-1]
    
    contentType = ContentType.objects.get_by_natural_key(myappStr, mymodelStr)

This works, but I think I shouldn't need to split a string. Perhaps at some moment the content_type will actually return a model and this string split hack is going to fall apart.

Any ideas?

Many thanks!

Adam

Russell Keith-Magee

unread,
Apr 22, 2014, 9:01:12 PM4/22/14
to Django Users
Hi Adam,

There's no method to directly get the content type from a full model string (i.e., 'myapp.mymodel'). The ContentType model doesn't have a combined field - it has an app_label field and a model field, which can be combined to give the full model name. If you look at the source code for the comments app, it does a split (although it's doing a split to get the model from the app cache, not the content type).

If you're using Django 1.7 (currently in beta), there's a new option - the app cache includes a way to retrieve a model from a combined model name. You can then get the content type from the model:

from django.apps import apps
model = apps.get_model(request.POST['content_type'])
content_type = ContentType.objects.get_for_model(model)

However, internally, get_model is just doing a split anyway, so if you want the content type and not a model, you'd be just as well served by doing the split yourself.

Yours,
Russ Magee %-)

Reply all
Reply to author
Forward
0 new messages