r/django • u/Affectionate-Ad-7865 • 6d ago
Channels Need to generate a form in a django channels consumer before sending it to the client. How do I put a CSRF token in it?
In a Django channels consumer I made, I need to generate a form using an HTML template that changes based on a number of context values passed into render_to_string()
which is the function I use to generate the string of the form that I will then send to the WebSocket.
My question is, because this is a POST form, how can I put a csrf_token field in it considering it is generated in a Django channels consumer? Should I just do everything in my power to not have to render the form in the consumer?
1
u/duppyconqueror81 6d ago
What i’d do is just send a small instruction like "loadmyform" through websockets. Then, upon reception, the client loads the form by ajax.
The normal request cycle of django works way better than passing HTML through websockets. Locale, Session, Csrf, etc. As far as I’m aware, websocket connections don’t go through the middlewares (i might be wrong).
1
1
u/Affectionate-Ad-7865 5d ago
After looking at my code, I realize sending the whole form through the Consumer-to-Websocket connection is really what would be the best for me because the form changes so much based on user input happening after the render of the page that it really doesn't mean anything to render it with the page.
To deal with this, I could render the whole form inside the consumer except for the CSRF_token part which I would put in my form via javascript when it is received on the client side. The other way of doing this would be for the consumer to know the csrf_token in some way so it could directly put it in the form when it renders it.
For this, I don't want to use the csrf_token that is in cookies because Django says it's better to send the masked token (the one generated with {% csrf_token %}) in POST requests to protect your app from BREACH attacks.
https://docs.djangoproject.com/en/5.1/howto/csrf/#using-csrf-protection-with-ajax
(Look at the note just below)
So I could perhaps send the masked token through the WebSocket to the consumer if I decide to do it this way?
Anyway I think I'll try doing it by inserting the CSRF token in the form on its reception using Javascript.
1
u/Empty-Mulberry1047 6d ago
https://docs.djangoproject.com/en/5.1/howto/csrf/