Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CSRF Token #50

Open
MyPersonalGitAccount opened this issue Aug 14, 2024 · 0 comments
Open

CSRF Token #50

MyPersonalGitAccount opened this issue Aug 14, 2024 · 0 comments

Comments

@MyPersonalGitAccount
Copy link

Hey everyone

Just in case anyone is having trouble with form submission and csrf tokens without using ajax, this is the solution I used to solve it:

Step 1: Create a middleware class which shares data to views on all requests

class CsrfTokenMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        share(request, csrf=get_token(request))

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

Step 2: Add it to the middleware settings

MIDDLEWARE = [
    ....
    "website.middleware.CsrfTokenMiddleware",
]

Step 3: accept it as a prop in your *.vue files

<script setup>
    const props = defineProps({
        csrf: String,
        error: String
    });
</script>

Step 4: Add a hidden field to your form

<input type="hidden" name="csrfmiddlewaretoken" :value="props.csrf" />

This was the only solution that worked for me. I tried both solution provided in the README without success.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant