I am developing a Django app that stores the user input in the database. Now the problem is that when the user writes the ? in the input field, Django treats it as the part of querystring so it doesn't save it.
I am using the following JavaScript code:
$("#submit").on("click",function(){
text = $("#input").val();
$.get('/add/'+text);
}
And here is my urls.py file:
urlpatterns = [
path('add/<str:text>',views.add, name='add'),
..............
]
And in views.py, I have:
def add(request,text):
field = Text(text=text)
field.save()
return HttpResponse('')
That is because you did not encode it properly. You need to use percentage encoding [wiki] to encode data in a URL.
In JavaScript, you can use the encodeURIComponent function for that:
$("#submit").on("click",function(){
text = $("#input").val();
$.get('/add/'+encodeURIComponent(text));
}
The question mark will thus be encoded to %3F, since this is the character that maps on codepoint 63 (or 0x3f as hexadecimal number).
Note that a str will not match a slash. You thus might want to use a path instead:
urlpatterns = [
path('add/<path:text>',views.add, name='add'),
# …
]
If you however create, delete, update, etc. records, then you should use a POST, PUT, PATCH or DELETE request, since GET requests are supposed to have no side-effects. In that case it might be better to pass the data as request payload.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With