Consent
Technical reference for the Consent module in Care EMR. For what a consent is and who can work with it, read the Consent concept.
A Consent records a decision, permit or deny, with one category, such as treatment, research or privacy. Each consent belongs to one encounter and reaches its patient through that encounter.
Source:
- Model:
care/emr/models/consent.py - Resource spec:
care/emr/resources/consent/spec.py - Viewset:
care/emr/api/viewsets/consent.py - Authorization:
care/emr/api/viewsets/encounter_authz_base.py·care/security/authorization/encounter.py·care/security/authorization/patient.py·care/security/authorization/file_upload.py EMRResourceandPeriodSpec:care/emr/resources/base.py
The Django model is the storage layer: status, category and decision are plain CharFields, and period and verification_details are JSONFields.
The resource specs define the allowed values, the shape of period, and the read and write schemas. The viewset adds the patient match and the one-verification-per-user rule. The closed-encounter block is in the authorization handler can_update_encounter_clinical_data, which the viewset calls.
Models
| Model | Purpose |
|---|---|
Consent | A permit-or-deny decision with one category, attached to one encounter |
Consent extends EMRBaseModel. The base provides external_id, created_date, modified_date, the soft-delete flag deleted, created_by, updated_by, history and meta.
Consent fields
Storage type is the Django column. Spec type is the type the API enforces. On create is the rule in ConsentCreateSpec.
| Field | Storage type | Spec type | On create | Notes |
|---|---|---|---|---|
status | CharField(50) | ConsentStatusChoices | Required | See values |
category | CharField(50) | CategoryChoice | Required | See values. The app offers six of the seven values |
date | DateTimeField | datetime | Required | The date and time the consent was given. The app labels it Consent Given On |
period | JSONField, default dict | PeriodSpec (start, end) | Send it on create. Without it, the create fails with HTTP 500 and stores nothing; {} is accepted | Both start and end are optional, and each must be timezone-aware when set. start cannot be after end. On create only, start cannot be before date. The app labels the ends Consent Valid From and Consent Valid Until. See PeriodSpec |
encounter | ForeignKey to emr.Encounter (CASCADE, related_name="consents") | UUID4 (encounter external_id) | Required | Must belong to the patient in the URL. Cannot change after create. In __exclude__, so the generic field copy skips it |
decision | CharField(10) | DecisionType | Required | See values |
verification_details | JSONField, default list | list[dict] (read schemas only) | Not in the schema | Not in the create or update schema. Only add_verification and remove_verification change it. See Verification actions |
note | TextField, nullable, blank | str | None | Optional | On update, null keeps the stored note |
On update, every field is optional, and a field sent as null or left out keeps its stored value. So PUT behaves like PATCH.
source_attachments is not a model field. The read schemas build it from FileUpload records when they serialize a consent.
Enum values
ConsentStatusChoices values
| Value | Label in the app |
|---|---|
draft | Draft |
active | Active |
inactive | Inactive |
not_done | Not Done |
entered_in_error | Entered in Error |
No consent code reacts to the status value. See Methods & save behaviour.
CategoryChoice values
| Value | Label in the app | Description in the app |
|---|---|---|
research | Research | "Consent to participate in research protocol and information sharing" |
patient_privacy | Privacy Consent | "Consent to collect, access, use or disclose (share) information" |
treatment | Treatment | "Consent to undergo a specific treatment" |
dnr | Do Not Resuscitate | "Consent to not receive CPR or resuscitation initiated in case of a cardiac event" |
comfort_care | No label | The server accepts it. The app does not offer it and has no label for it |
acd | Advance Directive | "Consent given in anticipation of a potential need for medical treatment" |
adr | Advance Care Directive | "Consent for actions to be taken if they are no longer able to make decisions for themselves" |
CategoryChoice also has a commented-out consent_document member (LOINC 59284-0), so the API does not accept that value. Its code comment says it is used only in migrations, but no migration contains it.
DecisionType values
| Value | Label in the app | Text on the consent card |
|---|---|---|
permit | Permit | Permitted |
deny | Deny | Denied |
The app labels the form field Consent Decision.
VerificationType values
These values are used in verification_type of the add_verification body. The app has no label for them.
| Value | Meaning |
|---|---|
family | The consent was given by a family member |
validation | The consent was validated by the patient themself |
Nested JSON shapes
PeriodSpec nested shape
The period field uses PeriodSpec from care/emr/resources/base.py.
| Field | Type | Notes |
|---|---|---|
start | datetime | None | Default None. Must be timezone-aware if set |
end | datetime | None | Default None. Must be timezone-aware if set |
PeriodSpec enforces these rules wherever a request sets period:
- A
startwithout a timezone fails with "Start Date must be timezone aware". - An
endwithout a timezone fails with "End Date must be timezone aware". - A
startlater thanendfails with "Start Date cannot be greater than End Date".
ConsentCreateSpec adds one rule on create only. A start earlier than date fails with "Start of the period cannot be before than the Consent date". A start equal to date passes.
ConsentVerificationSpec nested shape
ConsentVerificationSpec is the request body of add_verification. Each successful call appends one entry to verification_details, which the read schemas type as list[dict]. A second call by the same user fails.
| Field | Type | Required | Notes |
|---|---|---|---|
verified | bool | Required | The entry is stored even when the value is false |
verified_by | UUID4 | None | Optional | The server overwrites it with the requesting user. On read, it becomes that user's UserSpec |
verification_date | datetime | None | Optional | The server overwrites it with the current time |
verification_type | VerificationType | Required | family or validation |
note | str | None | Optional | Free text |
Related models
encounter is a foreign key to emr.Encounter with on_delete=CASCADE and related_name="consents". An encounter reaches its consents through consents.
A consent has no patient field. The patient is reached through encounter, and the list is filtered by the encounter's patient.
The read schemas also read FileUpload records (files) and User records (verifiers) when they serialize a consent.
Resource specs (API schema)
The four consent schemas extend EMRResource through ConsentBaseSpec. ConsentVerificationSpec is a plain Pydantic BaseModel, not an EMRResource.
serialize copies each non-foreign-key model field that is also a spec field and not in __exclude__. Then it runs perform_extra_serialization.
de_serialize dumps the spec with exclude_defaults=True. It assigns each dumped model field except id, external_id and the __exclude__ fields.
| Spec class | Role | Exposes / behaviour |
|---|---|---|
ConsentBaseSpec | shared base | id (UUID4 | None), status, category, date, period (PeriodSpec), encounter (UUID4), decision, note (str | None). __model__ = Consent, __exclude__ = ["encounter"] |
ConsentCreateSpec | write · create | Base fields. Required: status, category, date, encounter, decision. Optional: id, note. period: send it on create; without it the create fails with HTTP 500, while {} is accepted. Rejects a period.start before date. Sets the model's encounter from its external_id |
ConsentUpdateSpec | write · update | Extends ConsentBaseSpec, not ConsentCreateSpec. status, category, date, period, encounter, decision and note are all optional. No period-versus-date check |
ConsentListSpec | read · list | Base fields plus source_attachments: list[dict] and verification_details: list[dict] |
ConsentRetrieveSpec | read · detail | Identical to ConsentListSpec |
ConsentVerificationSpec | write · add_verification body | Plain BaseModel. See the shape |
Validation
- Create only: a
period.startearlier thandatefails with "Start of the period cannot be before than the Consent date". - Any
periodin a request:PeriodSpecrequires a timezone onstartandend, and refuses astartafterend. - Enums:
status,categoryanddecisionaccept only their enum values. On update, they can be left out. - Create and update (viewset): the encounter must belong to the patient in the URL. See Authorization checks.
- Update: there is no period-versus-date check. A field sent as
nullor left out keeps its stored value.
Server-maintained behaviour
- Encounter on create:
ConsentCreateSpec.perform_extra_deserializationsets the model's encounter from theexternal_idin the body. - Encounter on update: the encounter cannot change. The viewset removes
encounterfrom the update body, and__exclude__keeps the generic field copy away from it. - Update hook:
ConsentUpdateSpec.perform_extra_deserializationassigns the stored encounter to the spec attributeself.encounter, not to the model. - Verifications:
add_verificationsetsverified_byandverification_dateon the server. See Verification actions. - Files (read):
source_attachmentslists everyFileUploadwhoseassociating_idis the consent'sexternal_id, withfile_categoryconsent_attachmentandfile_typeconsent. - File states (read):
source_attachmentsincludes archived files and files whose upload was never marked complete. - Verifier details (read): each
verified_byinverification_detailsbecomes the verifying user'sUserSpec. - Identifiers (read):
idis the consent'sexternal_id, andencounteris the encounter'sexternal_id. - No audit fields (read): the read schemas have no
created_date,modified_date,created_byorupdated_by.
Methods & save behaviour
Consentoverrides neithersave()nordelete(), and no signal handler is attached to it.- Delete is a soft delete. The viewset sets
deleted = True, keeps the row, and returns 204. - The default manager hides deleted rows, so a deleted consent no longer appears in any list or lookup.
statusis a plain field. No consent code reacts to its value, so a consent with statusentered_in_errorstays in lists and can still be updated.
API integration notes
- The base path is
/api/v1/patient/{patient_external_id}/consent/. Every request needs a signed-in user. encounterin a body, and theencounterlist filter, take the encounter'sexternal_id, not its numeric id.- Validation errors return HTTP 400 with an
errorslist. Each item hastypeset tovalidation_errorand amsg. - The update endpoint accepts changes to
category,decision,dateandperiod. The app's edit form resends the stored values, so it changes onlystatusandnote. - The app always sends
period, withstartandendeach set to a date-time ornull. - The app calls only list, retrieve, create and update. No screen calls delete, upsert,
add_verificationorremove_verification. - The app defines a remove-verification call that sends
verification_id, but the server readsverified_by. No screen uses that call.
Authorization checks
The roles listed hold each permission by default. The permission definitions also name an Admin role. Roles are matched by name, and the only role named Admin in the database is for role organizations, which the facility screens do not offer. The table below leaves it out.
| Check | Passes when | Default roles |
|---|---|---|
| Read check, patient branch | The user holds "Can view clinical data about patients" on the patient. The role can come from a facility organization of an encounter of the patient that is not closed, or of that encounter's current location. It can also come from one of the patient's organizations, or a direct link to the patient | Staff, Doctor, Nurse, Facility Admin |
| Read check, encounter branch | Only when the patient branch fails and the request has ?encounter= with an encounter external_id. The user holds "Can Read encounter related clinical data" in that encounter's organizations or its current location's organizations. The encounter status does not matter. Else the request fails with "Permission denied to user" | Doctor, Nurse, Facility Admin |
| Write check | The encounter is not closed, and the user holds "Update Encounter related clinical data" in the encounter's organizations or its current location's organizations. Else the request fails with "You do not have permission to update encounter" | Doctor, Nurse, Facility Admin |
| Patient match | On create and update, the encounter exists and belongs to the patient in the URL. Else the request fails with "Patient external ID mismatch with encounter's patient". An unknown encounter on create gives 404 | Not a permission |
An encounter's organizations are its assigned organizations, their parent organizations, and the facility's root organization, "Administration". A role in "Administration" applies to every encounter of the facility.
A location's organizations include those of its parent location, its own organizations with their parents, and "Administration".
A closed encounter has the status Completed, Cancelled, Discontinued or Entered in error. The write check refuses every change to the consents of a closed encounter.
The closed-encounter rule does not refuse writes on encounters with the status Planned, In Progress, On Hold, Discharged or Unknown.
A closed encounter's facility organizations no longer count for the patient branch of the read check. The encounter branch does not depend on the encounter status.
Endpoints
Paths are relative to /api/v1/patient/{patient_external_id}. In each path, {id} is the consent's external_id.
| Action | Method and path | Permission path | Notes |
|---|---|---|---|
list | GET /consent/ | Read check | One filter, encounter. No search and no ordering parameter. Newest first. Limit and offset, 14 per page by default, 200 at most. Without encounter, it returns the consents of every encounter of the patient |
retrieve | GET /consent/{id}/ | Read check, through get_object. No retrieve-specific check | Same shape as a list item |
create | POST /consent/ | Patient match on the body's encounter, then write check on that encounter. No read check | Body: ConsentCreateSpec |
update / partial_update | PUT or PATCH /consent/{id}/ | Read check, through get_object. Then patient match, then write check on the consent's encounter | Body: ConsentUpdateSpec. PUT and PATCH take the same path. The viewset removes id, external_id, patient and encounter from the body |
destroy | DELETE /consent/{id}/ | Read check, through get_object. Then write check on the consent's encounter | Soft delete. Returns 204 |
upsert | POST /consent/upsert/ | Per item. An item without id takes the create path. An item with id is loaded without the read check, then patient match and write check run | Body: a datapoints list. An empty list fails with "No datapoints provided". More than MAX_DATAPOINTS_PER_UPSERT (100 by default) fails with "Too many datapoints provided" |
add_verification | POST /consent/{id}/add_verification/ | Read check, through get_object. Then write check on the consent's encounter | Body: ConsentVerificationSpec. See Verification actions |
remove_verification | POST /consent/{id}/remove_verification/ | Read check, through get_object. Then write check on the consent's encounter | Body: optional verified_by (a user UUID). See Verification actions |
Verification actions
add_verificationappends one entry toverification_details. The server setsverified_byto the requesting user andverification_dateto the current time, and ignores values sent for them.- Each user can verify a consent once. A second attempt by the same user fails with "Consent is already verified by the user". Other users can each add their own entry.
- The entry is stored whatever the value of
verified, so an entry withverifiedset tofalseis stored too. The request also setsupdated_byto the requesting user. remove_verificationwithoutverified_byremoves the requesting user's entry. Withverified_by, it removes that user's entry, so any user who passes the write check can remove another user's verification.- If no entry matches,
remove_verificationfails with "Consent is not verified by the user".
Files
- A consent's files go through the files API,
/api/v1/files/, withfile_typeconsent,file_categoryconsent_attachmentandassociating_idset to the consent'sid. - Reading a consent file needs the patient-level or the encounter-level read permission, with no
encounterparameter. Writing needs the write check, including the closed-encounter rule. - A refused file read or write fails with "Cannot View File".
- The files API has no delete. A file can be archived with an
archive_reason. - The files API list returns only files whose upload is complete. The consent's own
source_attachmentsalso lists incomplete and archived files. - A periodic task hard-deletes file records whose upload was never marked complete, after
FILE_UPLOAD_EXPIRY_HOURS(24 by default; 0 turns it off). - The one-shot base64 endpoint
POST /api/v1/files/upload-file/limits a file toMAX_FILE_UPLOAD_SIZEmegabytes (5 by default). The signed-URL flow that the app uses does not apply this limit. - A completed, non-archived consent file can be attached to a referral of the same patient.
- The app accepts jpg, jpeg, png and pdf files for a consent.
- For the files API itself, see the File upload reference.
Related
- Concept: Consent
- Flow: Record a consent
- Flow: View consents
- Flow: Add files to a consent
- Flow: Update a consent
- Reference: Encounter
- Reference: Patient
- Reference: File upload
- Reference: User
- Reference: Permission
- Reference: Role
- Reference: Base model
- Source (model): consent.py on GitHub
- Source (specs): resources/consent/spec.py on GitHub
- Source (viewset): viewsets/consent.py on GitHub