Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to read question mark (?) in the django URL

Tags:

python

django

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('')

like image 748
Talha Quddoos Avatar asked Oct 25 '25 10:10

Talha Quddoos


1 Answers

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.

like image 141
Willem Van Onsem Avatar answered Oct 28 '25 01:10

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!