I have parameters to be sent to two views in views.py
, I can't (or don't know how to) merge these two because one need to be separated to generate plot image like this one, is there any possibilities I could send the parameters to two views simultaneously or is it possible to merge these two views? Thanks in advance
My urls.py be like this:
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import survat.survatapp.views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('survat.survatapp.views',
url(r'^list/$', 'listindex', name='list'),
url(r'^graph.png$', 'showimage'),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
And my views.py be like
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from survat.survatapp.models import Document
from survat.survatapp.forms import DocumentForm
from survat.survatapp.modules.survat_core import printall
from survat.survatapp.modules.survat_core2 import printcox
from django.http import HttpResponse
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import lifelines
from lifelines import CoxPHFitter,AalenAdditiveFitter
from django.http import HttpResponse
from matplotlib import pylab
from pylab import *
import PIL, PIL.Image, StringIO
def listindex(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# ert= form.cleaned_data['aalenMember']
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('survat.survatapp.views.listindex'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
def delete_matrix():
documents = Document.objects.all()
for document in documents:
document.delete()
if request.method == 'POST':
tempCox = []
tempAalen = []
timeColumn = request.POST.get('timeColumn', '')
tempCox.append(timeColumn)
tempAalen.append(timeColumn)
eventColumn = request.POST.get('eventColumn', '')
tempCox.append(eventColumn)
tempAalen.append(eventColumn)
coxMember = request.POST.get('coxMember', '')
aalenMember = request.POST.get('aalenMember', '')
coxMemberI = int(float(coxMember))
aalenMemberI = int(float(aalenMember))
coxCovariate = []
aalenCovariate = []
for j in range(1,coxMemberI):
coxCovariate.append(request.POST.get('coxCovariate'+str(j), ''))
tempCox.append(request.POST.get('coxCovariate'+str(j), ''))
for k in range(1,aalenMemberI):
aalenCovariate.append(request.POST.get('aalenCovariate'+str(k), ''))
tempAalen.append(request.POST.get('aalenCovariate'+str(k), ''))
ert = request.POST.get('coxMember', '')
ert = str(type(int(float(ert))))
else:
tempCox = []
tempAalen = []
ert = "niji"
timeColumn = "niji"
eventColumn = "niji"
coxMember = "niji"
aalenMember = "niji"
coxMemberI = "niji"
aalenMemberI = "niji"
coxCovariate = []
aalenCovariate = []
for j in range(1,20):
coxCovariate.append ("niji")
for k in range(1,20):
aalenCovariate.append ("niji")
asdf=printcox('prostate1.csv','dtime','status1','age','hg','sz','sg','pf','rx')
# Render list page with the documents and the form
return render_to_response(
'survatapp/list.html',
{'documents': documents, 'form': form, 'ert':ert, 'wer':tempAalen,'asdf':asdf},
context_instance=RequestContext(request)
)
def showimage(request):
def printaalen(*args):
module_dir = os.path.dirname(__file__) # get current directory
file_path = os.path.join(module_dir, 'prostate1.csv')
prostate_dataset=pd.read_csv(file_path)
# prostate_dataset=pd.read_csv(args[0])
prostate_dataset=prostate_dataset[list(args[1:])]
pdplot=prostate_dataset[list(args[3:])]
for x in prostate_dataset:
if (prostate_dataset[x].dtype=="object"):
cat=pd.Series(list(prostate_dataset[x]))
for y in pd.unique(cat):
prostate_dataset[x+'.'+y]=pd.get_dummies(cat)[y]
prostate_dataset.drop(x, axis=1, inplace=True)
else:
pass
aaf=AalenAdditiveFitter(fit_intercept=False)
aaf.fit(prostate_dataset,args[1],event_col=args[2])
aalenListPlot=list(prostate_dataset.columns.values)[2:]
aalenPlotTemp=[]
fig=plt.figure(1,figsize=(12,20))
fig.suptitle('Regression in Aalen\'s Additive Model', fontsize=20)
i=1
for x in aalenListPlot:
ax = plt.subplot(6,2,i)
xlabel('Time')
ylabel('Cumulative hazards')
aaf.plot( columns=[ x ], color='red',ax=ax )
i=i+1
plt.tight_layout()
plt.subplots_adjust(top=0.95)
return fig
printaalen('prostate1.csv','dtime','status1','age','hg','sz','sg','pf','rx')
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
if 'uploadAndAnalyze' in request.POST:
printaalen('prostate1.csv','dtime','status1','age','hg','sz','sg','pf')
else:
form = DocumentForm()
grid(True)
# Store image in a string buffer
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
pilImage = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
pilImage.save(buffer, "PNG")
pylab.close()
# Send buffer in a http response the the browser with the mime type image/png set
return HttpResponse(buffer.getvalue(), mimetype="image/png")