Trying to update urls in Django but keep getting errors - django

I want to make my urls more descriptive for SEO purposes.
I want to add session variables and database variables, however neither seems to be working.
path was:
path('thing/<int:pk>'...)
trying to change to:
path('thing/<str:db_varible>/<int:pk>'...)
and trying to change to:
path('thing/<str:local_session_variable>/<int:pk>'...)
I'm keep getting the NoReverseMatch error.

Related

How to stop django from giving html pages as errors

I am working on an application with some friends and the back end REST API is in django. I sometimes get huge blocks of html printed to the console in place of anything meaningful, when I call an API from my angular front end. I have done some googling and I can't seem to find an answer of how to turn this off and make django return just error strings or json or something instead. Can someone help me get rid of this html?
Try using: https://docs.djangoproject.com/en/1.7/topics/logging/#configuring-logging
This will let you configure the logging in your django project.
Your Django app is working in debug mode. Please try this.
Go to ../yourdjangoproject/yourdjangoproject/settings.py
and find line Debug = True. Making it Debug=False will stop it from spitting out huge html upon errors.
Another thing you can do to only see errors as nice api response strings is this:
Find the view function which is giving the error, which can be found through the same huge html error message or by checking the view for url in urls.py
Then surround the whole view in try except like this.
def your_api_view(bla):
try:
#all of the view code goes here
except Exception as e:
return Response({"Error":e})
This way the error message will be shown to you like normal api response string.

Django doesn't read from database – no error

I just set up the environment for an existing Django project, on a new Mac. I know for certain there is nothing wrong with the code itself (just cloned the repo), but for some reason, Django can't seem to retrieve data from the database.
I know the correct tables and data is in the db.
I know the codebase is as it should be.
I can make queries using the Django shell.
Django doesn't throw any errors despite the data missing on the web page.
I realize that it's hard to debug this without further information, but I would really appreciate a finger pointing me to the right direction. I can't seem to find any useful logs.
EDIT:
I just realized the problem lies elsewhere. Unfortunately I can't delete this post with the bounty still open.
Without seeing any code, I can only suggest some general advice that might help you debug your problem. Please add a link to your repository if you can or some snippets of your database settings, the view which includes the database queries etc...
Debugging the view
The first thing I would recommend is using the python debugger inside the view which queries the database. If you've not used pdb before, it's a life saver which allows you to set breakpoints in your Python script and then interactively execute code inside the interpreter
>>> import pdb
>>> pdb.set_trace()
>>> # look at the results of your queries
If you are using the Django ORM, the QuerySet returned from the query should have all the data you expect.
If it doesn't then you need to look into your database configuration in settings.py.
If it does, then you must might not be returning that object to the template? Unlikely as you said the code was the same, but double check the objects you pass with your HttpResponse object.
Debugging the database settings
If you can query the database using the project settings inside settings.py from the django shell it sounds unlikley that there is a problem with this - but like everything double check.
You said that you've set up a new project on a mac. What is on a different operating system before? Maybe there is a problem with the paths now - to make your project platform independent remember to use the os.path.join() method when working with file paths.
And what about the username and password details....
Debugging the template
Maybe your template is referencing the wrong object variable name or object attribute.You mentioned that
Django doesn't throw any errors despite the data missing on the web
page.
This doesn't really tell us much - to quote the Django docs -
If you use a variable that doesn’t exist, the template system will
insert the value of the TEMPLATE_STRING_IF_INVALID setting, which is
set to '' (the empty string) by default.
So to check all the variables available to your template, you could use the debug template tag
{{ debug }}
Probably even better though is to use the django-debugging-toolbar - this will also let you examine the SQL queries your view is making.
Missing Modules
I would expect this to raise an exception if this were the problem, but have you checked that you have the psycopg module on your new machine?

Django URLs not matching with GET variables

I have the following django URL:
url(r'^companies/$', 'companies', name='companies'),
If I go to http://localhost:8000/companies/ it works perfectly. However, if I try adding any GET variables to the URL django raises a 404. For example, if I go to http://localhost:8000/companies/?c=1 django raises a 404. What's strange, is that on the 404 it says:
The current URL, companies/, didn't match any of these.
Why am I not able to pass GET variables to my URLs?
I am using django 1.4.
The companies view is defined like:
def companies(request):
It shouldn't have to accept any additional parameters because they are GET variables, not URL parameters- correct? I swear I've done this hundreds of times and it always just works...
Okay. Figured out what was causing this very strange behavior. I have a custom context processor that is calling resolve(request.get_full_path()). Apparently that causes a 404 if there are any GET variables in the URL. Very strange.

Django testing named URLs with additional GET parameters

I am trying to write some tests for a Django application I'm working on but I haven't yet decided on the exact urls I want to use for each view. Therefore, I'm using named urls in the tests.
For example, I have a url named dashboard:
c = Client()
resp = c.get(reverse('dashboard'))
This view should only be available to logged in users. If the current user is anonymous, it should redirect them to the login page, which is also a named url. However, when it does this, it uses an additional GET parameter to keep track of the url it just came from, which results in the following:
/login?next=dashboard
When I then try to test this redirect, it fails because of these additional parameters:
# It's expecting '/login' but gets '/login?next=dashboard'
self.assertRedirects(resp, reverse('login'))
Obviously, it works if I hard code them into the test:
self.assertRedirects(resp, '/login?next=dashboard')
But then, if I ever decide to change the URL for my dashboard view, I'd have to update every test that uses it.
Is there something I can do to make it easier to handle these extra parameters?
Any advice appreciated.
Thanks.
As you can see, reverse(...) returns a string. You can use it as:
self.assertRedirects(resp, '%s?next=dashboard' % reverse('login'))

Django url tag gives wrong values

My URLconf has:
url(r'^view-item$', 'appname.views.view_item', name='view-item'),
Now, if I go to http://myhost/path_to_django_app/view-item/, it works. However, {% url view-item %} returns '/view-item/'. Why is it doing this?
This problem occurred when I moved the application to a new server, so I'm guessing something must be configured wrong, but I don't even know where to look.
This may be due to the SCRIPT_NAME variable not being set correctly. The url tag will use this variable to compose the final absolute path to return.
You should check what request.META['SCRIPT_NAME'] is set to in one of your views. If it is not set correctly, then you may need to look into your backend configuration. If you are using mod_python, this usually involves making sure that django.root is set in the apache config. Check the installation docs for more info.
If you still can't get it to work, you can try adding this to settings.py:
FORCE_SCRIPT_NAME = '/path_to_django_app/'
The usual way to write your URl in django is with a trailing '/':
url(r'^view-item/$', 'appname.views.view_item', name='view-item')
or:
url(r'^view-item/', include('view.urls')),
Life will be much easier if you follow this convention.