1st command will take terminal into current project directory.
2nd command is used to create StudentProfile app.
3rd command creates superuser(admin) for admin site.This command ask for username,email and password.

We are sort of extending basic User auth model to store the other information specific to student by providing one-to-one relation between StudentProfile and User:

Also in DIRS field in TEMPLATE dict in settings.py add path:['assets/static/',]
Also add 'StudentProfile' in Django Settings.py in INSTALLED_APPS at end this helps the server detecting new apps in project:

Now we will define controller (Django Views) for how to render login form and how to render student information after successfull login(we are creating very basic form because our main purpose is to create api which will communicate with android):

Explanation:-
1]Login:-this defination checks whether the request is 'POST' or 'GET' if It is 'GET', Then It will render the form for Signin.Else,if request is 'POST' then it will use data received from form and will try to authenticate user.If credentials are correct then user is LoggedIn else Error message is displayed.

2]display:- Once User is Successfully loggedin he is redirected to dispaly page which displays his information by rendering the html.

3]Logout:-This defination logs the user out.

NOTE:- We will just require to change our views to create the API's for communicating with android application.

Now we will create Urls (Routers) which will route us to different controller which will render pages for us:

Explanation:-
1]urlpatterns define url for invoking different controllers which either renders or redirects.
2]include is used to include all urls of apps.
3]We are adding urlpatterns for MEDIA_ROOT ('assets/') URL will be MEDIA_URL ('/media/').This will expose Media files from project directory.

Now We are Done with our Web App

2] Creating API's for Android Application:-As in one of the Note, I told it's very easy to create the API's.We will use same controller as created before for web application just we will have some small changes.

1]Login:-there are some minor changes in url '/api' is appended this is because now we are referring different set of controllers which we will use to communicate with application.
If the request method is 'GET' then there is significant changes in the code as compared to what we have in web app.This is because once we are logged in to the app and we close app with out logging out it must open profile page for us rither than a form.
we are checking request.session exist or not, If it exist then we will redirect to profile page directly and if it not then we will return the form containing csrf token(what is csrf and how it works we will discuss it later).

2]display:-rither than rendering the display page we are simply return JSON as HttpResponse to the apllication(i.e making controller work as REST API).we have serialize django model to JSON using serializers library provided by django itself for serializing models.

NOTE:-when request method is 'GET' and there is no session object associated with request we are rendering the page called api_login_workThrough.html,This was the work Through of which I thought of to use csrf mechanism of django to work with my android application.There may be better way,but I came up with this simple Idea.We will see how this work Through works in detail later in the article.

The api_login_workThrough.html resides in assets/static/html and contains:-

It looks same as that of StudentProfile urls.py,Actually Its Same the difference will be made by urls.py of basic_app.

In urls.py of basic_app(Main project app) add url pattern at end:-

urlpatterns =[
...,
...,
path('api/',include('api')), ]

We Created API for the User Student Profile.

Now Let's get Started with Android

OverView of Android Apllication

AsyncRequest:-Request Response Handler

packagecom.example.workstation.basic;importandroid.annotation.TargetApi;importandroid.content.Context;importandroid.os.Build;importandroid.util.Log;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.net.CookieStore;importjava.net.HttpCookie;importjava.net.HttpURLConnection;importjava.net.URI;importjava.net.URISyntaxException;importjava.net.URL;importjava.util.List;importjava.util.Map;importjavax.net.ssl.HttpsURLConnection;publicclassAsyncRequestextendsThread/* Thread is used to make the request response cycle asynchronous to help preventing the UI from being Unresponsive*/{finalStringTAG=AsyncRequest.class.getSimpleName();finalStringdomain_name;BasicCookieStorestore;/*Basic Cookie Store is Persistent Cookie Store implementation for Android used to store Cookie */StringResponseMsg=newString();//Response message received from (Django)serverintResponseCode;//Response code received from server (Code: (2xx for OK),(3xx for Redirects),(4xx for ClientError),(5xx for InternalSerer Error)StringResponseBody=newString();//It is Data Received from Server(HTTP response or File response or JSON response)Map<String,List<String>>ResponseHeader;//Response Header Received from ServerStringUrl=newString();//Url to which to send request and responseStringRequestBody=newString();//Request Body means Data to be sent to ServerfinalStringRequestType;//Type of Request(GET,POST)AsyncRequest(StringrequestType,Contextcontext)/* Context is accepted for CookieStore to initialize for the Application*/{RequestType=requestType;store=newBasicCookieStore(context);domain_name=context.getResources().getString(R.string.domain_name);}@TargetApi(Build.VERSION_CODES.N)@Overridepublicvoidrun(){try{URLurl=newURL(Url);URIuri=newURI(Url);HttpURLConnectionhttpconn=(HttpURLConnection)url.openConnection();/*HttpURLConnection is the class which establish the connection between client and server and exchange data
* using HTTP request response cycle.
* url.openConnection() establishes the connection between client and server */httpconn.setInstanceFollowRedirects(false);/*Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection
instance*/HttpsURLConnection.setFollowRedirects(false);/*Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class*/httpconn.setRequestMethod(RequestType);//set Types of RequestStringS="";for(HttpCookieH:store.get(newURI(domain_name)))S+=H+"; ";httpconn.setRequestProperty("Cookie",S);/*retriving the cookie from cookie store and sending back to the server(session_id,csrf_token,etc)*/if(RequestType=="POST"){DataOutputStreamoutput=newDataOutputStream(httpconn.getOutputStream());output.writeBytes(RequestBody);output.flush();output.close();}/* if the request is POST then we send data to the server this using output stream received from connection*/booleanredirect=false;// normally, 3xx is redirectintstatus=httpconn.getResponseCode();if(status!=HttpURLConnection.HTTP_OK){//if request succeds then skipif(status==HttpURLConnection.HTTP_MOVED_TEMP||status==HttpURLConnection.HTTP_MOVED_PERM||status==HttpURLConnection.HTTP_SEE_OTHER)//if response code is 3xx then it is redirect requestredirect=true;//set redirect to true}System.out.println("Response Code ... "+status);if(redirect){// when response code 3xx then we receive redirect url in header field called "location"StringnewUrl=httpconn.getHeaderField("Location");// get the cookie if need, for loginList<String>cookiesL=httpconn.getHeaderFields().get("set-cookie");Log.i(TAG,"run: "+httpconn.getHeaderFields());if(cookiesL!=null)for(Stringx:cookiesL)store.add(newURI(domain_name),HttpCookie.parse(x).get(0));// open the new connnection again on url recived from location headerurl=newURL(domain_name+newUrl);uri=newURI(domain_name+newUrl);Log.i(TAG,"run: "+url);httpconn.disconnect();httpconn=(HttpURLConnection)url.openConnection();httpconn.setInstanceFollowRedirects(false);HttpURLConnection.setFollowRedirects(false);httpconn.setRequestMethod("GET");//considered that redirect url will be GET request onlyS="";for(HttpCookieH:store.get(newURI(domain_name)))S+=H+"; ";httpconn.setRequestProperty("Cookie",S);Log.i(TAG,"CookiesSession--: "+S);/*same as processed for first request*/}Log.i(TAG,"run: "+httpconn);this.ResponseMsg=httpconn.getResponseMessage();//retriving response message from httpconn objectthis.ResponseCode=httpconn.getResponseCode();//response code is retrivedthis.ResponseHeader=httpconn.getHeaderFields();//getting header fieldsbyte[]b=newbyte[1024*1024];// reserving the memory for responsebodyintlen;len=(newDataInputStream(httpconn.getInputStream())).read(b);//reads complete response body from httpconn objectLog.i(TAG,"run: "+b.toString());this.ResponseBody=newString(b,0,len);//stores in responsebodyhttpconn.disconnect();}catch(IOExceptione){Log.e(TAG,"run: ",e);}catch(URISyntaxExceptione){Log.e(TAG,"run: ",e);}}/*Getters and Setters*/voidsetUrl(StringUrl){this.Url=Url;}voidsetRequestBody(StringRequestBody){this.RequestBody=RequestBody;}StringgetResponseMsg(){returnResponseMsg;}StringgetResponseBody(){returnResponseBody;}Map<String,List<String>>getResponseHeader(){returnResponseHeader;}}

BitmapD:-Loads the image asynchronously using url

packagecom.example.workstation.basic;importandroid.content.Context;importandroid.graphics.Bitmap;importandroid.graphics.BitmapFactory;importandroid.util.Log;importjava.io.IOException;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.URL;publicclassBitmapDextendsThread{BitmapB;StringUrl;publicvoidsetUrl(StringUrl){this.Url=Url;}//Url from which to fetch imagepublicvoidrun(){try{Log.e("src",Url);URLurl=newURL(Url);// converts string url to URL objectHttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//establishes connection between client and serverconnection.setDoInput(true);connection.connect();//connection is establishedInputStreaminput=connection.getInputStream();//retriving input stream to retrive image dataB=BitmapFactory.decodeStream(input);//convert input received to proper image format depending on headerLog.e("Bitmap","returned");}catch(IOExceptione){e.printStackTrace();Log.e("Exception",e.getMessage());}}publicBitmapgetBitmap(){returnB;}//getter for fetching bitmap}

BasicCookieStore:-Persistent Cookie store implementation

This git repo contains two classes from our application viz. BasicCookieStore and SeriallizableHttpCookie,2nd class supports the first class to serialize the httpcookie object to string and store in the cookie store.

MainActivity:-Provides the Login Page for User Login

packagecom.example.workstation.basic;importandroid.content.Intent;importandroid.support.v7.app.AppCompatActivity;importandroid.os.Bundle;importandroid.util.Log;importandroid.view.Menu;importandroid.view.View;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.Toast;importjava.net.CookieStore;importjava.net.HttpCookie;importjava.net.MalformedURLException;importjava.net.URI;importjava.net.URISyntaxException;publicclassMainActivityextendsAppCompatActivity{Stringdomain_name;BasicCookieStorestore;Stringcsrf_token=newString();@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);domain_name=getResources().getString(R.string.domain_name);//server domainstore=newBasicCookieStore(this);//Creating CookieStore for ApplicationAsyncRequestP=newAsyncRequest("GET",this);//AsyncRequest object to snrd requestP.setUrl(domain_name+this.getResources().getString(R.string.Login));//url to which to send requestP.start();//starting asynchronous processtry{P.join();//procced after process P is completed}catch(InterruptedExceptione){e.printStackTrace();}Log.i("FORM:---","onCreate: "+P.getResponseBody());/*remember of csrf work through i told of explaining in android
once we receive the workthrough file from server we are checking for substring at index 1 to 4 if it is word "form"
then we are retriving the csrf token from form generated by {%csrf_token%} tag in template and store it in a variable
In response header there is field called "set-cookie" which contains cookie to be set we retrive the data and store it in this store
*/if(P.getResponseBody().substring(1,5).equals("form")){csrf_token=P.getResponseBody().substring(61,61+64);Log.i("csrf_token:--","onCreate: "+csrf_token);try{store.add(newURI(domain_name),HttpCookie.parse(P.getResponseHeader().get("set-cookie").get(0)).get(0));}catch(URISyntaxExceptione){e.printStackTrace();}}/*then we check if it returns error substring if so then something has went wrong and we recreate the activity
else
if workthrough form and also error is not returned then it implies that the user session was saved in cookie store and hence we directly authenticate
user to the user data preview
*/else{if(P.getResponseBody().substring(0,5).equals("Error")){this.recreate();}else{IntentdashBoard=newIntent(this,DashBoard.class);//Explicit intent creationthis.finish();dashBoard.putExtra("displayData",P.getResponseBody());//sending response data to new intent i.e dashboardLog.i("JSON:::","onCreate: "+P.getResponseBody());store.loadAllCookies();Log.i("VC","SignIN: "+store.getCookies());startActivity(dashBoard);//starting the intent(control goes to dashboard activity)}}}// create an action bar button@OverridepublicbooleanonCreateOptionsMenu(Menumenu){returnsuper.onCreateOptionsMenu(menu);}/* this is function which is triggered when user click on login button*/voidSignIN(ViewB)throwsMalformedURLException,URISyntaxException,InterruptedException{Buttonb=(Button)B;EditTextusernameView=(EditText)findViewById(R.id.Email);EditTextpasswordView=(EditText)findViewById(R.id.Password);Stringusername=usernameView.getText().toString();//retriving username from username fieldStringpassword=passwordView.getText().toString();//retriving password from password fieldif(!username.isEmpty()&&!password.isEmpty())//username and password validations{b.setClickable(false);AsyncRequestP=newAsyncRequest("POST",this);//creating the login requestP.setUrl(domain_name+this.getResources().getString(R.string.Login));//setting login urlP.setRequestBody("username="+username+"&password="+password+"&csrfmiddlewaretoken="+csrf_token+"&LOGIN=LOGIN");//setting request body it contains(username,password and csrf token which is used for CSRF attack protection by django)P.start();//satrting the processP.join();//procced after process P is completedif(P.getResponseBody().substring(0,5).equals("ERROR"))//if response contains "ERROR" string then recreate activity{Toast.makeText(this,P.getResponseBody(),Toast.LENGTH_LONG).show();usernameView.setText("");passwordView.setText("");this.recreate();}else//if login is successful then create Dashboard activity{IntentdashBoard=newIntent(this,DashBoard.class);dashBoard.putExtra("displayData",P.getResponseBody());store.loadAllCookies();this.finish();startActivity(dashBoard);}}}}

DashBoard:-user profile preview

packagecom.example.workstation.basic;importandroid.content.Intent;importandroid.graphics.Bitmap;importandroid.os.Build;importandroid.support.annotation.RequiresApi;importandroid.support.v7.app.AppCompatActivity;importandroid.os.Bundle;importandroid.util.Log;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.widget.ImageView;importandroid.widget.RelativeLayout;importandroid.widget.TextView;importorg.json.JSONArray;importorg.json.JSONException;importorg.json.JSONObject;publicclassDashBoardextendsAppCompatActivity{booleanflag=true;Stringdomain_name;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_dash_board);this.domain_name=this.getResources().getString(R.string.domain_name);BitmapDB=newBitmapD();IntentDataIntent=getIntent();//receiving the intentJSONArrayobj=newJSONArray();try{obj=newJSONArray(DataIntent.getStringExtra("displayData"));//the received response from server was JSON serialized coverting it back to JSON Array}catch(JSONExceptione){e.printStackTrace();}try{Log.i("Json","SignIN: "+((JSONObject)((JSONObject)obj.get(0)).get("fields")).get("username"));}catch(JSONExceptione){e.printStackTrace();}//selectiong differnt elements from UI(xml)TextViewusername=(TextView)findViewById(R.id.username);TextViewfirstname=(TextView)findViewById(R.id.firstname);TextViewlastname=(TextView)findViewById(R.id.lastname);TextViewemail=(TextView)findViewById(R.id.email);ImageViewI=(ImageView)findViewById(R.id.ProfilePic);try{//setting appropiate value from JSON Arrayusername.setText("username : "+((JSONObject)((JSONObject)obj.get(0)).get("fields")).get("username"));lastname.setText(""+((JSONObject)((JSONObject)obj.get(0)).get("fields")).get("last_name"));firstname.setText(""+((JSONObject)((JSONObject)obj.get(0)).get("fields")).get("first_name"));email.setText("Email : "+((JSONObject)((JSONObject)obj.get(0)).get("fields")).get("email"));B.setUrl(domain_name+"/media/"+((JSONObject)((JSONObject)obj.get(1)).get("fields")).get("profile_pic"));//setting image url to BitmapD object which loads the image on other threadB.start();B.join();Bitmapbm=B.getBitmap();I.setImageBitmap(bm);}catch(JSONExceptione){e.printStackTrace();}catch(InterruptedExceptione){e.printStackTrace();}}@OverridepublicbooleanonCreateOptionsMenu(Menumenu){getMenuInflater().inflate(R.menu.actionbardb,menu);returnsuper.onCreateOptionsMenu(menu);}//triggers on clicking close icon and finishes activitypublicvoidClose(MenuItemi){this.finish();}//triggers on clicking logout icon and destroys the current session and finishes activity@RequiresApi(api=Build.VERSION_CODES.JELLY_BEAN)publicvoidLogOut(MenuItemi)throwsInterruptedException{AsyncRequestP=newAsyncRequest("GET",this);P.setUrl(domain_name+this.getResources().getString(R.string.Logout));//sends logout requestP.start();P.join();this.finish();}}

we are done with our Tutorial.I have shared only code snippet which are important for understanding ,rest all I have skipped because of the length of the Article.I am linking my web application repo and android application repo: