1

I'm trying to store some data from a html form in a .txt file. But when I store data from my variable used to recieve data it give "None". But when I pass string directly it successfully store.

def write(request):
p_no = request.GET.get('p_no')
# temp = "% s" % p_no
# Str_value = '{}'.format(p_no)
temp = p_no.__str__()
with open('C:\\Users\\The Goat\\Desktop\\testp\\Files\\sample.txt', 'w+') as f:
    testfile = File(f)
    testfile.write(temp)+
    testfile.close
    f.close

return render(request,'index.html')

1 Answer 1

1

Perhaps in the form you use form method="post", and in the view you request request.GET.get.

The following code works for me(bboard replace with the name of your folder where the templates are located):

views.py

def form(request):
    return render(request, 'bboard/index3.html')

def write(request):
    p_no = request.GET.get('p_no')
    temp = p_no.__str__()
    with open('test12345.txt', 'w+') as f:
        f.write(temp)
        f.close

    return HttpResponse(f"<h2>Name: {temp}")

index3.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
</head>
<body>
    <h2>User form</h2>
    <form method="get" action="{% url 'write'%}">
        {% csrf_token %}
        <p>Name:<br> <input name="p_no" /></p>
        <input type="submit" value="Send" />
    </form>
</body>
</html>

urls.py

urlpatterns = [
    path("form/", form),
    path("write/", write, name="write"),
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.