In django how know if a url is part of urlpatterns config? - django

I build a dynamic breadcumb, and some parts of it are not valid urls (are not in urlpatterns).
I have this templatetag:
#register.filter
def crumbs(url):
"Return breadcrumb trail leading to URL for this page"
l = url.split('/')
urls = []
path = ""
for index, item in enumerate(l):
if item == "":
continue
path += item + "/"
urls.append({'path':path,'name':item})
Now, I want to check if that specific URL is a valid url, ie, have a key in urlpatterns (of curse I will need to change my templatetag).
Something like:
IsInUrlPattern('/') => True
IsInUrlPattern('/blog/2004/') => True
IsInUrlPattern('/blog/thisfail/') => False

You want the resolve() function.

Related

How to add URL component to current URL via a HTML button? (Django 2.1)

I have a HTML button that is supposed to sort the search results by alphabetical order.
Button HTML code:
A-Z
views.py:
def query_search(request):
articles = cross_currents.objects.all()
search_term = ''
if 'keyword' in request.GET:
search_term = request.GET['keyword']
articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity')
if request.GET.get('a-z') == 'True':
articles = articles.order_by('Title')
Currently, the URL contains the keywords searched by the user. For example, if the user searches for "cheese," the URL will be search/?keyword=cheese. When I click the sorting button, the URL becomes search/?a-z=True and loses the keyword, which means that the sorting mechanism isn't sorting the search results based on the keyword. I think I need the URL to contain both the keyword and ?a-z=True for the sorting mechanism to work on the search results. How can I make that happen?
I think this is not specific to Django only, you can use javascript to do that:
Add a function that will get the current url and do the sorting function and call that function via onclick.
Then add the necessary param.
A-Z
Then in your js part, you can check the url contains a keyword param, if not, just add the sort param.
function sort(foo) {
let url = window.location.href;
// check if current url includes a "keyword" param else add the sort as param
if(url.includes("?") && url.includes("keyword")) window.location.href = url + "&" + foo;
else window.location.href = url + "?" + foo;
}
This is just an idea and might not work since I never tried to run this.

Django Regex URL pattern overriding other URLs

I am working on a project which requires to display the data about a city which is requested through the url like example.com/city1 for city1 information etc.
I have used the below url pattern & view in my app. This view is working fine.
url(r'^(?P<cityId>[-\w]+)$',views.cityindex,name='cityindex'),
def cityindex(request, cityId):
city = City.objects.filter(url = cityId)
if len(city) == 0:
return redirect('/404')
return HttpResponse('City Data Extracted')
But when I try to open other urls like /admin or urls from other app it is being redirected to my cityindex view and then to 404 page as handled in my view above.
Below is the url patterns I used in my main urls.py file.
url(r'^', include('main.urls')),
url(r'^admin/', admin.site.urls),
url(r'^login_redirect/', include('loginapp.urls')),
I am presently using Django 1.11.12. Is there any way to stop this url from overriding?
Edit :
Urls in my main.urls file
url(r'^$',views.index,name='index'),
url(r'^about$', views.aboutpage,name="aboutpage"),
url(r'^terms$', views.termspage,name="termspage"),
url(r'^privacy$', views.privacypage,name="privacypage"),
url(r'^(?P<cityId>[-\w]+)$',views.cityindex,name='cityindex'),
To achieve this, think of sceanarios like this
1- www.example.com/cityname/
2- www.example.com/about/Us/
3- www.example.com/others/terms/
4- www.example.com/others/privacy/
Anytime you want to have other url like www.example.com/faculty/list
you use number 2-4 while you use the first to achieve your city name.
I have tested this to work in the following format
urlpatterns = [
url(r'^about/us/$', views.about_page), #about us or any other page
url(r'^(?P<cityname>\w+)/$', views.cityindex), #cityname
]
and in my view.py, i can catch the city name given like this
def cityindex(request, cityname):
data = cityname
#you can do anything you want here
return HttpResponse(data)
NB: the cityname could a number so you may decide to use it as city id instead, however, ensure it was converted to an integer in your view if you prefer to use cityid
I hope this helps

Django url dispatcher not identifying the view

Here is my urlpatterns
urlpatterns = [
url(r'^volunteer/$', views.volunteerInformation, name='volunteerInformation'),
url(r'^volunteer/(?P<ID>[0-0]{1})/$', views.volunteerInformation, name='volunteerInformation'),
]
Here is the view that I'm trying to call
def volunteerInformation(request, ID=None):
volunteers = Volunteer.objects.all()
if ID:
print ID
else:
print "XKCD"
return render(request, 'dbaccess/volunteer.html', {'volunteers': volunteers})
When the url is .../volunteer/, it prints XKCD. But when the url is ..../volunteer/1, I'm getting an error that the page was not found. Here is the error:
^ ^volunteer/(?P<ID>[0-0]{1})/$ [name='indVolunteerInformation']
^ ^volunteer/$ [name='volunteerInformation']
^admin/
The current URL, volunteer/3, didn't match any of these.
What can I do about it?
Your url regex is wrong, you are searching for numbers of length 1 in the range 0-0. To match any number change this:
^volunteer/(?P<ID>[0-0]{1})/$
for something like
^volunteer/(?P<ID>\d+)/$

How to pass non-latin string to url parameter in django?

Using django 1.7 and python 2.7, in a views I have:
page = 0
sex = [u'\u0632\u0646'] #sex = زن
url = "/result/%s/%d" % (sex, page)
return HttpResponseRedirect(url)
Which needs to return:
/result/زن/0
However the resulting url turns out to be:
/result/[u'\u0632\u0646']/0
Which is not what envisage in the pattern:
`url(r'^result/(?P<sex>\w+)/(?P<page>\d+)','userprofile.views.profile_search_result')`,
I also tried
return HttpResponseRedirect( iri_to_uri(url))
but does not solve the problem.
I got really confused and appreciate your help to fix this.
Since sex is a list, you simply need to use the actual element you want:
url = "/result/%s/%d" % (sex[0], page)
Although note that to construct URLs in Django, you should really use the reverse function:
from django.core.urlresolvers import reverse
...
url = reverse('userprofile.views.profile_search_result', kwargs={'sex': sex[0], 'page': page})
url should also be an unicode string for that to work:
page = 0
sex = u'\u0632\u0646' #sex=زن
url = u"/result/%s/%d" % (sex, page)
return HttpResponseRedirect(url)

Problem with Django url

Going to http://127.0.0.1:8300/projects/cprshelp/edit_file/?filename=manage.py results in a 404 error
urls.py
(r'^projects/(?P<project_name>[\w ,-<>]+)/', include('projects.urls')),
projects/urls.py
(r'edit_file/$', views.edit_file),
What do I need to change to my url files to make this particular url work?
List of valid urls:
^admin/doc/
^admin/
^projects/(?P<project_name>[\w ,-<>]+)/ edit_file/$
^media/(?P<path>.*)$
edit_file function:
def edit_file(request, project_name):
print '**** project name ' + project_name
#project = Project.objects.get(name=project_name)
filename = request.GET['filename']
#content_of_file = open(project.file_location + filename, 'r')
#content_of_file = '\n'.join(content_of_file.readlines())
context = RequestContext(request, {
#"project": project,
#"files": get_files_and_directories(project.file_location),
"filename": filename,
#"content_of_file": content_of_file,
})
return render_to_response("edit_file.html", context)
You need to backslash your - in your regex:
>>> p = re.compile(r'projects/[\w ,-<>]+/')>>> p.search('http://127.0.0.1:8300/projects/cprshelp/edit_file/?filename=manage.py').group()
'projects/cprshelp/edit_file/'
>>> p = re.compile(r'projects/[\w ,\-<>]+/')>>> p.search('http://127.0.0.1:8300/projects/cprshelp/edit_file/?filename=manage.py').group()
'projects/cprshelp/'
>>>
also consider using .get:
filename = request.GET.get('filename','')
Try changing your project/urls.py to
(r'^edit_file/$', views.edit_file),