On Wed, Apr 23, 2014 at 4:54 AM, Adam Teale <adamteale@gmail.com> wrote:
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?
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 %-)
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAJxq84-44kXasOEHc_4z2yfU8DkTP1LUy__DX%3DpQdiCjkO_--w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment