Django framework is a powerful Python web framework

Patient Tools

Read, save, and share this guide

Use these quick tools to make this medical article easier to read, print, save, or share with a family member.

Article Summary

The Django framework is a powerful Python web framework, and it comes with built-in security features that can be used out-of-the-box to prevent common web vulnerabilities. This cheat sheet lists actions and security tips developers can take to develop secure Django applications. It aims to cover common vulnerabilities to increase the security posture of your Django application. Each item has a brief explanation and relevant...

Key Takeaways

  • This article explains General Recommendations in simple medical language.
  • This article explains Authentication in simple medical language.
  • This article explains Key Management in simple medical language.
  • This article explains Headers in simple medical language.
Educational health guideWritten for patient understanding and clinical awareness.
Reviewed content workflowUse writer and reviewer profiles for stronger trust.
Emergency safety firstUrgent warning signs are highlighted below.

Seek urgent medical care if you notice

These warning signs are general safety guidance. Local emergency numbers and clinical judgment should always come first.

  • Severe symptoms, breathing difficulty, fainting, confusion, or rapidly worsening illness.
  • New weakness, severe pain, high fever, or symptoms after a serious injury.
  • Any symptom that feels urgent, unusual, or unsafe for the patient.
1

Emergency now

Use emergency care for severe, sudden, rapidly worsening, or life-threatening symptoms.

2

See a doctor

Book a professional medical evaluation if symptoms persist, worsen, recur often, affect daily activities, or occur in a high-risk patient.

3

Learn safely

Use this article to understand possible causes, tests, treatment options, prevention, and questions to ask your clinician.

The Django framework is a powerful Python web framework, and it comes with built-in security features that can be used out-of-the-box to prevent common web vulnerabilities. This cheat sheet lists actions and security tips developers can take to develop secure Django applications. It aims to cover common vulnerabilities to increase the security posture of your Django application. Each item has a brief explanation and relevant code samples that are specific to the Django environment.

The Django framework provides some built-in security features that aim to be secure-by-default. These features are also flexible to empower a developer to re-use components for complex use-cases. This opens up scenarios where developers unfamiliar with the inner workings of the components can configure them in an insecure way. This cheat sheet aims to enumerate some such use cases.

General Recommendations

  • Always keep Django and your application’s dependencies up-to-date to keep up with security vulnerabilities.
  • Ensure that the application is never in DEBUG mode in a production environment. Never run DEBUG = True in production.
  • Use packages like django_ratelimit or django-axes to prevent brute-force attacks.

Authentication

  • Use django.contrib.auth app for views and forms for user authentication operations such as login, logout, password change, etc. Include the module and its dependencies django.contrib.contenttypes and django.contrib.sessions in the INSTALLED_APPS setting in the settings.py file.
INSTALLED_APPS = [
    # ...
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    # ...
]
  • Use the @login_required decorator to ensure that only authenticated users can access a view. The sample code below illustrates usage of @login_required.
from django.contrib.auth.decorators import login_required

# User is redirected to default login page if not authenticated.
@login_required
def my_view(request):
  # Your view logic

# User is redirected to custom '/login-page/' if not authenticated.
@login_required(login_url='/login-page/')
def my_view(request):
  # Your view logic
  • Use password validators for enforcing password policies. Add or update the AUTH_PASSWORD_VALIDATORS setting in the settings.py file to include specific validators required by your application.
AUTH_PASSWORD_VALIDATORS = [
  {
    # Checks the similarity between the password and a set of attributes of the user.
    'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    'OPTIONS': {
      'user_attributes': ('username', 'email', 'first_name', 'last_name'),
      'max_similarity': 0.7,
    }
  },
  {
    # Checks whether the password meets a minimum length.
    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    'OPTIONS': {
      'min_length': 8,
    }
  },
  {
    # Checks whether the password occurs in a list of common passwords
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  },
  {
    # Checks whether the password isn’t entirely numeric
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  }
]
  • Store passwords using make-password utility function to hash a plain-text password.
from django.contrib.auth.hashers import make_password
#...
hashed_pwd = make_password('plaintext_password')
  • Check a plaintext password against a hashed password by using the check-password utility function.
from django.contrib.auth.hashers import check_password
#...
plain_pwd = 'plaintext_password'
hashed_pwd = 'hashed_password_from_database'

if check_password(plain_pwd, hashed_pwd):
  print("The password is correct.")
else:
  print("The password is incorrect.")

Key Management

The SECRET_KEY parameter in settings.py is used for cryptographic signing and should be kept confidential. Consider the following recommendations:

  • Generate a key at least 50 characters or more, containing a mix of letters, digits, and symbols.
  • Ensure that the SECRET_KEY is generated using a strong random generator, such as get_random_secret_key() function in Django.
  • Avoid hard coding the SECRET_KEY value in settings.py or any other location. Consider storing the key-value in environment variables or secrets managers.
import os
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
  • Regularly rotate the key, keeping in mind that this action can invalidate sessions, password reset tokens, etc. Rotate the key immediatley it if it ever gets exposed.

Headers

Include the django.middleware.security.SecurityMiddleware module in the MIDDLEWARE setting in your project’s settings.py to add security-related headers to your responses. This module is used to set the following parameters:

  • SECURE_CONTENT_TYPE_NOSNIFF: Set this key to True. Protects against MIME type sniffing attacks by enabling the header X-Content-Type-Options: nosniff.
  • SECURE_BROWSER_XSS_FILTER: Set this key to True. Enables the browser’s XSS filter by setting the header X-XSS-Protection: 1; mode=block.
  • SECURE_HSTS_SECONDS: Ensures the site is only accessible via HTTPS.

Include the django.middleware.clickjacking.XFrameOptionsMiddleware module in the MIDDLEWARE setting in your project’s settings.py (This module should be listed after the django.middleware.security.SecurityMiddleware module as ordering is important). This module is used to set the following parameters:

  • X_FRAME_OPTIONS: Set this key to to ‘DENY’ or ‘SAMEORIGIN’. This setting adds the X-Frame-Options header to all HTTP responses. This protects against clickjacking attacks.

Cookies

  • SESSION_COOKIE_SECURE: Set this key to True in the settings.py file. This will send the session cookie over secure (HTTPS) connections only.
  • CSRF_COOKIE_SECURE: Set this key to True in the settings.py file. This will ensure that the CSRF cookie is sent over secure connections only.
  • Whenever you set a custom cookie in a view using the HttpResponse.set_cookie() method, make sure to set its secure parameter to True.
response = HttpResponse("Some response")
response.set_cookie('my_cookie', 'cookie_value', secure=True)

Cross Site Request Forgery (CSRF)

  • Include the django.middleware.csrf.CsrfViewMiddleware module in the MIDDLEWARE setting in your project’s settings.py to add CSRF related headers to your responses.
  • In forms use the {% csrf_token %} template tag to include the CSRF token. A sample is shown below.
<form method="post">
    {% csrf_token %}
    <!-- Your form fields here -->
</form>
  • For AJAX calls, the CSRF token for the request has to be extracted prior to being used in the the AJAX call.
  • Additional recommendations and controls can be found at Django’s Cross Site Request Forgery protection documentation.

Cross Site Scripting (XSS)

The recommendations in this section are in addition to XSS recommendations already mentioned previously.

  • Use the built-in template system to render templates in Django. Refer to Django’s Automatic HTML escaping documentation to learn more.
  • Avoid using safemark_safe, or json_script filters for disabling Django’s automatic template escaping. The equivalent function in Python is the make_safe() function. Refer to the json_script template filter documentation to learn more.
  • Refer to Django’s Cross Site Scripting (XSS) protection documentation to learn more.

HTTPS

  • Include the django.middleware.security.SecurityMiddleware module in the MIDDLEWARE setting in your project’s settings.py if not already added.
  • Set the SECURE_SSL_REDIRECT = True in the settings.py file to ensure that all communication is over HTTPS. This will redirect any HTTP requests automatically to HTTPS. This is also a 301 (permanent) redirect, so your browser will remember the redirect for subsequent requests.
  • If your Django application is behind a proxy or load balancer, set the SECURE_PROXY_SSL_HEADER setting to TRUE so that Django can detect the original request’s protocol. For futher details refer to SECURE_PROXY_SSL_HEADER documentation.

Admin panel URL

It is advisable to modify the default URL leading to the admin panel (example.com/admin/), in order to slightly increase the difficulty for automated attacks. Here’s how to do it:

In the default app folder within your project, locate the urls.py file managing the top-level URLs. Within the file, modify the urlpatterns variable, a list, so that the URL leading to admin.site.urls is different from “admin/”. This approach adds an extra layer of security by obscuring the common endpoint used for administrative access.

Patient safety assistant

Check your symptom safely

Hi, I am RX Symptom Navigator. I can help you understand what to read next and what warning signs need care.
Warning: Do not use this in emergencies, pregnancy, severe illness, or as a substitute for a doctor. For children or teens, use with a parent/guardian and clinician.
A rural-friendly guide: warning signs, when to see a doctor, related articles, tests to discuss, and OTC safety education.
1 Symptom 2 Severity 3 Safe guidance
First safety question

Is there chest pain, breathing trouble, fainting, confusion, severe bleeding, stroke-like weakness, severe injury, or pregnancy danger sign?

Choose quickly

Browse by body area
Start here: Write or select a symptom. The guide will show warning signs, doctor guidance, diagnostic tests to discuss, OTC safety education, and related RX articles.

Important: This tool is educational only. It cannot diagnose, treat, or replace a doctor. OTC information is not a prescription. In an emergency, contact local emergency services or go to the nearest hospital.

Doctor visit helper

Prepare before seeing a doctor

A simple rural-patient checklist to help you explain symptoms clearly, ask better questions, and avoid unsafe self-treatment.

Safety note: This is not a prescription or diagnosis. For severe symptoms, pregnancy danger signs, children with serious illness, chest pain, breathing difficulty, stroke-like weakness, or major injury, seek urgent care.

Which doctor may help?

Start with a registered doctor or the nearest qualified health center.

What to tell the doctor

  • Write when the problem started and how it changed.
  • Bring old prescriptions, investigation reports, and current medicines.
  • Write allergies, pregnancy status, diabetes, kidney/liver disease, and major past illnesses.
  • Bring one family member if the patient is weak, elderly, confused, or a child.

Questions to ask

  • What is the most likely cause of my symptoms?
  • Which danger signs mean I should go to hospital quickly?
  • Which tests are necessary now, and which can wait?
  • How should I take medicines safely and what side effects should I watch for?
  • When should I come for follow-up?

Tests to discuss

  • Vital signs: temperature, pulse, blood pressure, oxygen saturation
  • Basic physical examination by a clinician
  • CBC, urine test, blood sugar, or imaging only when clinically needed

Avoid these mistakes

  • Do not use antibiotics, steroid tablets/injections, or strong painkillers without proper medical advice.
  • Do not hide pregnancy, kidney disease, ulcer, allergy, or blood thinner use.
  • Do not delay emergency care when danger signs are present.

Medicine safety and first-aid guide

This section is for patient education only. It does not replace a doctor, pharmacist, or emergency care.

Safe first steps

  • Rest, drink safe water, and observe symptoms carefully.
  • Keep a written note of symptoms, duration, temperature, medicines already taken, and allergy history.
  • Seek medical care quickly if symptoms are severe, worsening, or unusual for the patient.

OTC medicine safety

  • For mild pain or fever, ask a registered pharmacist or doctor before using common over-the-counter pain/fever medicines.
  • Do not combine multiple pain medicines without advice, especially if you have kidney disease, liver disease, stomach ulcer, asthma, pregnancy, or take blood thinners.
  • Do not give adult medicines to children unless a qualified clinician advises it.

Avoid these mistakes

  • Do not start antibiotics without a proper medical decision.
  • Do not use steroid tablets or injections casually for quick relief.
  • Do not delay emergency care because of home remedies.

Get urgent help if

  • Severe symptoms, confusion, fainting, breathing difficulty, chest pain, severe dehydration, or sudden weakness need urgent medical care.
Medicine names, dose, and timing must be decided by a qualified clinician or pharmacist after checking age, pregnancy, allergy, other diseases, and current medicines.

For rural patients and family caregivers

Patient health record and symptom diary

Write your symptoms, medicines already taken, test results, and questions before visiting a doctor. This note stays on your device unless you print or copy it.

Doctor to discuss: Doctor / qualified healthcare provider
Tests to discuss with doctor
  • Basic vital signs: temperature, pulse, blood pressure, oxygen level if needed
  • Relevant blood, urine, imaging, or specialist tests only after clinical assessment
Questions to ask
  • What is the most likely cause of my symptoms?
  • Which warning signs mean I should go to emergency care?
  • Which tests are really needed now?
  • Which medicines are safe for my age, pregnancy status, allergy, kidney/liver/stomach condition, and current medicines?

Emergency warning signs such as chest pain, severe breathing difficulty, sudden weakness, confusion, severe dehydration, major injury, or loss of bladder/bowel control need urgent medical care. Do not wait for online information.

Safe pathway to proper treatment

Patient care roadmap

Use this simple roadmap to understand the next safe steps. It is educational and does not replace examination by a doctor.

Go to emergency care if you notice:
  • Severe or rapidly worsening symptoms
  • Breathing difficulty, chest pain, fainting, confusion, severe weakness, major injury, or severe dehydration
Doctor / service to discuss: Qualified healthcare provider; specialist depends on symptoms and examination.
  1. Step 1

    Check danger signs first

    If danger signs are present, seek emergency care and do not wait for online information.

  2. Step 2

    Record the symptom story

    Write when symptoms started, severity, medicines already taken, allergies, pregnancy status, and test results.

  3. Step 3

    Visit a qualified clinician

    A doctor, nurse, or qualified healthcare provider can examine you and decide which tests or treatment are needed.

  4. Step 4

    Do only useful tests

    Do tests after clinical assessment. Avoid unnecessary tests, random antibiotics, or repeated medicines without diagnosis.

  5. Step 5

    Follow up and return early if worse

    If symptoms worsen, new warning signs appear, or treatment is not helping, return for review quickly.

Rural patient practical tips
  • Take a written symptom diary and all previous prescriptions/test reports.
  • Do not hide medicines already taken, even herbal or over-the-counter medicines.
  • Ask which warning signs mean urgent referral to hospital.

This roadmap is for education. A real diagnosis and treatment plan requires history, examination, and clinical judgment.

RX Patient Help

Ask a health question safely

Write your symptom story. A health professional or site editor can review it before any answer is prepared. This box is not for emergency care.

Emergency first: Severe chest pain, breathing trouble, unconsciousness, stroke signs, severe injury, heavy bleeding, or rapidly worsening symptoms need urgent local medical care now.

Frequently Asked Questions

Is this article a replacement for a doctor?

No. It is educational content only. Patients should consult a qualified clinician for diagnosis and treatment.

When should I seek urgent care?

Seek urgent care for severe symptoms, rapidly worsening condition, breathing difficulty, severe pain, neurological changes, or any emergency warning sign.

References

Add references, clinical guidelines, textbooks, journal articles, or trusted medical sources here. You can edit this area from the RX Article Professional Blocks panel.