'Form not submitting CSRF token missing although it is in rendered html
I'm getting a "CSRF token missing" error, when submitting a form in Django. I'm using django-crispy-forms in combination with htmx.
The form is rendered via render_crispy_form:
def SwapFormView(request, partialform):
ctx = {}
ctx.update(csrf(request))
mitglied = model_to_dict(request.user.mitglied)
if request.method == 'POST':
# do form things
return HttpResponse("""POST""")
else:
form = ChangeDataForm(
initial=mitglied,
partialform=partialform,
)
html = render_crispy_form(form, helper=form.helper, context=ctx)
return HttpResponse(html)
My helper is contructed like this:
def __init__(self, *args, **kwargs):
super(ChangeDataForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_id = 'change-form'
self.helper.attrs = {
'hx-post': reverse('back-to-same-url'),
'hx-target': '#change-form',
'hx-swap': 'outerHTML',
}
self.helper.add_input(Submit('submit', 'absenden'))
The thing is, that as soon as I change the helper to a 'normal' POST-Request it works - but I need this to be done via HTMX to only change out the specific parts in the DOM. Weirdest thing for me is, that the token is rendered into the final html of the form:
<form hx-post="/profil/nameform/" hx-swap="outerHTML" hx-target="#change-form" id="change-form" method="post" enctype="multipart/form-data" class="">
<input type="hidden" name="csrfmiddlewaretoken" value="token-value">
<label for="id_title" class="">Titel</label>
<input type="text" name="title" value="Hau" maxlength="50" class="textinput textInput form-control" id="id_title">
<label for="id_first_name" class=" requiredField">Vorname<span class="asteriskField">*</span> </label>
<input type="text" name="first_name" value="Test" maxlength="50" class="textinput textInput form-control" required="" id="id_first_name">
<label for="id_last_name" class=" requiredField">Nachname<span class="asteriskField">*</span></label>
<input type="text" name="last_name" value="aBVIpzRJoBKP" maxlength="50" class="textinput textInput form-control" required="" id="id_last_name">
<input type="submit" name="submit" value="absenden" class="btn btn-primary" id="submit-id-submit"> </div> </div> </form>
Any help is appreciated...
EDIT: The problem solved itself after I removed some kwargs I passed from the view to the form. Still don't know, what the real problem was, but I found a workaround.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
