Django accepting GET parameters - django

Error can be seen here: http://djaffry.selfip.com:8080/
I want the index page to accept parameters, whether it be
mysite.com/search/param_here
or
mysite.com/?search=param_here
I have this in my URL patterns, but I can't get it to work. Any suggestions?
urlpatterns = patterns('',
(r'^$/(?P<tag>\w+)', 'twingle.search.views.index'),
)

First of all your regular expression in url pattern is wrong.
r'^$/(?P<tag>\w+)'
It says to match everything from
^ the beginning of line
$ to the end of line
having pattern named tag which is composed of words and digits after the line end
Usually after the one line ends comes another line or EOF not content (unless you use multiline regexp and you don't need those here).
Line end should be after the tag:
r'^/(?P<tag>\w+)$'
Using a query string
Query strings are not parsed by url reslover.
Thus, if you have url in format:
http://mysite.com/?query=param_here
will match:
(r'^$', 'twingle.search.views.index')
In this case you can access query string in view like so:
request.GET.get('query', '')
Without a query string
mysite.com/search/param_here
will match:
(r'^search/(?P<query>\w+)$', 'twingle.search.views.index'),
Where everything that matches \w (you should change this to suite your needs) will be passed along with request to index view function as argument named query.
Both
You can use both url patterns like so:
urlpatterns = patterns('twingle.search.views',
url(r'^$', 'index'),
url(r'^search/(?P<query>\w+)$', 'index'),
)
In this example the view would look something like this:
def index(request, query=None)
if not query:
query = request.GET.get('query', '')
# do stuff with `query` string

Related

How to escape '/' in django urls

I am working on a project that generates dynamic urls
for eg if you type mysite.com/<yourtexthere> The site should generate a url with mysite.com/yourtexthere (where yourtext here is a slug of a model)and I am able to do that but the problem arises when I put something like this mysite.com/yourtexthere/moretext, Django doesn't match it with any of my existing URL patterns and gives me 404.
I wanted to ask is there a way by which I can treat '/' as just another character and generate unique url mymysite.com/yourtexthere/moretext where yourtexthere/moretext is now the slug.
views.py
def textview(request, slug):
obj, created= Text.objects.get_or_create(slug=slug, defaults={'text':'', 'password':'123'})
return render(request, 'text/textpage.html', {'obj' : obj, 'created' : created})
urls.py
# Only patterns
urlpatterns = [
path('', home, name='home'),
path('<slug:slug>/', textview, name='textview'),
]
From Django models docs:
A slug is a short label for something, containing only letters, numbers, underscores or hyphens.
So the 404 is actually correct, maybe use another field.
Django path converters match strings in the input URL using regex.
The default path converters are pretty basic - source code.
The slugConverter matches any string that only contains characters, numbers, and dashes, not forward slashes. In string yourtexthere/moretext the largest substring it will match is yourtexthere.
The pathConverter matches a string containing any type of character, so the result can contain a forward slash. It will match all of yourtexthere/moretext. So change your urlpatterns to this:
# Only patterns
urlpatterns = [
path('', home, name='home'),
path('<path:slug>/', textview, name='textview'),
]
The pathConverter will match all special characters. If you don't want this you can create your own custom converter with a regex tailored to your needs. For example, you could simply extend the slugConverter to also match strings with forward slashes.
class SlugPathConverter(StringConverter):
regex = '[-a-zA-Z0-9_/]+'

Why does a URL containing '/' after a '$' return a Page Not Found Error (404)

I'm having an issue with Django URL patterns.
When I add a '/' to the end of the index URL, the page returns a 404 error (Page Not Found) and if I remove the '/' from the end of the URL then the page works fine.
The issue is not reproducible with the URL for the admin page, can someone explain what's going on?
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$/',index),
]
$: Represents end of string, so, there's no posibility for a char living after it.
Matches the end of the string or just before the newline at the end of
the string
^ matches the start of the string so, ^$ in root urls.py means to Django: I don't want anything in my URL except the domain / base name then Django will route the request to your index page.
url method of django.conf.urls package accept regex as first parameter
$ represent end of string in regular expression hence any char after that will not be considered to match url string.
As I understood , in django urls:
'$' : End of the string, this is use in regex
'^' : It is also use in regular expression is matching starting of url
no characters after $ will be considered in the url pattern
hence change this to :
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^/$',index),
]

Django url disspatcher matches the wrong regex

I have created the following urlpatters
urlpatterns=[
url(r'(?P<user_name>[a-zA-Z]+)/$', views.profile_view,
kwargs=None, name='userprofile'),
url(r'(?P<user_name>[a-zA-Z]+)/interests/$',views.interest,name='interests')
]
But when I enter the url localhost:8000/mainuser/interest/ it treat it as first url and opens profile_view. It is clearly matching '/'. Help me with this.
You should begin your URL patterns with the start of line character ^. Because you are not including this character the regex for the first pattern matches any URL that ends with 1 or more characters followed by a forward-slash.
urlpatterns=[
url(r'^(?P<user_name>[a-zA-Z]+)/$', views.profile_view, kwargs=None, name='userprofile'),
url(r'^(?P<user_name>[a-zAZ]+)/interests/$',views.interest,name='interests'),
]

Only one letter of string is being passed to Django views function from template

HTML form:
<form id="save_form" method="post" action="{% url 'project_save' usernames=username project_name='lion' %}">
Notice the arg 'project_name's value is 'lion'
views.py:
def projectz_save(request, usernames, project_name):
template = loader.get_template('project_view/index.html')
context = RequestContext(request, {"username": usernames, "project": project_name})
return HttpResponse(template.render(context))
urls.py:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<usernames>\w+)(?P<project_name>\w+)save$', views.projectz_save, name='project_save'),
)
What happens is that only the 'n' in 'lion' is being passed as an argument. When I re-render the page, the template variable "project" now has the value 'n' instead of 'lion.' Any idea why this is happening?
It happens if I use a variable instead of a string (which is obviously the ultimate goal), but even simplified down to a simple string it's still happening.
Your problem is that while the template is correctly constructing the URL, your urls.py regexp is too greedy.
Specifically, you have no divider between your usernames named group and your project name named group:
r'^(?P<usernames>\w+)(?P<project_name>\w+)save$'
Given any sequence of word characters, all but the last will be matched by the \w+ in the usernames group. The last will be matched by the project_name group, because + requires at least one character. So if username in the template is 'johndoe', the url tag will construct the URL:
johndoelionsave
The regexp will then match johndoelio as the usernames group, since all of those are matched by \w+, n as the project_name group, since it's matched by \w+, and then the fixed save and end-of-string parts.
Your best fix will be to break up the URL pattern so that the parsing is unambiguous. I suggest:
r'^(?P<usernames>\w+)/(?P<project_name>\w+)/save$'
In which case the template tag will produce:
johndoe/lion/save
and the regexp will parse out the details you want.

Django urlpatterns frustrating problem with trailing slashes

All of the examples I can find of urlpatterns for django sites have a separate entry for incoming urls that have no leading slash, or the root folder. Then they handle subfolders on each individual line. I don't understand why a simple
/?
regular expression doesn't permit these to be on one simple line.
Consider the following, let's call the Django project Baloney and the App name is Cheese. So in the project urls.py we have something like this to allow the apps urls.py to handle it's requests...
urlpatterns = patterns('',
(r'^cheese/', include('Baloney.Cheese.urls')),
)
then inside of the Cheese apps urls.py, I don't understand why this one simple line would not trigger as true for all incoming url subpaths, including a blank value...
urlpatterns = patterns('',
(r'^(?P<reqPath>.*)/?$', views.cheeseapp_views),
)
Instead, it matches the blank case, but not the case of a value present. So...
http://baloneysite.com/cheese/ --> MATCHES THE PATTERN
http://baloneysite.com/cheese/swiss --> DOES NOT MATCH
Basically I want to capture the reqPath variable to include whatever is there (even blank or '') but not including any trailing slash if there is one.
The urls are dynamic slugs pulled from the DB so I do all the matching up to content in my views and just need the url patterns to forward the values along. I know that the following works, but don't understand why this can't all be placed on one line with the /? regular expression before the ending $ sign.
(r'^$', views.cheeseapp_views, {'reqPath':''}),
(r'^(?P<reqPath>.*)/$', views.cheeseapp_views),
Appreciate any insights.
I just tried a similar sample and it worked as you wrote it. No need for /?, .* would match that anyway. What is the exact error you are getting? Maybe you have your view without the request parameter? I.e. views.cheeseapp_views should be something like:
def cheeseapp_views(request, reqPath):
...
Edit:
The pattern that you suggested catches the trailing slash into reqPath because * operator is greedy (take a look at docs.python.org/library/re.html). Try this instead:
(r'^(?P<reqPath>.*?)/?$', views.cheeseapp_views)
note it's .*? instead of .* to make it non-greedy.