I am new to Django and just playing around with the code and features but I seem to be stuck (yes I have done the entire tutorial). For some reason my mysite/urls.py is not taking me to the right urls, actually it ONLY takes me to one template no matter what I do. Here is my urls.py:
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('app.views',
(r"^app/$",'index'),
(r"^app/detail/$",'detail'),
url(r'^admin/', include(admin.site.urls)),
)
My app/views.py is:
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.http import HttpResponse
from mysite.app.models import Post,PostAdmin
def index(request):
return render_to_response("app/link1.html")
def detail(request):
return HttpResponse("You're looking at detail.")
I have a base.html template and link1 which {% extends base.html %}. But for some reason if I enter http://localhost:8000/app or http://localhost:8000/app/detail, I get the link1.html? Or even when I do http://localhost:8000/, I just get the link1.html. What could cause this? (Its probably something minor)
If I understand correctly shouldn't the url pattern with (r^"app/detail/$",'detail'), take me to the detail HttpResponse in views.py like the tutorial rather than a template?
Thank you
I have checked your code, it works just fine. I cannot replicate such error with your views and urls. Post your templates and directory structure to make sure they are fine too.
test result for /app/
Hello link 1.
test result for /app/detail/
You're looking at detail.
Related
I recently began learning django and have been running into some trouble and I can't figure out why.
My problem is quite simple: whenever I try to run my homepage with a template, it throws up a 404 error.
My file hierarchy is as such:
crm
accounts
templates
accounts
dashboard.html
urls.py
views.py
crm
urls.py
In crm/urls, I have
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('accounts.urls'))
Then in accounts/urls, there is,
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
And in views, I have
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return render(request, 'accounts/dashboard.html')
My dashboard.html is just a basic html file with a title and h1, that's it.
Also, whenever I change
return render(request, 'accounts/dashboard.html')
to
return HttpResponse('home')
in my home function, it decides to show.
Your dashboard.html is inside a folder, so it should be referenced like accounts/dashboard.html
Relevant docs: https://docs.djangoproject.com/en/3.0/intro/tutorial03/#a-shortcut-render
In their example, they are using polls/index.html (scroll a bit up from the linked position in the docs). It is analogous to your accounts/dashboard.html in placement (both are in a subfolder as they should be).
Django looks for templates across multiple apps in the same way it searches for static files. Except that you can "see" static files being copied over to a separate folder with manage.py collectstatic while templates get "discovered" in place and not copied anywhere. In facg, if you are running manage.py runserver then the static files are also discovered in place, so the logic is the same.
One difference is that template loading can be changed by using a different set of loaders (docs on template loaders, but by default (and for the majority of projects I guess) this similarity holds.
Hello StackOverflow community,
I'm currently learning how to use the library Django combined with Python. However, I've ran into some issues which are somehow strange. My situation is the following. I have a project called "animals" which is the base of the Django application. My app is called "polls". Then I've defined the following views.
polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
def animals(request, animal_id):
return HttpResponse("%s" % animal_id)
def index(request):
return HttpResponse('Hello world')
So far, so good. Unfortunatly I can't say the same about the urlpatterns.
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index'),
# Redirects to localhost:8000/polls/<animal_id>
path('<int:animal_id>/',views.animals,name='animals')
]
Whenever I want to navigate to the url "localhost:8000/polls/10/" Django reminds me of the fact, that the url is not accepted by the application and a 404 Error is thrown inside my browser. Am I missing something here?
UPDATE
I've managed to resolve the problem by fixing a rather trivial error. While the polls/urls.py was alright, the problem lay inside the animals/urls.py file. This file looked like this:
animals/urls.py
from django.conf.urls import url
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
url(r'^admin/', admin.site.urls),
path('polls',include('polls.urls')),
]
As one can see, the "polls" path is not finished with a "/" sign. This indicates to Django that my desired route would be localhost:8000/polls where is any integer I add to the url. However, you have to add the slash at the end. Otherwise Django won't work as expected.
I am following the Django 1.6 tutorial 3 (https://docs.djangoproject.com/en/1.6/intro/tutorial03/) and I have become stuck towards the beginning - "Writing your first view".
The Django tutorial first says to edit the views.py, which I have done as follows:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
Then it says to create a urls.py in the same directory, which I have done. My urls.py looks like this:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
The next instruction is to now check the URL http://localhost:8000/polls/ for the message 'Hello, world. You're at the poll index.' but my browser simply produces the Django 404 error - Page not found.
I'm sure I'm doing something pretty stupid but I can't what is wrong, I've tried restarting the python webserver. I've followed the previous 2 tutorials with success, can anybody help me out?
If it makes a difference, I'm using Windows7, Python 3.4.1 and Django 1.6.5
Your view.py for polls must be in projectname/polls/ directory when first urls.py will be in projectname/projectname/.
Then, if you decide to configure and add more polls app specific urls, you can create urls.py in projectname/polls/.
Building a blog in Django and I suspect something is wrong with matching my main urls.py
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'$', 'posts.views.home'),
url(r'^(?P<slug>[\w-]+)/$', 'posts.views.single'),
)
Here's my views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, RequestContext, Http404, get_object_or_404
from .models import Post
def home(request):
posts = Post.objects.filter(private=False)
return render_to_response('all.html', locals(), context_instance=RequestContext(request))
def single(request, slug):
post = Post.objects.filter(slug=slug)
return render_to_response('single.html', locals(), context_instance=RequestContext(request))
The function-based view home works perfectly and returns all non-private posts. However, the single view alters the URL to make the correct slug (ie: 127.0.0.1/this-correct-slug) but just goes to the top of the page and does nothing to filter the content (shows a 200 GET request in terminal). Using post = get_object_or_404(Post, slug=slug) yields same result.
I'm unsure of the post = Post.objects.filter(slug=slug) part but I also know it's not getting that far - trying to add print statements to see if the function is being called shows nothing.
I'm also a little unsure of the argument locals(). I've been using it but, frankly, only because I'm still not sure how to use the data dictionary.
Assume that the templates all.html and single.html are correct.
Thanks!
The problem is that your first regex is not rooted. It matches '$' which basically means "any string that ends" - which is everything. So all URLs end up being matched by that pattern.
It should be ^$, ie the empty string.
I'm following the Django tutorial and got stuck with an error at part 4 of the tutorial. I got to the part where I'm writing the vote view, which uses reverse to redirect to another view. For some reason, reverse fails with the following exception:
import() argument 1 must be string, not instancemethod
Currently my project's urls.py looks like this:
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^polls/', include('mysite.polls.urls')),
(r'^admin/(.*)', include(admin.site.root)),
)
and the app urls.py is:
from django.conf.urls.defaults import *
urlpatterns = patterns('mysite.polls.views',
(r'^$', 'index'),
(r'^(?P<poll_id>\d+)/$', 'details'),
(r'^(?P<poll_id>\d+)/results/$', 'results'),
(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)
And the vote view is: (I've simplified it to have only the row with the error)
def vote(request, poll_id):
return HttpResponseRedirect(reverse('mysite.polls.views.results', args=(1,)))
When I remove the admin urls include from the project's urls.py, i.e. making it into:
urlpatterns = patterns('',
(r'^polls/', include('mysite.polls.urls')),
#(r'^admin/(.*)', include(admin.site.root)),
)
it works.
I've tried so many things and can't understand what I'm doing wrong.
The way you include the admin URLs has changed a few times over the last couple of versions. It's likely that you are using the wrong instructions for the version of Django you have installed.
If you are using the current trunk - ie not an official release - then the documentation at http://docs.djangoproject.com/en/dev/ is correct.
However, if you are using 1.0.2 then you should follow the link at the top of the page to http://docs.djangoproject.com/en/1.0/.