Django:get field values using views.py from html f

2020-07-10 06:05发布

问题:

Hello everyone I have an HTML form as follows:

<body class="">
    <div class="navbar navbar-static-top navbar-inverse"></div>
    <div style="height:20%; width:30%; margin-top:12%; margin-left:40%;">
        <div class="list-group">
            <form role="form">
            <br/>
                <div class="form-group input-group">
                    <span class="input-group-addon"><i class="fa fa-circle-o-notch"  ></i></span>
                    <input type="text" name="Username" class="form-control" placeholder="Username" />
                </div>
                <div class="form-group input-group">
                    <span class="input-group-addon"><i class="fa fa-tag"  ></i></span>
                    <input type="text" name="first_name" class="form-control" placeholder="FIRST_NAME" />
                </div>
                <div class="form-group input-group">
                    <span class="input-group-addon"><i class="fa fa-tag"  ></i></span>
                <input type="text" name="last_name" class="form-control" placeholder="LAST_NAME" />
                </div>
                ...
                ...
                <a href="/submit" class="btn btn-success ">POST</a>
            </form>
        </div>
    </div>
</body>

and after clicking on post i am redirecting it to views.py. can any one tell me how to get the field values of all the fields of the form into views.py. thanks in advance

回答1:

Each input should have a name attribute:

<input type="text" name="username" class="form-control"
                                      placeholder="Desired Username" />

And then in your view you can access that data using request.POST or request.GET dictionary-like objects (it depends on the method attribute of the <form> tag):

def register(request):
    username = request.POST['username']
    ...

But you shouldn't render/handle forms this PHPish way. Learn the django forms.



回答2:

To catch the data in python backend

for POST request:

def register(request):
    username = request.POST.get('username')

for GET request

def register(request):
    username = request.GET.get('username')

.get was missing on earlier answer



标签: django forms