Skip to content

Instantly share code, notes, and snippets.

@DataGreed
Created November 30, 2019 03:07
Show Gist options
  • Save DataGreed/d54cc8af04168b7da8b5c70c120e4901 to your computer and use it in GitHub Desktop.
Save DataGreed/d54cc8af04168b7da8b5c70c120e4901 to your computer and use it in GitHub Desktop.
Swagger-UI for django-rest-framework (DRF) with CSRF and log in/log out support
{% load rest_framework %}
<!DOCTYPE html>
<html>
<head>
<title>Swagger</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" />
<style>
{# style DRF login prompts a bit to make it less ugly #}
.log-in-prompt{
font-family: sans-serif;
list-style-type: none;
float: right;
margin-right: 30px;
}
.log-in-prompt a{
text-decoration: none;
color: grey;
}
.log-in-prompt :visited{
color: grey;
}
.log-in-prompt ul{
padding-inline-start: 0px;
list-style-type: none;
}
</style>
</head>
<body>
<div class="log-in-prompt">
{# django rest framework log in/out prompt and current username #}
{% if user.is_authenticated %}
{% optional_logout request user %}
{% else %}
{% optional_login request %}
{% endif %}
</div>
<div id="swagger-ui"></div>
<script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
<script>
const ui = SwaggerUIBundle({
url: "{% url schema_url %}",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: "BaseLayout",
requestInterceptor: (req) => {
req.headers['X-CSRFToken'] = "{{csrf_token}}"
return req;
}
});
</script>
</body>
</html>
@DataGreed
Copy link
Author

DataGreed commented Nov 30, 2019

See https://www.django-rest-framework.org/topics/documenting-your-api/ for instruction on how to get swagger-ui working on DRF.

Replace the template provided by DRF manual with the one here to fix CSRF in POST-requests and add log in/ log out button

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment