最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Manually access content from Form fields in Django - Stack Overflow

programmeradmin3浏览0评论

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 not 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>  

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?

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 not 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>  

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?

Share Improve this question edited yesterday Jon M asked yesterday Jon MJon M 6747 silver badges20 bronze badges 1
  • It looks like I've wasted hours on this because the solution is that the POST does indeed send fields that aren't contained in the Forms definition. What wasn;'t obvious to me, is that Checkbox inputs only send data when they're checked for for performance reasons. – Jon M Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 2

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']}>

UPDATED

Regarding the fact that the input field data, with type checkbox, is not sent if checked=false, this behaviour is described in the HTML specification, here is link to a good answer containing a link to the specification and possibly a solution to this problem with adding a hidden field with the same name attribute with a default value to sending this field always. Also, you can see how CheckboxInput is implemented in Django including handling the field value for checked=false cases.

发布评论

评论列表(0)

  1. 暂无评论