Debug School

rakesh kumar
rakesh kumar

Posted on

How to get access token from api and get the data from protected api to renders data in template file in django

api to get token

 path('api/token/', CustomAuthToken.as_view()),
Enter fullscreen mode Exit fullscreen mode

Image description
it gives access token using postman

Protected api
how to protect api refer reference

path('myemployee/', EmployeeAPIView.as_view()),
Enter fullscreen mode Exit fullscreen mode

Image description

step 1:set route in

Enter fullscreen mode Exit fullscreen mode

step2: in write a code inside function

def LoginPage(request):
    if request.method=='POST':
        if user is not None:  
            url = 'http://localhost:8000/myemployee/' 
            auth_response ='http://localhost:8000/api/token/', data={'username': username, 'password': pass1})
            token = auth_response.json().get('token') 
            headers = {                                                                                                                                                                                                                
           'Authorization': f'token {token}',
            response = requests.get(url, headers=headers)
            data = response.json() 

            return render(request, 'employee_list.html', {'employees': data,'token': token}) 
            return HttpResponse ("Username or Password is incorrect!!!")
    return render (request,'login.html')
Enter fullscreen mode Exit fullscreen mode

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">
            <td>Full Name</td>
           <a href="{% url 'employee_insert' %}" class="btn btn-outline-success">
                    <i class="fas fa-plus"></i> Add New
        {% for employee in employees %}
                    <a href="{% url 'employee_update' %}" class="btn text-secondary px-0">
                        <i class="far fa-edit fa-lg"></i>
                    <form action="{% url 'employee_delete' %}" 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>
        {% endfor %}

{% endblock content %}
Enter fullscreen mode Exit fullscreen mode


Image description

Image description

Top comments (0)