1

I am learning Django. I have 2 functions in my app, one for cats, and another for dogs (as an example). I have the following folder structure:

/myproject/templates <-- dogs.html, cats.html
/myproject/dogs/ <-- views.py, models.py etc
/myproject/cats/ <-- views.py, models.py etc

Now both cats and dogs have shared views, etc, but currently I am just repeating these in each views.py file. Is there a way to "import" views and definitions from one view to another quickly?

This would save me cut and pasting a lot of the work.

What are the dangers of this? E.g. could conflicts arise? etc.

dirn
  • 19,454
  • 5
  • 69
  • 74
alias51
  • 8,178
  • 22
  • 94
  • 166
  • Your question is clear but the problem youre trying fo solve is not. If you provide more exact details of your project, we can provide a more useful response – skzryzg Oct 11 '14 at 12:11

2 Answers2

1

sure, you can use inheritance and you should use CBV in this case

import Animal

class Dog(Animal):
    ....
    pass

class Cat(Animal):
    ....
    pass

You must change your urls.py as well

from django.conf.urls import url
from dogs.views import Dog
from cats.views import Cat

urlpatterns = [
    url(r'^dog/', Dog.as_view()),
    url(r'^dog/', Cat.as_view()),
]
Sasa
  • 1,172
  • 1
  • 15
  • 24
  • Thanks, what if I want a view to inherit all properties of multiple other views? – alias51 Oct 11 '14 at 11:01
  • you can't inherit another view with FBV (Function Based Views) in Django – Sasa Oct 11 '14 at 11:05
  • here is the good explanation why to use CBV http://stackoverflow.com/questions/14788181/class-based-views-vs-function-based-views – Sasa Oct 11 '14 at 11:06
0

The simplest thing is to have the URLs for cats and dogs point to the same views:

urlpatterns = patterns(
    'catsanddogs.views',
    url(r'^(?P<kind>dog|cat)/(?P<id>\d+)$', 'details'),
)

And then in catsanddogs.views:

def details(request, kind, id):
    if kind == "dog":
        ... whatever is specific to dogs ...
    elif kind == "cat":
        ... whatever is specific to cats ...
    else:
        raise ValueError("...")

    ... whatever applies to both ...
    return HttpResponse(...)
Louis
  • 146,715
  • 28
  • 274
  • 320