Home > OS >  How to pull information from html and use it in a view in Django
How to pull information from html and use it in a view in Django

Time:12-17

Im trying to send a post request with a payload that includes a username and password. The post request works fine on its own but I'm not sure how to get the user and pass that are entered and use them with the post request. Trying to take the data entered into the html and use it in a view

I've looked around online and found something suggesting something similar to which doesn't fail but instead returns none:

username = response.GET.get['username'] password = response.GET.get['password']

I see this stack overflow:Django request.POST.get() returns None that definitely has the correct answer in it but I don't quite understand whats going on/what I need to do in order to get the result im trying for. I can see its something to do with that I have to post the data to the url or something for it to be eligible to grab from the above statements or something, but again, I don't really understand whats happening.

Honestly what im looking for here is an ELI5 of the answer from the link

CodePudding user response:

This is what your template(html) should look like:

<form method="POST">
{% csrf_token %}
     <input type="text"  name="username">
     <input type="password"  name="password">
 </form>
 <input type="submit" value="Submit">

This is what your views.py should look like to use the 'POST' data sent from your form:

def myView(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # to print on the console
        print(username, password)
    return render(request, 'myView')

CodePudding user response:

In order to pass data from html to Django you need html forms. There's a great tutorial about them in the Django documentation: https://docs.djangoproject.com/en/4.1/topics/forms/

  • Related