URL with parameters does not find static files Django - django

I'm making a URL with parameters but it does not find the static files because it adds the name of the URL to the location of the static files, with normal urls this does not happen (I already have some pages working like this).
This is a url without parameters
This is a url with parameters
Look that add 'validador' to static file urls
This is the function:
def validador(request, id):
context = {}
context['browser_mobile'] = detect_browser_type(request.META['HTTP_USER_AGENT'])
context['id'] = id
return render(request, 'validador.html', context)
URLs file:
from django.urls import path
app_name='torredecontrol'
urlpatterns = [
path('', inicio, name='inicio'),
path('iniciativa', iniciativa, name='iniciativa'),
path('agregar_iniciativa', agregarIniciativa, name='add_iniciativa'),
path('validador/<int:id>', validador, name='validadores'),

Related

django use of quotes in url template tag

In myusers.urls I have set app_name = 'users' and name='users' in the urlpatterns.
Why are quotes needed around users:users in the following:
/users
is that a shortcut? Do the quotes tell django to resolve the address? Would the following work?
/users
urls.py
from django.urls import path
from . import views
app_name = 'users'
urlpatterns = [
path('', views.index, name='index'),
path('users/', views.users, name='users'),
]
views.py
from django.shortcuts import render
from myusers.models import *
# Create your views here.
def index(request):
return render(request, 'myusers/index.html')
def users(request):
users = AllUser.objects.all()
return render(request, 'myusers/users.html', {'users':users})
Unquoted arguments are template variables, not python variables, not module references, but only names with values provided to the template. This is the "context" passed to templates from views, where the key is the variable name. It can also be variables inside for loops and with constructs.
Quoted arguments are strings.
The URL tag uses its string arguments to resolve urls, by using Django's reverse and that's it. The string "users:users", refers to the URL namespace "users" and the view with name "users".

Django Rest Framework GET request with params

I'm trying to make a get request with params (srcFilename) in Django Rest Framework. I'm pretty confused about where to add the "req.query.srcFilename" (as it would be in javascript) in django. I read I have to add the complete url with the params in "<>" as shown in the code below, but it wont find the url.
views.py:
#api_view(['GET'])
def api_generate_signed_url(request, srcFilename):
print(f'srcFilename: {srcFilename}')
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(srcFilename)
if request.method == 'GET':
url = blob.generate_signed_url(
version="v4",
# This URL is valid for 15 minutes
expiration=datetime.timedelta(minutes=15),
# Allow GET requests using this URL.
method="GET",
)
print(f"Generated GET signed URL: {url}")
return Response(url)
urls.py:
from django.urls import include, path
from rest_framework import routers
from .views import api_generate_signed_url
router = routers.DefaultRouter()
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path(r'signedurl?srcFilename=<srcFilename>', api_generate_signed_url),
]
When trying this in Postman I get the following error:
The current path, signedurl, didn't match any of these.
Postman screenshot
You have to change your path as below...
path('signedurl', api_generate_signed_url),
No need to write ?srcFilename=<srcFilename>. Just remove it.
Then in your view access your request parameters through the QueryDict request.query_params.get('srcFilename').

Check(conditional) if the current url is the same with a url declared in path

In the main urls.py I have:
urlpatterns = [
path('items/', include('items.urls', namespace='items')),
....
]
In items urls.py I have:
urlpatterns = [
path('item/add/', ItemCreateView.as_view(), name='create_item'),
]
I want to check in a view/dispatch() if the current page url is the same with the one in the path, something like:
if self.request.path == 'items:create_items'
You can use reverse to convert the namespaced pattern name items:create to the URL.
from django.urls import reverse
if self.request.path == reverse('items:create_items'):
Depending on your server setup and whether you are concerned about the querystring, you may want to use request.path_info or request.get_full_path() instead of request.path.

Image in Django admin is generated with wrong URL

I'm trying out Django and ran into the following problem:
I have a model class Property which has various attributes amongst which is an image. The image property is defined as:
image = models.FileField(
upload_to = 'properties',
default = 'properties/house.jpeg')
The directory properties is a sub directory of images which is defined in settings.py as:
MEDIA_ROOT = '/Users/.../Development/pms/images/'
MEDIA_URL = 'http://localhost:8000/images/'
Derived from similar posts on SO regarding this topic, I added the following to my Property model:
def admin_image(self):
return '<img src="images/%s" width="100"/>' % self.image
admin_image.allow_tags = True
I then added admin_image() as a property to the list display:
list_display = ('admin_image', ...)
When I check the URL for the image in the admin application, I get the following:
http://127.0.0.1:8000/admin/properties/property/images/properties/house.jpeg/
This generates a 404 as the URL is generated incorrectly. Firstly the path is incorrect and secondly there's a trailing / at the end of the URL.
I'm obviously missing something... What do I do wrong?
EDIT:
Thanks to #okm for the various pointers. I did the following:
Added the following to my urls.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
... original url patterns ...
urlpatterns += staticfiles_urlpatterns()
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^images/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
Then in settings.py set MEDIA_ROOT:
absolute/filesystem/path/to/images
And in settings.py set MEDIA_URL:
/images/
According to the doc & here, try self.image.url instead of '...' % self.image

Django RequestContext and media doesnt work

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.