api to get token
path('api/token/', CustomAuthToken.as_view()),
it gives access token using postman
Protected api
how to protect api refer reference
path('myemployee/', EmployeeAPIView.as_view()),
step 1:set route in settings.py
path('login/',views.LoginPage,name='login')
step2: in view.py write a code inside function
def LoginPage(request):
if request.method=='POST':
username=request.POST.get('username')
pass1=request.POST.get('pass')
user=authenticate(request,username=username,password=pass1)
if user is not None:
url = 'http://localhost:8000/myemployee/'
auth_response = requests.post('http://localhost:8000/api/token/', data={'username': username, 'password': pass1})
token = auth_response.json().get('token')
print(token)
headers = {
'Authorization': f'token {token}',
}
response = requests.get(url, headers=headers)
data = response.json()
print(data)
return render(request, 'employee_list.html', {'employees': data,'token': token})
else:
return HttpResponse ("Username or Password is incorrect!!!")
return render (request,'login.html')
Step3:renders data in template file
{% extends "base.html" %}
{% block content %}
<h1>Welcome, {{ username }}!</h1>
<p>Your access token: {{ token }}</p>
<a href="{% url 'logout' %}" class="btn btn-primary">Logout</a>
<table class="table table-borderless">
<thead class="border-bottom font-weight-bold">
<tr>
<td>Full Name</td>
<td>Mobile</td>
<td>Position</td>
<td>
<a href="{% url 'employee_insert' %}" class="btn btn-outline-success">
<i class="fas fa-plus"></i> Add New
</a>
</td>
</tr>
</thead>
<tbody>
{% for employee in employees %}
<tr>
<td>{{employee.fullname}}</td>
<td>{{employee.mobile}}</td>
<td>{{employee.position}}</td>
<td>
<a href="{% url 'employee_update' employee.id %}" class="btn text-secondary px-0">
<i class="far fa-edit fa-lg"></i>
</a>
<form action="{% url 'employee_delete' employee.id %}" method="post" class="d-inline">
{% csrf_token %}
<button type="submit" class="btn">
<i class="far fa-trash-alt fa-lg text-danger float-right"></i>
</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
Output
Top comments (0)