Django include within single urls.py - django

I want to make an include in my urls.py referring to another urls in the same urls.py file.
My structure is as follows:
├── docs
├── requirements
├── scripts
└── sonata
├── person
│   ├── migrations
│   ├── templatetags
│   └── urls.py
├── registration
│   ├── migrations
│   └── urls.py
└── sonata
├── settings
└── urls.py
And I want every coming url with prefix 'pdf/' to add a value to kwargs and calling again the rest of url. This is my attempt:
urlpatterns = patterns('',
url(r'^$',TemplateView.as_view(template_name='registration/login.html')),
# This is my attempt for capturing the pdf prefix
# and calling this same file afterwards with the pdfOutput variable set to True
url(r'^pdf/', include('sonata.urls'), kwargs={'pdfOutput':True}),
url(r'^admin/', include(admin.site.urls)),
url(r'^person/', include('person.urls')),
url(r'^registration/', include('registration.urls')),
url(r'^menu/', registration_views.menu, name='menu'),
url(r'^customers/', person_views.customers, name='customers'),
url(r'^employees/', person_views.employees, name='employees'),
url(r'^alumns/', person_views.alumns, name='alumns'),
url(r'^teaching/', person_views.docencia, name='teaching'),
url(r'^i18n/', include('django.conf.urls.i18n')),
)
Is there any way of doing this? I looked at the docs. It seems pretty clear how to pass values, but after proving I can't make the include. (I don't want either to do include() with the [array] of patterns repeating all urls. This would break DRY principle).
Thanks in advance

The problem is that include immediately imports the included url configuration, resulting in a circular import error. You can do something like this, though:
sonata_patterns = [
url(r'^$',TemplateView.as_view(template_name='registration/login.html')),
url(r'^admin/', include(admin.site.urls)),
url(r'^person/', include('person.urls')),
url(r'^registration/', include('registration.urls')),
url(r'^menu/', registration_views.menu, name='menu'),
url(r'^customers/', person_views.customers, name='customers'),
url(r'^employees/', person_views.employees, name='employees'),
url(r'^alumns/', person_views.alumns, name='alumns'),
url(r'^teaching/', person_views.docencia, name='teaching'),
url(r'^i18n/', include('django.conf.urls.i18n')),
]
urlpatterns = [
url(r'^pdf/', include(sonata_patterns), kwargs={'pdfOutput':True})
] + sonata_patterns
Another possibility is to use middleware to capture the pdf prefix and set an attribute on the request. That way, you won't have to worry if all views accept your pdfOutput argument.

Related

How to include urls file from sub sub folder in django

i try to include urls from my Api folder
i tried path('api/', include("main.Apps.Api.apps.urls")) but it doesn't work
in my settings.py i add the app by INSTALLED_APPS += ["main.Apps.Api.apps.ApiConfig"]
and i changed the app name in Api.apps.py to name = 'MikeWebsite.Apps.Api' Everything works
But include the urls return me
ModuleNotFoundError: No module named 'MikeWebsite.Apps.Api.apps.urls'; 'MikeWebsite.Apps.Api.apps' is not a package
my project file tree look like this
main
└───_main
├── __init__.py
├── settings.py
├── urls.py
├── wsgi.py
└──_Apps
├──_Api
| └── urls.py
└── ...
What I'm doing is wrong?
And if you have a good source of information on how to work with apps nested in Django

How to serve `Docs` folder in Django which contains static html files?

I have following code structure in Django.
├── docs
│   └── _build
│      ├── doctrees
│      └── html
│   └── index.html
│  
├── localcoinswap
├── scripts
├── _static
├── _templates
├── tests
└── manage.py
Here the docs folder contains static html files. i.e index.html
Here are some questions regarding to problem:
The docs folder's html should be served as url <domain>/docs/index.html in Django project. How to achieve this
It should be restricted to User's who have is_staff attribute True.
What urlpattern should I use and Which View is useful to serve those static files (Admin restricted)?
Thank you in advance!
Add the base directory for your docs in TEMPLATES setting in settings.py.
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, '_templates'), "add your base directory here"],
...
}
]
In your urls.py, serve the files using TemplateView. To further restrict the url to only the staff users, you can wrap the view in staff_member_required decorator.
from django.contrib.admin.views.decorators import staff_member_required
...
urlpatterns += [url(r'^docs/index\.html$', staff_member_required(TemplateView.as_view(template_name='index.html')), name="index"),]
Make sure the file names for your templates and doc templates don't clash, else the first one evaluated according to the DIR list will always be considered.

Django tutorial 1 not showing polls

I am taking a test Driven Development course for python (which is awesome) Obeythetestinggoat and so my Django needs work. So I'm taking the Djangoproject.com course and I get all the code entered and the server runs but the polls won't change.
The home page http://127.0.0.1:8000 shows
"It worked!
Congratulations on your first Django-powered page."
Which is great but it won't show the polls or the admin buttons and I've run out of ideas on how to redirect it but not sure the problem.
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
I'm rather proud that I figured out the server and other areas but I just don't know what I am missing to get the page to show the polls.
https://docs.djangoproject.com/en/1.10/intro/tutorial01/
Yes, all you need to do is go to http://127.0.0.1:8000/polls/ . Otherwise if you want put your default polls page on the home page like you intended to do in http://127.0.0.1:8000/
you could do this in your urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
hope it helps.
http://127.0.0.1:8000 is the main page of your preoject, but in the urls, you define (with regex) how to manage requests to http://127.0.0.1:8000/polls/ and http://127.0.0.1:8000/admin/. You should visit those URLs.
There's a urls.py at the wrong place made by the django-admin startproject mysite command.
.
├── db.sqlite3
├── manage.py
├── mysite
│   ├── asgi.py
│   .
│   .
│   │
│   ├── urls.py <-- right place
│   └── wsgi.py
├── polls
│   .
│   .
│   ├── urls.py
│   └── views.py
└── urls.py <-- wrong place
If you forget to remove it, and keep it, while creating the right one at the right place, it prevents the rules of the right one to be applied.

Django REST Framework: How to add prefix in URL for versioning

I am trying to create version for REST application. Here is my URL Examle
www.myapi.com/foo [default version]
www.myapi.com/v1/foo [version one]
This is the project structure
├── __init__.py
├── settings.py
├── urls.py
├── default_app
│ ├── __init__.py
│ ├── serializer.py
│ ├── models.py
│ ├── views.py
│ ├── urls.py
│
└── v1_app
├── __init__.py
├── serializer.py
├── models.py
├── views.py
├── urls.py
default_app urls.py
from django.conf.urls import *
from default_app import views as df_views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'foo', df_views.viewname, "foo")
urlpatterns = router.urls
v1_app urls.py
from django.conf.urls import *
from v1_app import views as ver_views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'foo', ver_views.viewname, "foo")
urlpatterns = router.urls
main file for urls.py
from django.conf.urls import patterns, include, url
from defualt_app import urls as default_urls
from v1_app import urls as v1_urls
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += patterns('',
url(r'^', include(default_urls, namespace="default")),
url(r'^v1/', include(v1_urls, namespace="v1"))
)
urlpatterns += staticfiles_urlpatterns()
My issue is, when i using simple url without any prefix then it is working
www.myapi.com/foo
and when i used version prefix v1 or v2 then it throws error [Page not found (404)]
www.myapi.com/v1/foo
I got this idea from this link
https://stackoverflow.com/a/21839842/1558544
If I don't use middleware class then is this possible to get same result?
Thank you
Django REST Framework does not support url namespaces well, but there are solutions to making them work for most cases.
In the case of serializers, you must define all fields that are hyperlinked with a HyperlinkedRelatedField, including the url field that is automatically added, which is a HyperlinkedIdentityField. This includes setting the view_name argument on all of the fields to the correct, automatically generated view name. This should be something like [namespace]:[base_name]-detail.
But this also means you cannot use the DefaultRouter index page that is generated by the DefaultRouter, as it does not handle namespaces at all. In order to get one, you are going to need to either create your own, or override the automatically generated view in the router.

django not displaying image

I started with a django app and tried displaying an image in the home page. But the image is not getting displayed.
My settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR,"media")
MEDIA_URL = "/media/"
My urls.py:
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'myapp.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'',include('users.urls')),
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My home.html:
<html>
<head>
<title>MY SITE</title>
</head>
<body>
<img src="/media/image/myimage.jpg" alt="my image"/>
Welcome to my site
</body>
</html>
I get the text my image displayed instead of the image
ok, so I set up a simple 'paired-down' working example of this so no moving pieces were missing. Some Notes:
I used django 1.6
If you want to use a 'scale-able' delivery of static images you will want to follow
the django-1.6 staticfiles documentation which is what this example provides.
This means that you need to hack-n-slash your MEDIA references. ( MEDIA is really meant for file upload's) and you dont need to fool with the staticfiles_urlpatterns in your urls.py file. As you get this behavior out-of-the box when you add 'django.contrib.staticfiles' to your settings.py
Overview: Here is what your file tree-layout will look like in django 1.6, and the file structure that I am referencing in this answer.
├── djproj
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
├── manage.py
└─── myapp
   ├── admin.py
   ├── __init__.py
   ├── models.py
   ├── static
   │   └── myapp
   │   └── myimage.jpg
   ├── templates
   │   └── index.html
   ├── tests.py
   └── views.py
Step 1: Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
Step 2: In your settings file, define STATIC_URL, for example:
STATIC_URL = '/static/'
Step 3: change your home.html to look like this ( I used index.html in my example )
[ PROJECT_HOME/myapp/templates/index.html ]
<html>
<head>
<title>MY SITE</title>
</head>
<body>
{% load staticfiles %}
<img src="{% static "myapp/myimage.jpg" %}" alt="My image"/>
Welcome to my site
</body>
</html>
Make sure to read the django-1.6 staticfiles documentation related to STATICFILES_STORAGE so you understand what these template tags are buying you. Hint: python manage.py collectstatic
Step 4: ( you may have already done this, but I did not see it) Make sure that TEMPLETE_DIRS is defined in your settings.py and includes your home.html ( key here is that django's template engine needs to be serving this as we will be using some template tags)
[ PROJECT_HOME/djproj/settings.py ]
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
BASE_DIR + '../myapp/templates',
)
Step 5: build a view that renders your home.html page.
[ PROJECT_HOME/myapp/views.py ]
from django.shortcuts import render_to_response
def index( request ):
return render_to_response('index.html')
Since this is a bit convoluted, and there are several moving pieces here: here is a changeset that shows the complete 'changes'
You can of-coarse pull the entire github project if any of this is confusing.
django-staticfiles-setupexample
Final Note: STATIC files were not always handled this way in django. The MEDIA dir used to be the settings attr you were after. So this answer is for Django 1.6 ( staticfiles were added in django version 1.3)( the directory layout was changed in django 1.5).
You can ( as you were trying to do) hardwire your media dirs to the STATIC defines. Altho I do-not recommend this. Which is why I did not describe how to do it this way.
You are adding the media urls too late in the list. Django will try to match each urlpattern in succession, stopping when it gets to the first one. In this case, it matches on r'' and doesn't get to the static files or the media urls.
You may be able to put each pattern in the single call to patterns(), instead of using +=. That would be the cleanest, but I can't test it here. A sure-fire way to do it would be to pull the "users.urls" line out and add it later, like so:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += url(r'',include('users.urls'))
I'd recommend you set DEBUG = TEMPLATE_DEBUG = True and request the image URL directly.
You'll get Django debug output either showing that the URL can't be matched or the file path it's actually looking for.
The settings look generally correct although you've not shared BASE_DIR which is important in this case.
I had been struggling with the issue for like an entire day yesterday... I finally gave up and moved on creating my site without worrying about the images. Then today I decided to check the responsiveness of the site. I found out that my URLs were okay since I had strictly been following the documentation and best practices. The chrome console was saying:
Failed to load resource: net::ERR_BLOCKED_BY_CLIENT
The issue was with HTTP Referral Policy. Check them out. So after doing some research, this helped a lot, I found out that AdBlock was blocking my referred images. Apparently, my /media/ path was flagged in one of their regex patterns, deciding that my images were redirections to Ads. The ironic thing is that my website is about ads... so it must have heavily factored in, as my site has words like 'ad' in its url patterns. Long story short, I disabled AdBlock and my images now render. So I think it might be worth considering that even with best practices in your Django code, such an error could be caused by something with your browser!