Home > Mobile >  Django: how to get HTML input field value to django view?
Django: how to get HTML input field value to django view?

Time:07-29

i want to get a value in an input to a django views, this is not a form as i am not trying to submit any form, i just need the value that is in the input field

this is the html template

<input readonly name="ref_code" type="text" value="{{ request.user.profile.recommended_by.profile.code }}">

this is my django views

code = str(request.GET.get('ref_code'))
print("This is the code:"   code)

It keep printing This is the code: None

NOTE: i have also tried using request.POST.get("ref_code") it did not still work What might be the issue?

CodePudding user response:

You definitely need something like a form.

So, let's walk you step by step on how your code works.

First, there is a view which prepares the data to be rendered with the template. This view responds to the first request from the user's browser and returns the rendered template as a static html page to the user.

Second, user's browser displays received html page to the user.

Third, user enters something into the input field.

At this stage the data user has entered is still on their side in their browser.

At this point you have two options:

  1. Use a form to let user send the data to some view on the server which will then process the received data.
  2. Use JavaScript to capture the entered data and send it to the server using an AJAX request.

I guess, you would like to use the second option in this case.

I'd recommend to read a guide on AJAX basics. The Ajax guide on MDN is a good place to start.

  • Related