i have just begun learning Django, and i stick with the principle that the fastest and best way to learn is through practice. I'm on the process of building my first web app, and i would really appreciate your help on the following :
I'm working on getting the front end to show up. But i'm having a hard time understanding the way the URLS work.
I have the following directory :
/myApp
/myApp
/public
/templates
/account
login.html
base.html
settings.py
urls.py
...
/account
urls.py
views.py
I have this on my myApp(the main app) 'urls.py' file
urlpatterns = patterns('',
...
url(r'^$', include(account.urls), name='account'),
)
And inside my account urls.py file, i already have the ff :
...
urlpatterns = patterns(
'account.views',
url(r'^$', 'login_user', name='login'),
)
I already defined following on the account views.py file :
def login_user(request):
return render(request, 'account/login.html')
So i guess the request should render my login.html file.
But i get the error that,
NameError at /
name 'account' is not defined
Therefore, i've figured that there must be something wrong with my settings.py file, right?
So here it is if it serves some purpose (just the important stuffs) :
...
BASE_DIR = os.path.join(os.path.dirname(__file__), '.')
...
ROOT_URLCONF = 'myApp.urls'
WSGI_APPLICATION = 'myApp.wsgi.application'
TEMPLATE_DIRS = [
os.path.join(BASE_DIR,'templates'),
]
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = "/static/"
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'public'),
]
Right now, i really need to at least get the front end working. I hope the details i gave you gives you an idea of how i am organizing my file right now.
Additional note : I want to just create one template directory for the whole app. And as you can see on the structure, the template folder is inside the main app. How do i configure it inside the settings such that the apps use the main template folder?
You should put the account.urls in quotes. Also remove the $ sign from the regex:
url(r'^', include('account.urls')),
And in the account/urls.py file you should correct the base module name from oauth to the acount (your view is account.views.login_user, not the oauth.views.login_user):
urlpatterns = patterns('account.views',
....
)
Related
This question is the sequel of my previous question -
Reverse for 'hobbieswithCSS.html' not found. 'hobbieswithCSS.html' is not a valid view function or pattern name (solved)
I have moved from one error (in the title of previous question) to another, (in the title of this question) but hopefully this one will not be that much difficult to solve.
I have this anchor tag on my homepage -
My Hobbies
I have this view in my views.py file -
def hobbieswithCSS(request):
return render(request,'hobbieswithCSS.html')
And these are my urlpatterns -
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^basic_app/',include('basic_app.urls')),
url(r'^logout/$',views.user_logout,name='logout'),
url(r'^hobbies/$', views.hobbieswithCSS, name='hobbieswithCSS'),
]
these will solve it for sure.
1.if your saved your templates in a separate templates by app name in templates directory you have to put the name of the sub-folder before the name of the template like this hobbies/hobbieswithCSS.html .
2. set the root of the template directory in your settings.py for project and templates.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, 'templates'),
)
also check this out Django TemplateDoesNotExist?
Change your views.py like this:
def hobbieswithCSS(request):
return render(request,'basic_app/hobbieswithCSS.html')
I've got the hang of constructing rest API's to pass all data, but I'm having trouble knowing how to set up the folder structure to be able to load an angular template by visiting an URL.
Lets say that in my settings.py I have a registered path api, that contains the JSON data i want to pass to the client, and have some angtemplate.html. I also have a Django app called apitest which gets data from the server and provides the data to the api that angular needs to get data from.
How do I route the request so that when a user goes to a url on my server like 127.0.0.1:8000/apifetch, the user is presentet with angtemplate.html that has loaded the data from /apifetch?
I realize this is a triple question involving first angular app-structure, second Django template syntax and folder structure, and thirdly url-patterns.
I tried to follow the thinkster angular django tutorial, but was unable to connect the angular app to the website.
My own theory is that inside the apitest Django application I create a few templates and in the static folder of that app I keep my angular apps, which I load as static into the template, and connect the url as I would usually do.
However I've heard that you shouldn't mix Django and angular templates, which that would be doing.
Broad answers are much appreciated, most of all just an example folder structure with the urls that make it work would be incredibly valuable, so that I can start experimenting with my self from a somewhat working base. I've been banging my head against the wall for some time with this.
TLDR: Use a separate path like /api/* for backend API, redirect every other route to index.html for Angular app.
I've been working with Django v1.10 + AngularJS (after which migrated to Angular).
I'm using Angular/AngularJS for all front end works and only use the back end mostly to get data via API.
I've been using this folder structure:
dist (this is where I put the generated Angular bundle)
index.html
django_app
settings.py
urls.py
wsgi.py
...
app
static (django static files)
apps.py
models.py
urls.py
views.py
...
src (Angular source code, you could move all Angular related files into a separate folder if you want to keep things clean in the root folder, i.e., angular/src)
angular.json
tsconfig.json
...
During development, I would redirect all routes to index.html for the Angular app.
In django_app\urls.py:
urlpatterns = [
url(r'^api/', include('app.urls')),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^admin/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^admin/reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
url(r'^admin/', admin.site.urls, name='admin'),
]
# Serve media files locally for development
if settings.DEBUG:
import debug_toolbar
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
url(r'^.*$', staticfilesviews.serve, {'path': 'index.html'}, name='index'),
]
These are my settings:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'dist'),
)
In production, you should use a reverse proxy like nginx to route only Django for specific uses, e.g., calling API. Everything else should be passed to the Angular app entry index.html
I am trying to create my own thumbnails within the Django admin and I believe they are being properly pointed to. However I cannot view the thumbnail. This is what I see:
When I click on the thumbnail, I get redirected to this URL and all I see is an empty white page.
http://localhost:8000/media/media/Screen_Shot_2016-04-08_at_12.55.25_PM.png
It is the correct URL but I do not see anything within the page.
Here is what code I have:
Within my settings.py
All files will go to cherngloong/uploads and /media/ will be the public front facing representation of the MEDIA_ROOT
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/media/'
Within cherngloong/cherngloong/urls.py I appended to the list to serve static files:
urlpatterns = [
url(r'^admin', include(admin.site.urls)),
url(r'', TemplateView.as_view(template_name="index.html"), name="index"),
url(r'^api/', include('api.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My cherngloong/api/urls.py:
urlpatterns = [
url(r'ig$', most_recent)
]
cherngloon/api/models.py:
class Media(models.Model):
...
...
file = models.FileField(upload_to="media/", default=None)
cherngloong/api/admin.py:
class MediaAdmin(admin.ModelAdmin):
search_fields = ["name", "file"]
list_display = ("name", "media_type", "url", "album", "display", "thumbnail")
def display(self, media_obj):
return '%s' % (media_obj.file.url, media_obj.file.name)
def thumbnail(self, media_obj):
location = media_obj.file.url
thumbnail_html = "<img border=\"0\" alt=\"\" src=\"{1}\" height=\"80\" />".format(location, location)
return thumbnail_html
thumbnail.allow_tags = True
display.allow_tags = True
Project structure:
I can't see any inconsistency on the code you have. I just created a project on GitHub with the same structure, and code you posted here, and everything worked like a charm, you can test it yourself, see the code here: https://github.com/vladir/cherngloong. I used the last version of Django, I know you are using a version below Django 1.9 because you are still using allow_tags, but even so your code seems good for me. Perhaps my code can help you to find what is happening.
I found why it is happening. Remove this line:
url(r'', TemplateView.as_view(template_name="index.html"), name="index"),
from your cherngloong/cherngloong/urls.py, and it will render ok.
It seems as this URL is too open, and it interferes with the thumbnails URL.
It could work for you instead:
url(r'^$', TemplateView.as_view(template_name="index.html"), name="index"),
I updated my code on the repo, so that you can test that it is working.
please tell me how to move the view (view.py) in the directory "views".
Now the structure of my folders and files is as follows:
proj1(catalog)
views.py(file)
manage.py(file)
proj1(catalog)
wsgi.py(file)
urls.py(file)
settings.py(file)
__init__.py(file)
views(catalog)
urls.py following content:
from django.conf.urls import patterns, include, url
import views
urlpatterns = patterns('',
url('^$', views.hello),
url('^datetime$', views.current_datetime),
url('^dt$', views.current_datetime),
url('^dt/(\d{0,2})$', views.current_datetime2),
)
I need to file located in the directory view.py proj1/proj1 /.
wherein static pages is still made available to the browser.
the problem is that I do not know how to change the code in the files: urls.py, settings.py
There is no need to change views, just do in settings.py
TEMPLATE_DIRS = (
'/path/to/proj1/proj1/views/', # or another path with templates
'django/contrib/admin/templates/'
)
I am having trouble with some custom admin pages triggering the Django admin site instead of displaying my custom pages.
My urls.py follows:
urlpatterns = patterns('',
# ... trimmed ...
# Admin pages
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
# Lobby Visitor Log
url(r'^visitorLog', include('lobbyVisitorLog.urls')),
)
In my lobbyVisitorLog app I have the following directory structure, leading to "admin" pages
lobbyVisitorLog
- templates
- admin
And my lobbyVisitorLog/urls.py follows:
urlpatterns = patterns('visitorLog.views',
url(r'^/$', views.home, name='homeView'),
url(r'^/search', views.search, name='searchView'),
url(r'^/submit', views.submit, name='submitView'),
url(r'^/admin/$', views.adminView, name='adminView'),
url(r'^/admin/import/$', views.adminImportView, name='adminImportView'),
url(r'^/(?P<guest_type>\w+)$', views.logEntry, name='logEntryView'),
)
The views.py for the admin index page looks like this:
def adminView(request):
return render(request, 'admin/index.html', {}, context_instance=RequestContext(request))
When I go to "mysite/visitorLog/admin/" I get the Django admin site with the following message: “You don't have permission to edit anything.”
However, if I change my "admin" directory to "utils" (or whatever else, other then "admin") and update my views.py accordingly, everything appears as expected! This is okay, I can deal with my directory being called "utils" but it will annoy me... just enough.
What is happening that is causing the Django admin page to load instead of my custom pages?
By default django first checks each of the paths you have in TEMPLATE_DIRS for 'admin/index.html'. If it doesn't find it there, it starts searching in the templates directory for each app in the INSTALLED_APPS setting.
If 'django.contrib.admin' is listed first in INSTALLED_APPS, it will use the identically named 'admin/index.html' template from the django.contrib.admin app.
Moving 'django.contrib.admin' to the last position in INSTALLED_APPS should allow it to find 'admin/index.html' in your lobbyVisitorLog app first, but this will break the admin site by cause it to use 'admin/index.html' from your app, lobbyVisitorLog.
A good way to solve this is to always have a sub-directory named after your app within your app's templates directory. For example:
lobbyVisitorLog
- templates
- lobbyVisitorLog
- admin
- index.html
and then update your view's template path:
def adminView(request):
return render(request, 'lobbyVisitorLog/admin/index.html', {}, context_instance=RequestContext(request))
You can find more on how Django loads templates here