1👍
There is nothing in your urls.py
or views.py
that could cause that.
I assume if you type {mysite}/index.html
into the browser it goes to the Home page as expected?
…and it’s only when you are on a journal page and click the ‘Home’ link that it goes to the wrong url?
It sounds like you have a problem with the href
of the links in your HTML… probably your link looks like: <a href="index.html">Home</a>
?
It is missing the slash in front so the url is treated relative to the current url, i.e. if you are on /journal/2014/01
then clicking that link will take you to /journal/2014/01/index.html
The best way to avoid these kind of problems (and to avoid having to change all your templates if you change any of the urls in urls.py
) is to name your urls and use Django’s url
tag
Note that Django url patterns are regular expressions so you should be escaping the .
character as \.
Also, taking advantage of regex, you only need one url pattern to match all the urls you want to accept for the index
view. Same for the journal
view.
So your urls.py
would look like:
urlpatterns = patterns(
'',
url(r'^(?:index\.html)?$', index, name='index'),
url(r'^contact\.html$', contact, name='contact'),
url(r'^about\.html$', about, name='about'),
url(r'^journal(?:\.html$|/(\d{4})(?:/(\d{2}))?$)', journal, name='journal'),
url(r'^auth\.html$', auth, name='auth'),
url(r'^logout\.html$', logx, name='logout'),
url(r'^admin/', include(admin.site.urls)),
# develop
url(r'^Observations/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': MEDIA_ROOT}),
)
And in your templates:
<a href="{% url 'index' %}">Home</a>
<a href="{% url 'journal' %}>Journal</a>
<a href="{% url 'journal' '2014' %}>Journal: 2014</a>
<a href="{% url 'journal' '2014' '06' %}>Journal: June 2014</a>
I would probably make a further change, which is to use named groups for your journal
url:
url(r'^journal(?:\.html$|/(?P<year>\d{4})(?:/(?P<month>\d{2}))?$)', journal, name='journal'),
and update the view code accordingly:
def journal(request, year=None, month=None):
# print args
if request.user.is_authenticated():
obss = Obs.objects.all()
if year is not None:
obss = obss.filter(date__year=year)
if month is not None:
obss = obss.filter(date__month=int(month))
ar_obs = Obs.objects.all()
archive = create_archive_data(ar_obs)
return render_to_response('journal.html', {'obss': obss, 'user': request.user,
'archive_counts': archive})
else:
state = "Please log in below..."
# return HttpResponseRedirect('auth.html', {'state': state})
return render_to_response('auth.html', {'state': state})
Also, rather than doing the is_authenticated
check and subsequent login redirect manually in every view that needs it, you should look at using Django’s login_required
decorator:
https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.decorators.login_required