Problem with Django url - django

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),

Related

Do I need to create the template if I want to load the template correctly?

def directory_index(path, fullpath):
try:
t = loader.select_template([
'static/directory_index.html',
'static/directory_index',
])
except TemplateDoesNotExist:
t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
c = Context()
else:
c = {}
files = []
for f in fullpath.iterdir():
if not f.name.startswith('.'):
url = str(f.relative_to(fullpath))
if f.is_dir():
url += '/'
files.append(url)
c.update({
'directory': path + '/',
'file_list': files,
})
return HttpResponse(t.render(c))
This snippet is from static.py source code. It seems select_template will try to load directory_index.html or directory_index from the static subdirectory. To avoid raising the error, I guess I need to create a static folder following my DIR path and place directory_index.html in it, right?

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)

Get url from a string groovy

I am working with a grails app. I need to extract only part of the url up to .com (or gov, edu, mil, org, net, etc.) from a string.
For example:
Input: https://stackoverflow.com/questions?=34354#es4 Output: https://stackoverflow.com/
Input: https://code.google.com/p/crawler4j/issues/detail?id=174 Output: https://code.google.com/
Can anyone suggest how it can be done? Also, if it can be done, I need to change https to http in the resulting string. Please help. Thanks.
Edit: I apologize to all the downvoters that I did not include the thing that I tried. This is what i tried:
URL url = new URL(website);
String webUrl = url.getprotocol()+"://"+url.getAuthority()
But I got the following error: MissingPropertyException occurred when processing request: [POST] /mypackage/resource/crawl
Something like this satisfies the 2 examples given:
def url = new URL('http://stackoverflow.com/questions?=34354#es4')
def result = 'http://' + url.host +'/'
assert result == 'http://stackoverflow.com/'
def url2 = new URL('https://code.google.com/p/crawler4j/issues/detail?id=174')
def result2 = 'http://' + url2.host +'/'
assert result2 == 'http://code.google.com/'
EDIT:
Of course you can abbreviate the concatenation with something like this:
def url = new URL('http://stackoverflow.com/questions?=34354#es4')
def result = "http://${url.host}/"
assert result == 'http://stackoverflow.com/'
def url2 = new URL('https://code.google.com/p/crawler4j/issues/detail?id=174')
def result2 = "http://${url2.host}/"
assert result2 == 'http://code.google.com/'
I found the error in my code as well. I mistyped getProtocol as getprotocol and it evaded my observation again and again. It should have been:
URL url = new URL(website);
String webUrl = url.getProtocol()+"://"+url.getAuthority()
Thanks everyone for helping.
You can try
​String text = 'http://stackoverflow.com/questions?=34354#es4'
def parts = text.split('.com')
return parts[0] + ".com"
This should solve your problem

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

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.