Manually access content from Form fields in Django
I'm in a position where I would like to submit content to a form that is not defined in a Forms class.
For example, in my forms.py:
class AnalyseForm(forms.Form):
TYPES = (('a', 'Type A'),('b', 'Type B'), ('c', 'Type C'))
filename = forms.FileField(label="Document to Aalyse")
doctype = forms.ChoiceField(choices=TYPES, label="Doc Type:")
and in my views.py:
I am trying to send an additional variable that doesn't exist in the Form class, because I defined it in the HTML file manually. The answer to this isn't 'define it in the Form class. I have for example other HTML widgets that are to going to play with being shoehorned into a Django Form definition.
def AnalyseDoc(request):
doctype=""
if request.method == "POST":
form = AnalyseForm(request.POST, request.FILES)
if form.is_valid():
filecontent = request.FILES['filename']
doctype=form.cleaned_data['doctype']
# dummydata=form.cleaned_data['dummydata']
print(dummydata)
analyse = analyseStuff(file=filecontent,doctype=doctype, dummydata=dummydata)
else:
form = AnalyseForm()
return render(
request,
"summary.html",
{
"dummydata": "x",
"form": form,
'filecontent': filecontent,
"doctype": doctype,
},
)
This is a bit of a quandry
<h1>What file would you like to Analyse?</h1>
<form action = "" method = "post" enctype="multipart/form-data">
<div class="form-check form-switch">
<label class="form-check-label" for="dummydata">Use Dummy Data</label>
<input class="form-check-input" type="checkbox" role="switch" id="dummydata" checked>
</div>
{% csrf_token %}
{{form | crispy}}
<button id="submit" type="submit" class="btn btn-primary">Analyse<button>
</form>
This is a quandry. How then do I access the value of 'dummydata' in this instance
Obviously, I can't get the content from cleaned_data. It's not a formal Form field. I can't see it by using
request.POST.get('dummydata')
Any thoughts on how I can access dummydata within my views function?
All you need to do in your situation is specify the name attribute for your checkbox. Here's also a link that might be helpful. Something like this:
<form action = "" method = "post" enctype="multipart/form-data">
<div class="form-check form-switch">
<label class="form-check-label" for="dummydata">Use Dummy Data</label>
<input class="form-check-input" type="checkbox" role="switch" id="dummydata" checked name="dummy">
</div>
{% csrf_token %}
{{form | crispy}}
<button id="submit" type="submit" class="btn btn-primary">Analyse</button>
</form>
And then request.POST
:
<QueryDict: {'dummy': ['on'], 'csrfmiddlewaretoken': ['11wTd1DBszhGWk4JGFUgM4sH2lOSxLD44lu1g5XqtvY9K9z0ptdceeRMdx2ZFgjK'], 'doctype': ['a']}>