I'm beginner, but I've been looking everywhere for solution. I can't see uploaded images (404).
Error from image link (for example:http://192.168.1.1:8000/media/portfolio/icon.png/ -> by the way, this proper url ) :
No SuperPages matches the given query.
SuperPages is my model which contains url object.
I configured everything for media files like here: http://www.muhuk.com/2009/05/serving-static-media-in-django-development-server/. And to be clear, when I'm using generic views only, it works great. But with views, I can't see images (links to images are fine). Static files works great. So this is my code:
urls.py
from mysite.cms.views import superpages
urlpatterns = patterns('',
(r'^(?P<url>.*)$', superpages),)
views.py
from django.template import loader, RequestContext
from mysite.cms.models import SuperPages
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
DEFAULT_TEMPLATE = 'default.html'
def superpages(request, url):
if not url.endswith('/') and settings.APPEND_SLASH:
return HttpResponseRedirect("%s/" % request.path)
if not url.startswith('/'):
url = "/" + url
f = get_object_or_404(SuperPages, url__exact = url)
t = loader.get_template(DEFAULT_TEMPLATE)
c = RequestContext(request, {
'superpages': f,
})
return HttpResponse(t.render(c))
There's something wrong with your urls.py. I suppose you have defined your patterns like this:
urlpatterns = patterns('',
(r'^(?P<url>.*)$', superpages),
(r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
A URL such as http://192.168.1.1:8000/media/portfolio/icon.png/ matches the first pattern so your superpages view is called and raises a 404. What you need to do is put your catch-all superpages pattern at the very end of your urlpatterns. Or you can choose a different approach with a middleware, see what django.contrib.flatpage does for an example.
Related
I have an app which is called sitepages which have three models I wanna pass their objects to a html page called listing.html which is inside templates/sitepages
the sitepages urls.py contains:
from django.views.generic import TemplateView
from django.urls import include
from django.urls import path
from sitepages import views
app_name = "sitepages"
urlpatterns = [
path("news-events-listing/", views.view, name='listing'),
]
the sitepages/views.py:
from .models import Listing, Details1, Details2
from django.template.response import TemplateResponse
def view(request):
return TemplateResponse(request, 'sitepages/listing.html', {
'first_pages': Details1.objects.all(),
'seconde_pages': Details1.objects.all(),
'listing_page': Listing.objects.first(),
})
in the root urls.py I added:
path("", include("sitepages.urls", namespace='sitepages'))
when I put in any template the following:
Listing
it redirects me to the url /news-events-listing but no page is found and it gives me 404 error...what am I doing wrong? why the template is not returned? I should mention that I'm using wagtail for the whole site (I don't know if it's related)
In your root urls.py, make sure your new line
path("", include("sitepages.urls", namespace='sitepages'))
appears before the path("", include(wagtail_urls)) line. The wagtail_urls pattern matches any URL path and passes it to Wagtail to be handled as a Wagtail page, so any patterns after it will never be reached.
I'm very very new to Python 3 and Django and I get to the following problem: I use a standard Template and now how to set it up when there is 1 view. But I don't get the code right for multiple views. I currently run the page locally
At the moment I have tried to change different orders within urlpatterns, and they do work when only 1 url in in there, but I can't get the second one in
views.py
from django.shortcuts import render, render_to_response
# Create your views here.
def index(request):
return render_to_response('index.html')
def store(request):
return render_to_response('store.html')
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from myapp import views as views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^store/$', views.store, name='store'),
url(r'^admin/', admin.site.urls)
]
urlpatterns += staticfiles_urlpatterns()
I would like the url pattern that lets me go to the index view and the store view
EDIT:
Full code is shared via: https://github.com/lotwij/DjangoTemplate
The error in the comments shows you are going to http:/127.0.0.1:8000/store.html, but your URL pattern url(r'^store/$', ...) does not include the .html, so you should go to http:/127.0.0.1:8000/store/.
The Django URL system uncouples the URL from the name of the template (sometimes the view doesn't even render a template!). You could change the regex to r'^store.html$ if you really want .html in the URL, but I find the URL without the extension is cleaner.
With my (Django v 1.17) project I am using django-subdomains.
I have no problem to call index view and when I open my url https://subdomain.domain.com I will get index.html.
My issue that I wrote a new view called example for the sub-domain but when I open the url https://subdomain.domain.com/exmaple I will get error Page not found (404).
Hete is my code:
settings.py
INSTALLED_APPS = [
'subdomain'
]
SUBDOMAIN_URLCONFS = {
'subdomain': 'subdomain.urls',
}
subdomain/urls.py
from django.conf.urls import url, include
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$example', views.example, name='example'),
]
subdomain/views.py
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
def index(request):
template = loader.get_template('subdomain/index.html')
return HttpResponse(template.render())
def example(request):
template = loader.get_template('subdomain/example.html')
return HttpResponse(template.render())
Error:
Page not found (404)
Request Method: GET
Request URL: https://subdomain.domain.com/example
Using the URLconf defined in subdomain.urls, Django tried these URL patterns, in this order:
1. ^$ [name='index']
2. ^$example [name='example']
The current path, econ, didn't match any of these.
Please advise how to fix this issue and write view for sub-domain.
This is unrelated to django-subdomains. The dollar should be at the end of the regex.
url(r'^example$', views.example, name='example'),
The dollar matches the end of the string, so if you have it at the beginning then it's not going to match.
While i'm rendering a template i would like to retrieve the url of the template by giving the namespace value and not the path. For example instead of this:
return render(request, 'base/index.html', {'user':name})
i would like to be able to do the following:
from django.shortcuts import render
from django.core.urlresolvers import reverse
return render(request, reverse('base:index'), {'user':name})
but the above produces an error. How can i do it? Is there any way to give the namespace to a function and get the actual path?
Extended example:
- urls.py
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^', include('base.urls', namespace='base')),
)
- app base: urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('base.views',
url(r'^/?$', 'index', name='index'),
)
- app base: views.py
from django.shortcuts import render
from django.core.urlresolvers import reverse
def homepage(request):
'''
Here instead of 'base_templates/index.html' i would like to pass
something that can give me the same path but by giving the namespace
'''
return render(request, 'base_templates/index.html', {'username':'a_name'})
Thanks in advance.
Template names are hard coded within the view. What you can also do is that you can pass the template name from the url pattern, for more details see here:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('base.views',
url(r'^/?$', 'index',
{'template_name': 'base_templates/index.html'},
name='index'),
)
Then in view get the template name:
def index(request, **kwargs):
template_name = kwargs['template_name']
Consider that I have 1 resource and 2 urls (let's say new one and old one) connected to that resourse. So, i want to setup HTTP redirection for one of urls.
In myapp/urls.py I have:
urlpatterns = patterns('',
url(r'^(?P<param>\d+)/resource$',
'myapp.views.resource',
name='resource-view'
),
)
In mycoolapp/urls.py I want to specify:
from django.views.generic.simple import redirect_to
from django.core.urlresolvers import reverse_lazy
urlpatterns = patterns('',
url(r'^coolresource/(?P<param>\d+)/$',
redirect_to,
{
'url': reverse_lazy('resourse-view',
kwargs={'param': <???>},
current_app='myapp'
),
}
),
)
The question is how to pass <param> to the reverse_lazy kwargs (so, what to put instead of <???> in the example above)?
I wouldn't do this directly in the urls.py, I'd instead use the class-based RedirectView to calculate the view to redirect to:
from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse_lazy
class RedirectSomewhere(RedirectView):
def get_redirect_url(self, param):
return reverse_lazy('resource-view',
kwargs={'param': param},
current_app='myapp')
Then, in your urls.py you can do this:
urlpatterns = patterns('',
url(r'^coolresource/(?P<param>\d+)/$',
RedirectSomewhere.as_view()),
)
Redirect View is great if you are using a hard coded url, it replaced redirect_to which is now deprecated. I don't think you can use it when redirecting and reversing from urls.py. Here is my solution, x is the response object in this case:
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
urlpatterns = patterns('',
....
url(r'^coolresource/(?P<param>\d+)/$',
lambda x, param: HttpResponseRedirect(
reverse('myapp.views.resource', args=[param])
),
name='resource-view-redirect'),
....
)
You can still use the name of the url pattern instead of a hard coded url with this solution. The location_id parameter from the url is passed down to the lambda function.
As of Django 1.6 you can do this (Documentation):
...
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^coolresource/(?P<param>\d+)/$',
RedirectView.as_view(pattern_name='resource-view'),
),
)
One of the possible solutions of the general problem is to use hard-coded url pattern instead of reverse_lazy (documentation)
url(r'^coolresource/(?P<param>\d+)/$',
redirect_to,
{'url': '/%(param)s/resource'}
),
But, I don't like it so much, since it makes me harder after to do possible changes in urls.
You can't know or get what the value is until the view is called, so calculate url inside it.
Django's regex matching method for urls allows one to define and assign variables:
(?P<variable_name>...) defines variable_name depending on the uri being called; so what you need to put is: param instead of <???>