How to point django to put a template in the front page - python

I am trying to learn python in the django framework, I took a course, but it was based on an earlier version of django while I am using Django 2.1.3 and python 3.7.0, so I've got errors.My question is how can I point urls.py to take an html template and put it in the main page in this version of Django?
Thank you!!

You should point urls.py to views.py for your home page.
So your urlpatterns would look like, your main app:
urlpatterns = [
path(r'', include('page.urls'))
]
urls.py in page app:
urlpatterns = [
url('^$', views.page, name = 'index')]
And views.py like:
def page(request):
return render(request,"page.html")
There is tons of tutorials online. Have a look on Django documentation or YouTube . I also have blog with some info (I started learning recently too) https://adamw.eu

I assume Front page stands for Home page and that your site is called website. Then in urls.py of website/website (the directory that also contains the settings.py file), create a HomePage view
from django.views.generic import TemplateView
class HomePage(TemplateView):
template_name = 'index.html'
Then in urls.pyin the same folder, do something like:
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.HomePage.as_view(), name="home"),
]
You then need a templates folder at the root of your website, that is in website/templates and create website/templates/index.html which will be your homepage template.
In the website/website/settings.py file, make sure to set TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') and modify the TEMPLATES variable:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
... # rest of the code here
Reboot server, this should work fine.

Related

Django namespacing still produces collision

I have two apps using same names in my django project. After configuring namespacing, I still get collision. For example when I visit localhost:8000/nt/, I get template from the other app. (localhost:8000/se/ points to the right template).
I must have missed something. Here is the code:
dj_config/urls.py
urlpatterns = [
path("se/", include("simplevent.urls", namespace="se")),
path("nt/", include("nexttrain.urls", namespace="nt")),
# ...
]
dj_apps/simplevent/urls.py
from . import views
app_name = "simplevent"
urlpatterns = [
path(route="", view=views.Landing.as_view(), name="landing")
]
dj_apps/nexttrain/urls.py
from django.urls import path
from . import views
app_name = "nexttrain"
urlpatterns = [
path(route="", view=views.Landing.as_view(), name="landing"),
]
dj_config/settings.py
INSTALLED_APPS = [
"dj_apps.simplevent.apps.SimpleventConfig",
"dj_apps.nexttrain.apps.NexttrainConfig",
# ...
]
TEMPLATES = [
{
# ....
"DIRS": [],
"APP_DIRS": True,
}
Both views will have the same code:
class Landing(TemplateView):
template_name = "landing.html"
Templates are located in:
dj_apps/simplevent/templates/landing.html
dj_apps/nexttrain/templates/landing.html
Note that reversing order of apps in INSTALLED_APPS will reverse the problem (/se will point to nexttrain app).
The usual structure that your template backend expects when looking for template files is: <your app>/templates/<your app>/some_template.html, so your template paths should be:
dj_apps/simplevent/templates/simplevent/landing.html
dj_apps/nexttrain/templates/nexttrain/landing.html
Django does it like this because when collectstatic is run, it practically copies the files from templates folder of each app and places it in one static folder. This is why the app name needs to be twice in the path. Because in the final folder you end up with the app names already there. Also, you could have in your app overridden templates from third party apps (e.g. admin). It sounds a bit too convoluted for me too, but I'm pretty sure that is the intended way you're supposed to separate templates.
Also, in your view, you need to have the app name when specifying the template_name option:
# simplevent app
class Landing(TemplateView):
template_name = "simplevent/landing.html"
# nexttrain app
class Landing(TemplateView):
template_name = "nexttrain/landing.html"
PS. the same principle is applied to static folders.

Why is the Django template file not updating value from the context?

(I am a beginner in Django)
I am following along a tutorial in Django where we can dynamically pass some variable to a template file from associated function in views.py
When I am running the code for the first time, it works fine, but when I change the values within the context, the template does not update with the new values even when I refresh it
Here is my views.py code -
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
# return HttpResponse('<h1>Hey, welcome</h1>')
# we can dynamically send data to our index.html file as follows -
context={
'u_name': 'Ankit',
'u_age': 25,
'u_nationality': 'Indian',
}
return render(request,'index.html',context)
Here is my template index.html -
<h1>
How are you doing today {{u_name}} <br>You are {{u_age}} years old<br>Your nationality is {{u_nationality}}
</h1>
settings.py has been correctly set as well -
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR,'templates'],
Editing post to add urls.py as well (this is within the app)
from . import views
from django.urls import include,path
urlpatterns = [
path('',views.index,name='index')
]
And the urls.py in the main project -
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('MyApp.urls'))
]
Here is my output -
does not take the values from the context
Would be glad if someone could point out what error I am making. Thanks in advance

I'm getting 404 error on every page in django

I'm developing my first app in Django and facing some issues. The server runs smoothly and I can operate the admin panel without any issues.
However, all of the app pages including the default homepage show a "404 not found" error.
I have created a templates directory in project root
updated this line in settings.py for templates,
'DIRS': [os.path.join(BASE_DIR,'templates')],
View for the app
from django.shortcuts import render
from .models import *
# Create your views here.
def customers(request):
customers = Customer.objects.all()
return render(request, "customers.html", {'customers': customers})
urls for the app
from django.urls import path from . import views
urlpatterns = [path('customers',views.customers, name='customers')]
urls for the project
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static
urlpatterns = [
path('trips/',include('trips.urls')),
path('customers/',include('customers.urls')),
path('drivers/',include('drivers.urls')),
path('vehicles/',include('vehicles.urls')),
path('admin/', admin.site.urls), ]
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Help is appreciated
I can't see any problem with your case, you should be able to load http://localhost:8000/customers/customers. Maybe double customers was not you intention, then remove one of them (one in main urls.py one in app's).
Also when Django debug mode is active and you get a 404 because of URL mismatch, it shows you a list of URLs you have. To see it navigate to a non existing URL like http://localhost:8000/aaa. Then if you see customers/ there try http://localhost:8000/customers/. Go step by step to find the problem.

Getting error when I am trying to fetch my main url patterns

I am a beginner in Django I have created a Django project in that I have included two more application when I did add urls.py file in both Applications both are working well but when I am fetching my main admin URL it is giving an error
Page not found (404)
Request Method: GET
URL: http://127.0.0.1:8000/
the URLconf defined in mac.urls, Django tried these URL patterns, in this order:
admin/
shop/
blog/
The empty path didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to
False, and Django will display a standard 404 page.
when I am fetching this URL in http://127.0.0.1:8000/ i am getting an error it is working for http://127.0.0.1:8000/shop/
here is my main urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('shop/', include('shop.urls')),
path('blog/', include('blog.urls')),
]
Your django app has 3 routes:
http://127.0.0.1:8000/admin/ goes to django admin app
http://127.0.0.1:8000/shop/ goes to your shop app
http://127.0.0.1:8000/blog/ goes to your blog app
And since you have no configuration for http://127.0.0.1:8000, you see an error instead.
You can see that in the error, when django tries to match your url with list of available urls.
If you want to get admin app on url http://127.0.0.1:8000, change urls.py to:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', admin.site.urls),
path('shop/', include('shop.urls')),
path('blog/', include('blog.urls')),
]
It's generally not advisable to set admin app at root url - it has it's own system of urls inside (admin/<app_name>/<model_name>), so chances are it will shadow your urls and make the unreachable.
Create a view that will be your front page.
From there you should link to the other areas of your website.
Don't direct that to admin, that's ridiculous.
You've created a Django project and started two apps. You should have a project-level urls.py file and then an app-level urls.py file for each of your apps.
To explain that in greater detail lets say our Django project is called config and our two apps are called app1 and app2. Your project-level urls.py file, which will be located at config/urls.py, could contain the following:
# config/urls.py
from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('', TemplateView.as_view(template_name='home.html'),
name='home'),
path('app1/', include('app1.urls')),
path('app2/', include('app2.urls')),
]
In this file we specify a route for our admin panel, which on your local server will be located at http://127.0.0.1:8000/admin. We've also specified a home route, the second path with the empty string. This means when you navigate to http://127.0.0.1:8000/ you will be directed to your home page (for the example above I just used a generic built-in view). It's not a good idea to route immediately to your admin panel.
We've also included paths to our other two apps. What these two lines essentially say is: "include the urls from this other app". Now we need to create two urls.py files, one for each of our apps. In this example I'll just focus on the urls.py file for app1:
# app1/urls.py
from django.urls import path
from .views import AppContentView
urlpatterns = [
path('content/', AppContentView.as_view(),
name='app_content'),
]
This is a view that you would have to create, but what we've now done is we've created one path that will be located at http://127.0.0.1:8000/app1/content. In fact any new paths we create in this file will always begin with http://127.0.0.1:8000/app1/, because we've already told Django in our project-level urls.py to include the urls from the app1 urls.py file so we've essentially prefixed all of these paths with /app1/.
If you think of urls configurations like a tree it might help too:
Project Level Url Configs.
|
|
|
___________________________
| |
| |
App 1 Url Configs. App 2 Url Configs.

Django url not finding a template using CreateView in Class-Based Views

I have created a page where a user can add a new item (notes in this case) and I am making use of CBV which I have recently started learning.
This is my model form
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ('title', 'note', 'tags')
This is the view in views.py
class NoteCreate(CreateView):
model = Note
form_class = NoteForm
template_name = "add_note.html"
Then this is the url as I used in the urls.py of the app
from django.conf.urls import patterns, url
from . import views
from madNotes.views import NoteCreate, NoteIndex,
urlpatterns = patterns(
'',
url(r'^notes/add/$', NoteCreate.as_view(), name="new_note"),
url(r'^$', NoteIndex.as_view()),
url(r'^(?P<slug>\S+)/$', views.NoteDetail.as_view(), name="entry_detail"),
)
NB: I used the same url as the main page at 127.0.0.1:8000 in the projects urls.py file and it worked.
I have seen several tutorials and even the docs and can't seem to find what I am doing wrong. Will I also need to add a function in order for it to be saved in the db or the CBV will do it all?
EDit: The error I get is this
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/notes/add/
Here is the project's urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from MadNotez import settings
from registration.backends.default.views import RegistrationView
from madNotes.forms import ExRegistrationForm
if settings.DEBUG:
import debug_toolbar
urlpatterns = patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
url(r'accounts/register/$', RegistrationView.as_view(form_class = ExRegistrationForm), name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^admin/', include(admin.site.urls)),
url('^markdown/', include('django_markdown.urls')),
url('^notes/', include('madNotes.urls')),
#url(r'^$', views.NoteCreate.as_view(), name="new note"), when I used it here it worked
)
you say that is the urls.py of the app, which means it is included by the project's urls.py.
As you show now, all the app's URIs go under the notes prefix:
url('^notes/', include('madNotes.urls')),
so as things stand at present the correct URI for the page is
http://127.0.0.1:8000/notes/notes/add/
In order to clean things up a bit, I'd suggest to modify the app's urls.py to
url(r'^add/$', NoteCreate.as_view(), name="new_note"),
so that the page can be reached at
http://127.0.0.1:8000/notes/add/
This way all the app's pages/services are available under the notes prefix and with a simple name that is consistent with their action (i.e. add, delete, etc)

Categories

Resources