Reputation: 8648
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.
Upvotes: 1
Views: 2385
Reputation: 151491
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(...)
Upvotes: 0
Reputation: 1190
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()),
]
Upvotes: 1