Reputation: 1495
In Django I want to open a URL (this is posted by a user in a form) and after clicking the submit button (of the form) with the URL, get the data (the URL) and do some things with it (printing it in the view).
I only have one function in the views.py
file, so I guess my main problem is that I should have two. But I am not really sure how to solve it, however have I tried.
My form is this one:
<html>
<head>
<title>
Practica Django
</title>
</head>
<form method="POST" action="" id = "loginForm">
{% csrf_token %}
<input type="text" name="text" id= "text" value= '{% if submitbutton == "Submit" %} {{ firstname }} {% endif %}' maxlength="100"/>
<input type="reset" name="Reset" id = "Reset" value="Reset" />
<input type="Submit" name="Submit" id = "Submit" value="Submit" />
{% if submitbutton == "Submit" %}
<h1 id = 4 name="resultado2"> {{ type }}</h1>
{% endif %}
</form>
</html>
In my views I have this:
def vistaFormulario(request,):
text = request.POST.get('text')
submitbutton = request.POST.get('Submit')
m = str(text)
print(m)
print(text)
# Descarga el contenido del HTML
with urllib.request.urlopen('http://www.elmundo.es/espana/2018/06/05/5b162c3b468aebd9678b4695.html') as response:
page = response.read()
soup = BeautifulSoup(page, 'html.parser')
p = soup.find_all('p')
And so it continues. But I need to open that URL! But whichever the user has written in the form and push the input button!
As you can see, I have two prints
, just to see what values do those values have. They have None before typing something and pressing the input button, and after pressing it, they have whatever you have written.
What I want is to get in this method whatever I input in the button from the beginning. I do not understand why they have none. I want to get the value, and then print them.
Upvotes: 0
Views: 728
Reputation: 764
So, your issue is that you do a call to Beautiful Soup, but you don't need to do it when the user initially loads the page and hasn't submitted the form.
The easiest solution is to put the logic that calls bs
into an if
block that only fires if you POST
:
# Define these so that they have a value to be called in the template
text = submitbutton = ''
if request.method == 'POST':
text = request.POST.get('text')
submitbutton = request.POST.get('Submit')
m = str(text)
print(m)
print(text)
# Descarga el contenido del HTML
with urllib.request.urlopen('http://www.elmundo.es/espana/2018/06/05/5b162c3b468aebd9678b4695.html') as response:
page = response.read()
soup = BeautifulSoup(page, 'html.parser')
p = soup.find_all('p')
# This needs to be outside your 'if' clause, so that the page will render if the method isn't POST
context = {'text': text,
'submitbutton': submitbutton,
'type':q1}
return render(request, 'form/form.html', context)
From your sample, I'm not sure how qt
gets defined or exactly why you're capturing the submitbutton
, but this should work more or less.
Upvotes: 1