Reputation: 421
I'm just wondering what you think the best practice is for class based views in Django.
On one hand, you have something like this which uses GET and POST.
class User_Logout(View):
def get(self, request):
auth.logout(request)
return HttpResponseRedirect(reverse('frontend-login'))
This would map to a urls.py containing:
from frontend.views import User_Logout
urlpatterns = patterns('',
url(r'logout$', User_Logout.as_view(), name="frontend-logout"),
)
Or, something that uses specific methods. For example, I could create a class called Score_Dashboard(View), encapsulating every page associated with scores as methods of that class.
Something along the lines of...
class Scores(View):
def score_one(self, request):
return HttpResponseRedirect('http://www.youtube.com')
def score_two(self, request):
return HttpResponseRedirect('http://www.youtube.com')
And then call each of these as a method of an instance of each class inside urls.py:
from views import Scores
scores = Scores()
urlpatterns = patterns('',
url(r'score_one$', scores.score_two, name="score_one"),
url(r'score_two$', scores.score_two, name="score_one"),
)
So my question is, which one is more 'proper' or even perhaps 'better' and why?
Another way to asking this is, should every page have its own class?
Thank you!
Upvotes: 2
Views: 247
Reputation: 3242
Regarding your question, it would be easier to catch different args in your URLs and process them in one view :
def scores(request, score):
if score == "score_one":
# do something
if score == "score_two":
# do something else
urlpatterns = patterns('',
url(r'(?P<score>score_one|score_two)$', scores, name="scores"),
)
Using Class Based Views in this situation is maybe not needed (especially if you're just redirecting).
Upvotes: 1
Reputation: 36181
If you don't need to use a Class Based view, don't use it.
The most simple definition of a view is with a function. Your views should already be organized per app so you don't need to create another subgroup (or if you really want to organize views inside an app, just create two different views file):
def score_one(request):
return HttpResponseRedirect('http://www.youtube.com')
def score_two(request):
return HttpResponseRedirect('http://www.youtube.com')
CBV should be reversed for case where you are extending built-in classes provide by Django, to make list of objects, change form, etc.
Upvotes: 1