Skip to content

Handy

How to check for permissions in svelte

To check if the current user has the proper permissions you can use the following code:

hasPermission('bbrs.change_boat_location')
In a svelte component you can use this code to show or hide a button:
{#if hasPermission('bbrs.change_boat_location')}
    <button>Change location</button>
{/if}

Add a permission to a Django model

To add a permission to a model you can use the following code:

class Boat(models.Model):
    class Meta:
        permissions = [
            ('change_boat_location', 'Can change the location of the boat'),
        ]

How to check for permissions in Django

There are 2 ways to check for permissions in Django. The first way is to use the has_perm method on the user object.

if request.user.has_perm('bbrs.change_boat_location'):
    # do something
The second way is to use the @permission_required decorator this is normally used in views. But does not work for the api functions

Write a API function and use it in Svelte

Tip

For the API funtionalities we use the Django Ninja this explanation is a quick summary of the documentation. For more information please check the Django Ninja documentation

For adding a new API function you need tree things:

  1. A function that does the work including the @api or @route decorator
  2. A schema that defines the input
  3. A schema that defines the output

The function

The function runs when the correct api endpoint is called. It that get the input data and returns the output data (and if needed does some logic). A simple get function looks like this:

@router.get("/boats/{boat_id}", response=BoatOutSchema, operation_id="bbrs_get_boat", tags=["boats"])
def get_boat(request, boat_id: int):
    boat = Boat.objects.get(id=boat_id)
    return boat
  • The @router.get is the decorator that tells the router that this is a get function.

  • The "/boats/{boat_id}" is the endpoint of the function. The {boat_id} is a variable that is passed to the function.

  • The response=BoatOutSchema is the schema that is used to validate the output data.

  • The operation_id="bbrs_get_boat" is the name of the function. This is used in svelte to call the function. The opration_id should be structured like this {package_name}{operation}{model}.

  • The tags=["boats"] is used to group the functions in the documentation.

This example returns the boat with the id that is passed to the function. The output is validated by the BoatOutSchema and converted to JSON.

The docs for the api are generated by the Django Ninja and can be found at the endpoint /api/docs.

The input schema

The input schema is required to validate the input data.

The output schema

The output schema is required to validate the output data.

Use the API function in Svelte

First we need to generate the client for the api. This can be done by running the following command (The backend needs to be running):

pnpm run generate