开发者

Views and models as python package cannot be resolved

I'm fairly new to Django, and I try to get the hang of using modules for views and models. Strangely enough, the URls work fine.

  • My app structure is

    templatetags/
    urls/
    views/
    models.py
    t开发者_如何学JAVAests.py
    
  • The views-dir has an __init__.py, and animals.py, containing one view.

    from myapp.models import Animal
    from django.shortcuts import render_to_response
    
    def overview(request):
        objects = Animal.objects.all()
        return render_to_response('myapp/animal_list.html', {'objects': objects})
    
  • There's an animals.py in urls/, containing

    from myapp.views.animals import *
    urlpatterns = patterns('',
        url(r'^$', 'views.animals.overview', {}, 'myapp_animal_overview'),
    )
    

The result: Caught ViewDoesNotExist while rendering: Could not import views.animals. Error was: No module named animals

But it's there! Can anyone see where I go wrong here? My app consists of about 10 models, hence the need for splitting. Thank you very much in advance.


Well, generally, you don't need to import myapp.views.animals. The URL dispatcher imports the required view as necessary when the regex matches a requested URL, as per: https://docs.djangoproject.com/en/dev/topics/http/urls/#how-django-processes-a-request.

Generally speaking, I would expect your urls.py to look something like:

from django.conf import settings
from django.conf.urls.defaults import patterns, include, url # for example ...

urlpatterns = patterns('',
    url(r'^$', 'views.animals.overview'),
)


You were right, I didn't need that extra import.

What did work, was

    urlpatterns = patterns('',
        url(r'^$', 'myapp.views.animals.overview'),
    )

I needed to specify the app where the views were. Problem solved!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜