No template named index error - python

I am new to Python, and I am trying to run a web.py app with Python Anywhere, but I keep getting the No template named index error. I've modified wsgi.py to use the following:
import web
import MySQLdb
urls = (
'/', 'index'
)
render = web.template.render('/home/user/templates/')
Any help would be greatly appreciated.

You've used the literal path '/home/user/templates/'. Unless your username is actually user, there is no such directory, and therefore attempting to read the index template out of that directory is going to fail.
If your username is, say, rhpt, you'd change that to '/home/rhpt/templates/'.
Even better, you might want to use os.path.expanduser('~/templates/') instead of hardcoding your username. (Then you can give your code to a friend, or a client, and they can host it without having to edit the code.)

Related

Something's Wrong When I Try to Register on my Website [duplicate]

I have some code and when it executes, it throws a NoReverseMatch, saying:
NoReverseMatch at /my_url/ Reverse for 'my_url_name' with arguments '()' and keyword arguments '{}' not found. n pattern(s) tried: []
What does this mean, and what can I do about it?
The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.
The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.
To start debugging it, you need to start by disecting the error message given to you.
NoReverseMatch at /my_url/
This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched
Reverse for 'my_url_name'
This is the name of the url that it cannot find
with arguments '()' and
These are the non-keyword arguments its providing to the url
keyword arguments '{}' not found.
These are the keyword arguments its providing to the url
n pattern(s) tried: []
These are the patterns that it was able to find in your urls.py files that it tried to match against
Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.
Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.
Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.
The url name
Are there any typos?
Have you provided the url you're trying to access the given name?
If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').
Arguments and Keyword Arguments
The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.
Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.
If they aren't correct:
The value is missing or an empty string
This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.
The keyword argument has a typo
Correct this either in the url pattern, or in the url you're constructing.
If they are correct:
Debug the regex
You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.
Common Mistakes:
Matching against the . wild card character or any other regex characters
Remember to escape the specific characters with a \ prefix
Only matching against lower/upper case characters
Try using either a-Z or \w instead of a-z or A-Z
Check that pattern you're matching is included within the patterns tried
If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)
Django Version
In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.
If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.
A very common error is when you get with arguments ('',). This is caused by something like this:
{% url 'view-name' does_not_exist %}
As does_not_exist doesn't exist, django evaluates it to the empty string, causing this error message.
If you install django-fastdev you will instead get a nice crash saying does_not_exist doesn't exist which is the real problem.
With django-extensions you can make sure your route in the list of routes:
./manage.py show_urls | grep path_or_name
If the route is missing you probably have not imported the application.
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView - I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name for the new class, it worked fine.
The arguments part is typically an object from your models. Remember to add it to your context in the view. Otherwise a reference to the object in the template will be empty and therefore not match a url with an object_id.
Watch out for different arguments passing between reverse() and redirect() for example:
url(r"^some_app/(?P<some_id>\d+)/$", some_view_function, name="some_view")
will work with:
reverse("some_view", kwargs={"some_id": my_id})
and:
redirect("some_view", some_id=my_id)
but not with:
reverse("some_view", some_id=my_id)
and:
redirect("some_view", kwargs={"some_id": my_id})

Changing Django's default list of Common Password

I just try to use Django. when i try to create superuser with the createsuperuser and i try to use some common password like abcd1234 (because abc or 123 isn't allowed), it cannot accept it because apparently that my password is too common, i know that the createsuperuser use somekind of password list to match mine with theirs. I want to ask that whether it is possible to change the password list.
i already tried to open manage.py to find the createsuperuser method but i didnt find it because it only contains run(sys.argv)
You should be able to.
Look for a folder which follows the path:
\Python3\Lib\site-packages\django\contrib\auth or the equivalent on your system.
In it, you should see a file named common-passwords.txt.gz.
Inside it, there will be a file called common-passwords.new.txt
You should just be able to change the passwords on the list. One password per line. Passwords should be entirely lowercase as Django automatically translates passwords to lowercase for comparison against the common password list.
Relevant documentation: https://docs.djangoproject.com/en/2.2/topics/auth/passwords/#django.contrib.auth.password_validation.CommonPasswordValidator
Welcome to Stackoverflow!
You can follow the other answer as well. But you will have to place your password file whenever you change your virtualenv. Here is the way to keep it in the project.
Place your file in project folder where manage.py exists
Open settings.py from your projects folder and add the following
FILE_NAME = "custom_common_password_list.txt"
Create a file custom_common_password.py under projects folder
# projectname/custom_common_password.py
import os
from django.contrib.auth.password_validation import CommonPasswordValidator
from django.conf import settings
class CustomCommonPasswordValidator(CommonPasswordValidator):
def __init__(self):
super().__init__(password_list_path=os.path.join(settings.BASE_DIR, settings.FILE_NAME))
We are basically calling the CommonPasswordValidator with our file path.
Modify the AUTH_PASSWORD_VALIDATORS and add the following:
AUTH_PASSWORD_VALIDATORS = [
# ...
{
'NAME': 'projectname.custom_common_password.CustomCommonPasswordValidator',
},
#...
]
We comment the existing CommonPasswordValidator and place our custom validator. Make sure to replace projectname with your project name.
I would definitely recommend using a safer password.
Why? You don't want hackers to guess your password and hijack your website. Even small websites are targets of large fishing attempts and can be used to spread malware and do bad stuff.
One method that hackers use to gain entrance to your system is by using common password lists. So make sure that you choose a password that is not in such lists.
An easy to remember password which is still safe might consist of several words. As an alternative, you could use a password manager to remember a random string of characters for you.
You can find more suggestions here on how to create safe passwords: https://www.bu.edu/tech/support/information-security/security-for-everyone/how-to-choose-a-strong-password/

Django reverse error [duplicate]

I have some code and when it executes, it throws a NoReverseMatch, saying:
NoReverseMatch at /my_url/ Reverse for 'my_url_name' with arguments '()' and keyword arguments '{}' not found. n pattern(s) tried: []
What does this mean, and what can I do about it?
The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.
The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.
To start debugging it, you need to start by disecting the error message given to you.
NoReverseMatch at /my_url/
This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched
Reverse for 'my_url_name'
This is the name of the url that it cannot find
with arguments '()' and
These are the non-keyword arguments its providing to the url
keyword arguments '{}' not found.
These are the keyword arguments its providing to the url
n pattern(s) tried: []
These are the patterns that it was able to find in your urls.py files that it tried to match against
Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.
Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.
Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.
The url name
Are there any typos?
Have you provided the url you're trying to access the given name?
If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').
Arguments and Keyword Arguments
The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.
Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.
If they aren't correct:
The value is missing or an empty string
This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.
The keyword argument has a typo
Correct this either in the url pattern, or in the url you're constructing.
If they are correct:
Debug the regex
You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.
Common Mistakes:
Matching against the . wild card character or any other regex characters
Remember to escape the specific characters with a \ prefix
Only matching against lower/upper case characters
Try using either a-Z or \w instead of a-z or A-Z
Check that pattern you're matching is included within the patterns tried
If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)
Django Version
In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.
If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.
A very common error is when you get with arguments ('',). This is caused by something like this:
{% url 'view-name' does_not_exist %}
As does_not_exist doesn't exist, django evaluates it to the empty string, causing this error message.
If you install django-fastdev you will instead get a nice crash saying does_not_exist doesn't exist which is the real problem.
With django-extensions you can make sure your route in the list of routes:
./manage.py show_urls | grep path_or_name
If the route is missing you probably have not imported the application.
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView - I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name for the new class, it worked fine.
The arguments part is typically an object from your models. Remember to add it to your context in the view. Otherwise a reference to the object in the template will be empty and therefore not match a url with an object_id.
Watch out for different arguments passing between reverse() and redirect() for example:
url(r"^some_app/(?P<some_id>\d+)/$", some_view_function, name="some_view")
will work with:
reverse("some_view", kwargs={"some_id": my_id})
and:
redirect("some_view", some_id=my_id)
but not with:
reverse("some_view", some_id=my_id)
and:
redirect("some_view", kwargs={"some_id": my_id})

django-session-security session not expiring

i am trying to use ajax pooling on my site (setTimeout) alongside django-session-security . In the documentation there is a mention of SESSION_SECURITY_PASSIVE_URL but i can't seem to get it to work.
My settings:
SESSION_SECURITY_WARN_AFTER = 15
SESSION_SECURITY_EXPIRE_AFTER = 21
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SECURITY_PASSIVE_URL = ['http://localhost:8000/core/notice/check/', 'core/notice/check/', '/core/notice/check/']
My javascript:
setTimeout(function(){
get_notifications();
}, 2000);
Any ideas what i am doing wrong?
It seems that it's just because your settings parameter name is missing the ending 's'. It should be 'SESSION_SECURITY_PASSIVE_URLS' instead of 'SESSION_SECURITY_PASSIVE_URL' in your case. Consider the source code here.
Other than that I believe you can safely remove redundant elements from the SESSION_SECURITY_PASSIVE_URLS list and leave just the '/core/notice/check/' entry there. Again, as we can see from the source code the decision of whether request 'is passive' is made by checking the request.path against the list of values from the settings.
Can't comment, thus attempting to answer here. Have you added {% include 'session_security/all.html' %} to your (base) template? Also do you have added session_security URLs in appropriate urls.py file?
SESSION_SECURITY_PASSIVE_URLS allows you to add static urls. However, most urls in Django are anything but static. How would you add dynamic urls to this list to bypass session update. For example in url /category/1/product/5/, 1 and 5 are dynamic ids but I would like to skip any url that matches the pattern
'/category/(?P<cat_id>[\d]+)/product/(?P<product_id>[\d]+)/'
This is unlikely, but if you are using django-ajax middleware AJAXMiddleware, it conflicts with session_security mechanism, and either the session expiry notification might not appear or session expiration might not work altogether. I had to remove AJAXMiddleware to make session_security work again.

Why won't my regex parse this URL in Django?

Currently working in Django, and I'm trying to set things up so that a form on one page calls a specific URL, for which the appropriate view is rendered. I'm having trouble with the regular expression that parses the URL, as it won't read the value '\?' as an escaped question mark, which is what I believe it should be doing. The following RE checks out on Pythex.
When the app submits the form, it calls the URL:
http://127.0.0.1:8000/map/?street=62+torrey+pines+cove&city=san+diego&state=CA&radius=50&drg=4
In my project level urls.py file, I have the following:
url(r'^map/', include('healthcare_search.urls', namespace="healthcare_search")),
This calls my app level urls.py file, where I have:
url(r'^\?street=(?P<street>[a-z0-9+]+)&city=(?P<city>[a-z+]+)&state=(?P<state>[a-z]{2})&radius=(?P<radius>[0-9]{1,3})&drg=(?P<drg>[0-9]{1,3})', views.map_hospitals, name = "map_hospitals"),
This just results in a 404 error, saying the URL doesn't match any of the patterns. I know that it's a RE problem, because I removed everything from the app level RE, and submitted just http://127.0.0.1:8000/map/ to see if it would call the right view, which it did successfully. Things seem to break apart on the '\?'. Any ideas what I'm doing wrong?
As a note, this is the first time I've written a regular expression, so my apologies if it is unclear or poorly written.
You don't want to get access to the variables that way. A better option is to get them from the request, since they'll be available in the request's dictionary of variables. In your view, you can get the value of street via request.GET.get('street', None), which will return the value if street is in the request or return None otherwise.

Categories

Resources