Django Noob URL to from Root Page to sub Page - django

I have a Django project where I want to use an app for all the sites web pages. My project looks like this:
project
src
project
urls.py
views.py
...
web
migrations #package
urls.py
views.py
...
templates
web
index.html # I want this to be my root page
page2.html # This is the second page I'm trying to link to
I am trying to create a link in index.html that will take me to page2.html. This is what I am doing
In project->urls.py I have url(r'^$', include('web.urls', namespace="web")),. This should direct all page requests going to url http://127.0.0.1:8000/ to page index.html
project->views.py is empty because I want all web pages served up by the web app.
In web->urls.py I have url(r'^$', views.index, name='home_page') which relates to web->views.py and the function
def index(request):
print("Main index Page")
return render(request, 'web/index.html', {})
Which returns the correct page.
This works fine until I add the link to index.html for page2.html. The link looks like this: {% url 'web:page2' %}. I update web->urls.py. I add the following function into web->views.py:
def page2(request):
print("Page2")
return render(request, 'web/page2.html', {})
Now I get
Reverse for 'page2' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$page2/?$']
With the '{% url 'web:page2' %}' line highlighted.
When I remove the link everything works fine. What is wrong with my logic/setup?

You need to add an additional URL pattern:
urls = [
url(r'^page2/$', views.page2, name='page2'),
url(r'^$', views.index, name='home_page'),
]
or alternatively, pass a parameter you can use to identify the page to be rendered to the view. Currently, you aren't mapping a URL to the function you want to call when the URL is matched for page2, just the home page.

Related

Where is and how to edit the default Django homepage

Created a test demo project as below, how to edit the default Django homepage (or create my own homepage) that still using the same homepage url http://127.0.0.1:8000/?
Note: I don't want to create a new app and put the homepage under the new app, because that could change the homepage url from http://127.0.0.1:8000/ to http://127.0.0.1:8000/new_app.
You merely need to add the appropriate html template file and put the path into your project urls.py file. For example you could create a templates folder, under which you could add base.html or home.html or whatever you want (with the associated view), and then in urls.py you add:
path('', views.home),
You can get the default page back by adding the following in the urls.py file of your main app.
…
from django.views import debug
…
urlpatterns = [
…
path('', debug.default_urlconf),
…
]

NoReverseMatch Unless Url Is In Main Project Urls.py

I have a project called 'my_project' and within that project I have an app called 'my_app' so I have two urls.py files. All of my url's for my_app are located within it's urls.py file and work correctly, except one. That one is 'download_file'. My site works when this is included in my_project's urls.py, but when it's in my_app's urls.py I get a NoReverseMatch error on page load.
I don't know why this url only works when it's located in my main projects url's folder. I suspect it has something to do with the regex, though I can't figure it out.
The user would be on this page:
http://127.0.0.1:8000/user_area/username/classes
then click the 'download' link:
<a href="{% url 'download_file' file_path=item.instance.user_file %}" target='_blank'>{{ item.instance.filename }}</a>
my_project.py
urlpatterns = [
# reference to my_app
re_path(r'^user_area/(?P<username>[\w-]+)/', include('my_app.urls')),
]
# this works
url(r'^download_file/(?P<file_path>(.+)\/([^/]+))$', users_views.DownloadFile.as_view(), name='download_file'),
]
my_app.py
urlpatterns = [
path('classes', views.classes, name='classes'),
# if I remove the url from my_project.py this one returns NoReverseMatch on page load
url(r'^download_file/(?P<file_path>(.+)\/([^/]+))$', users_views.DownloadFile.as_view(), name='download_file'),
Thank you.
The problem is occurring because your URL template tag is providing only one parameter: file_path.
This works when the URL is declared in your project urls.py, because only one parameter is needed.
When you try to use the URL in my_app.urls, you need to also provide the username parameter. You will need to use something like:
<a href="{% url 'download_file' username=request.user.username file_path=item.instance.user_file %}" target='_blank'>{{ item.instance.filename }}</a>

django 1.10 one app page with a link redirect to another app page

I'm new to django server and trying to build a simple website for user registration. Here is the problem, I create my own app with index.html as my homepage. I also used another user registration app from:
https://github.com/pennersr/django-allauth/tree/master/allauth
I was trying to add the app to my homepage with a 'sign up' link. Basically, the account part, and ideally, the link can direct to: http://127.0.0.1:8000/accounts/login/
However, when I run the server, it gives me error:
Reverse for 'base' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
server result:
Both apps work fine individually, but when I try to add the link to my homepage, the error occurs.
The related code in index.html file in my first app:
<li>Log In</li>
The full path for index.html in my project is:
project/app1/templates/app1/index.html
The full path for base.html in my project is:
project/allauth/templates/base.html
I know I probably need to add a url line in my first app's urls.py file, and a view to show it, but how can I do it? Can anyone help me with this, much appreciate.
<li>Log In</li>
this line uses URL reversing, 'allauth:base' is the URL patterns, allauth prefix is the namespace, base is the named URL. You must define the namespace and named URL in the urls.py first.
Define your namespace in project's urls.py file like this:
from django.conf.urls import include, url
urlpatterns = [
url(r'^author-polls/', include('polls.urls', namespace='author-polls')),
url(r'^publisher-polls/', include('polls.urls', namespace='publisher-polls')),
]
Define your named URL in app's urls.py file like this:
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
...
]
all the help you need is in this document: Naming URL patterns

Using a name for dummy url patterns in django

I have a project with an app named exams. Right now my index page is the index page of one of these apps. So the url patterns is something like this:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^', include('exams.urls', namespace="exams")),
)
However it is possible that in future I want to create a new view for my index page and change the url patterns to something like this:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^exams/', include('exams.urls', namespace="exams")),
url(r'^/$', 'mysite.views.index', name="index"),
)
I want to create some links in my template to index whether it loads the exams app or another view. So I tried to use the name argument for the url method(like above) but it seems it's not working. When I use {% url 'index' %} in my template it returns the following error:
Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
UPD: I forgot to mention that I tried using the following code:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^', include('exams.urls', namespace="exams"), name="index"),
)
And I got the error I wrote above.
UPD2: To clarify the problem more:
Right now when I go to http://mydomain/ I'll see my app index. But maybe in the future I like to change my index page and use another view for creating it. So when I go to http://mydomain/ I'll see the page rendered by that view and by going to http://mydomain/exams I'll see my apps index pages. In that case my urls.py will be sth like the second code I wrote above in which I can easily link to index page using {% url 'index' %} tag. However for now I'm using the code I wrote in my first update. I want my templates to render {% url 'index' %} as a link to my index page(instead of using {% url 'exams:index' %} so when I later change the urls.py code I won't have to change all of my templates.
If I understand well, you want an index view that could be easily changed, while not changing the links pointing to it in your templates. You can use your index view as a wrapper for other views ie:
def a_view_that_will_show_all_the_exams(request):
# this is the page displayed for now as default, but this could change
# some logic here
def another_view_that_could_become_the_home_page(request):
# some logic here
def index(request):
return a_view_that_will_show_all_the_exams(request)
# or another_view_that_could_become_the_home_page
# or return exams.views.whatever_view
This way you can easily change the result of the index view while keeping your links static.
If I understood you correctly, right now you don't have a url with the name index, in his case it is normal that when the template renders, it tries to find a url named index, and when it doesn't find it, it fails. What you might need is create the url and redirect to another view for now, like explained here:
Redirect to named url pattern directly from urls.py in django?
UPDATE:
I'm still not completely sure of what you want (sorry about that), but I suspect what you want to do is something similar to this:
from django.conf.urls import patterns, include, url
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^exams/', include('exams.urls', namespace="exams")),
url(r'^/$', RedirectView.as_view(url=reverse_lazy('exams:index'), name="index"),
)
The solution that Raphael is giving you is similar, but the user will not be redirected (with both urls the user will see the same content). Maybe that is what you are looking for?

Django Unable to Find reverse() URL

I have the following URLConf setup:
urlpatterns = patterns('myapp.views',
url(r'^$', 'index', name="home"),
url(r'^login$', 'login'),
)
So far in my views, I have this:
def index(request):
"""Displays paginated message views"""
return HttpResponseRedirect(reverse("myapp.views.login"))
def login(request):
"""Displays login screen"""
return render_to_response('myapp/login.html', {
"title": "Login"
})
The problem arises when I try to go to the login page. Django seems to be unable to find my URL.
Going to the url http://localhost:8000/login, I receive the following error:
Page not found (404)
Request Method: GET Request
URL: http://localhost:8000/login
'login' could not be found
You're seeing this error because you have DEBUG = True in your Django
settings file. Change that to False, and Django will display a
standard 404 page.
It seems that even though I am using the reverse function to find Django's own recommended URL based on my URLConf, it is still unable to find its own URL!
Any ideas?
EDIT:
I need to clarify somethings: The problem is not that Django is unable to figure out the correct URL, it is that once that URL is loaded, Django is unable to find the view associated with that.
can you please put name attribute to your url like this
url(r'^$', 'index', name="home"),
then call reverse with this name
examples
urlpatterns = patterns('',
url(r'^archive/(\d{4})/$', archive, name="full-archive"),
url(r'^archive-summary/(\d{4})/$', archive, {'summary': True}, "arch-summary"),
)
from django.core.urlresolvers import reverse
def myview(request):
return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
It turns out the error was caused by me changing the STATIC_URL variable in my settings.py file. Changing that back to "/static/" made everything work.