Reputation: 99
in my view.py I have a def index(request): and def other(request):
In def other(request): I want to run the exact same code like def index(request): if request.method == 'POST': and else do something different
Copy the code from def index(request): to def other(request): after if request.method == 'POST': works but duplicate code is bad. If I do index(request) after the if statement, def other(request): return nothing.
What is the right method to achieve this?
@login_required
def other(request):
if request.method == 'POST':
# do the same like in def index(request):
index(request)
else:
# do somthing different
pass
return render(request, 'search/index.html')
@login_required
def index(request):
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
# do something
pass
return render(request, 'search/index.html')
Upvotes: 0
Views: 262
Reputation: 3827
You can redirect to index function using redirect function. let your url.py file contains something like
url(r'^index/$', 'app.views.index', name='index'),
then you can redirect your other view to index like
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
def index(request, *args, **kwargs):
# your index code
return HttpResponse(result)
def other(request, *args, **kwargs):
if request.method == 'POST':
return redirect(reverse('index', args=args, kwargs=kwargs))
else:
# else code for GET, PUT,...
if you don't want to redirect, follow the code below
def index(request, *args, **kwargs):
# your index code
return HttpResponse(result)
def other(request, *args, **kwargs):
if request.method == 'POST':
return index(request, *args, **kwargs)
else:
# else code for GET, PUT,...
Upvotes: 1