0

I want pass model name as parameter to views.py
But it does not woork very well
Please guide me how to do this Thank you

when I go to http://127.0.0.1:8000/filter/image/party/
There is error said :

'unicode' object has no attribute 'objects'

but the terminal can print mm='Party'

Here is my code:

models.py:

class Party(models.Model):  
     ....
class Fun(models.Model):  
     .... 

urls.py:

urlpatterns = patterns('',
    url(r'^image/(?P<model>\w+)/$', views.object_list_1 ),

views.py:

def object_list_1(request, model):
    mm =  model.capitalize()
    obj_list = mm.objects.all()        
    template_name = 'filterimgs/%s_list.html' % mm.lower()
    return render_to_response(template_name, {'object_list': obj_list, 
                          context_instance=RequestContext(request))

2 Answers 2

5

Not sure why you think this would work: just calling capitalize() on a string doesn't magically transform it into a model class.

You'll need to look up the actual class by its name in Django's model registry. Luckily, there is a function for that: get_model.

from django.db.models.loading import get_model
cls = get_model(app_name, model)
obj_list = cls.objects.all() 
Sign up to request clarification or add additional context in comments.

Comments

0

You should map the model name to model class.

One way is using getattr to get model instance from app module.

from app_name import models

def object_list_1(request, model):
    mm =  model.capitalize()
    cls = getattr(models, mm)
    obj_list = cls.objects.all()
    template_name = 'filterimgs/%s_list.html' % mm.lower()
    return render_to_response(template_name, {'object_list': obj_list,
                          context_instance=RequestContext(request))

Or using explicit mapping:

name_to_model_class = {'Party': Party, 'Fun': Fun}

def object_list_1(request, model):
    mm =  model.capitalize()
    cls = name_to_model_class[mm]
    obj_list = cls.objects.all()
    template_name = 'filterimgs/%s_list.html' % mm.lower()
    return render_to_response(template_name, {'object_list': obj_list,
                          context_instance=RequestContext(request))

1 Comment

Thanks you let me know the problem:'Party' and Party is different

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.