How to create href link from one Django app to another - django

I know this has been asked multiply times before, but I still don't get it.
How can I create a href-link in one Django app that sends the user to a 2nd app?
This is my setup:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
app1/
migrations/
templates/
app1/
app1.html
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
app2/
migrations/
templates/
app2/
app2.html
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls'), name='app1'),
path('app2/', include('app2.urls'), name='app2'),
]
myproject/settings.py
INSTALLED_APPS = [
'app1.apps.App1Config',
'app2.apps.App2Config',
'django.contrib.admin',
...
]
app1/urls.py (analogous for app2)
from django.urls import path
from . import views
urlpatterns = [
path('', views.app1, name='app1'),
]
app1/views.py (analogous for app2)
from django.template import loader
from django.http import HttpResponse
def app1(request):
template = loader.get_template('app1/app1.html')
return HttpResponse(template.render())
app1/templates/app1/app1.html (analogous for app2)
<p>This is the template of app1.</p>
Go to App2 # doesn't work
Go to App2 # doesn't work
Go to App2 # doesn't work
My problem is that this sends me to the address 127.0.0.1:8000/app1/app2/ which gives me a 404 error. However, I can access app2 via 127.0.0.1:8000/app2/ without a problem.
Edit:
Thanks everyone for your feedback. After going through your suggestions, I made the following changes:
myproject/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls', namespace='app1')), # ADDED NAMESPACE
path('app2/', include('app2.urls', namespace='app2')), # ADDED NAMESPACE
]
myproject/settings.py: no changes
app1/urls.py: (analogous for app2)
from django.urls import path
from . import views
app_name = 'app1' # THIS WAS MISSING
urlpatterns = [
path('', views.app1, name='app1'),
]
app1/views.py: no changes
app1/templates/app1/app1.html: (analogous for app2)
<p>This is the template of app1.</p>
Go to App2 # AS SUGGESTED BY seif
Now it works.

in your template and views try not to hardcode the url of href instead use the {%url ''%}
which will be {%url 'namespace:urlname'%}
<p>This is the template of app1.</p>
Go to App2
this give you flexibility to change the path in your urls and not to worry about changing it at all your templates and views you can read more here https://docs.djangoproject.com/en/3.1/topics/http/urls/#reverse-resolution-of-urls

your href link doesn't go to the .html file in templates, templates are just for UI, and barely have a say in how you project gets routed, infact it depends on you to configure. instead it should go to the url specified in your url file,
so say your bases url is
path('app1/', include('app1.urls'), name='app1')
for one of your app it will be
App 1
if you have other links under app1 url file, it will then be
A link under App 1
example.com here, could be localhost:8000 or just localhost with any port, depending on the port your django project runs one.
then as for this,
from django.template import loader
from django.http import HttpResponse
def app1(request):
template = loader.get_template('app1/app1.html')
return HttpResponse(template.render())
I will suggest you do something like this instead
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest
def app1(request,slug=None):
return render(request,'app1/app1.html',{})
#path to the template folder, under templates, depends on your configuration though
Kindly read more on templates configuration and routing in Django,but this should give a jumpstart.
Cheers

When you input "127.0.0.1:8000/app1/app2/", django will recieve "app1/app2/" and work like below(not accurate):
1.compare app1/ to every element in urlpatterns of myproject/urls.py
so, app1/ will be found.
2.compare app2/ to every element in urlpatterns of app1.urls
there's nothing will be found, because there is only a "" in urlpatterns of app1.urls.
so you get a 404 page.
if you input "127.0.0.1:8000/app2/", in step 2, "" equals to "",
fuction views.app2 executes, and you get a correct page.
I suggest you read the django's tutorials in official site.
https://docs.djangoproject.com/en/3.1/intro/tutorial01/

Related

Rendering new custom html templates in existing Django project

I'm not a Django expert but I need to make customizations of this software which is written in Django using the rest framework.
I need to render a custom html template let's say a.html, however when I go to http://localhost:8080/custom/custom/a I get redirected back to different page - not a.html.
This is what I've done so far. I created a new folder in apps called custom:
cvat
apps
custom
templates
custom
_init.py
a.html, b.html, ...
urls.py
apps.py
from django.apps import AppConfig
class CustomConfig(AppConfig):
name = 'cvat.apps.custom'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('custom/<str:name>', views.CustomView),
]
views.py
from django.shortcuts import render
def CustomView(request, name):
return render(request, 'custom/'+name+'.html')
In addition, I have modified these existing files to add the custom folder that was created in apps:
in urls.py added my url patterns:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('cvat.apps.engine.urls')),
path('django-rq/', include('django_rq.urls')),
path('custom/', include('cvat.apps.custom.urls')),
]
in base.py added this:
INSTALLED_APPS = [
...
'cvat.apps.custom'
]
Any advice on what I'm doing wrong?
You can try something like this
url can be like this
urlpatterns = [
path('custom/<name>/', views.CustomView),
]
and your view should be like this.
def CustomView(request, name):
return render(request, f'custom/{name}.html')
Hope this will help you.

Routing does not work in Django: page not found (GET)

I've tried multiple methods of writing views but I don't think it is a problem here. App is installed in settings.py
It displays error every time.
project structure:
structure
views.py (app folder)
from django.http import HttpResponse
from django.shortcuts import render
def home_view(request):
return HttpResponse('Hello World')
url.py in apps folder
from django.urls import path
from . import views
urlpatterns = [
path('home_view/', views.home_view)
]
apps.py in app folder
from django.apps import AppConfig
class AppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'app'
urls.py in store folder
from django.contrib import admin
from django.urls import path, include
from app import views
urlpatterns = [
path('app/home_view/', include('app.url')),
path('admin/', admin.site.urls),
]
error message:
error
As a django web development expert I saw some small corrections to be done:
In store urls.py file its app/ and app.urls
from django.contrib import admin
from django.urls import path, include
from app import views
urlpatterns = [
path('app/', include('app.urls')),
path('admin/', admin.site.urls),
]
Then change the app url.py file name to standard name urls.py.
also don't forget to add your app to installed_apps variable in settings.py file:
INSTALLED_APPS=[
'app',
'django.contin.auth',
#and other already specified apps
]
Rest all files have no bugs!!
According to this the correct path for HttpResponse is:
http://localhost:8000/app/home_view/
OR
http://127.0.0.1:8000/app/home_view/
In your urls.py file
Change
path('app/home_view/', include('app.url')),
To
path('', include('app.url')),
Then
On your browser go to:
127.0.0.1:8000/home_view/
The main thing it must be app.urls not app.url. change your file to url.py to urls.py, its recommended.
If you have defined path('app/home_view/', include('app.urls')) in urls.py of your store folder, then it goes to your urls.py which is in app.
In your app's urls.py you have written path('home_view/',views.home_view).
It means if you type 127.0.0.1:8000/app/home_view/home_view/ then it will render your HttpResponse that is Hello world.

module 'guestbook.views' has no attribute 'index'

i make a startapp "guestbook" inside my django project.
here is the file list(guestbook)
__init__.py admin.py apps.py migrations models.py template tests.py urls.py views.py
guestbook/template
guestbook
guestbook/template/guestbook
index.html
i want to get the index render but i am facing error which is
File "C:\Users\_monster\Desktop\skill\django_frontend\backend\f_django\guestbook\urls.py", line 7, in <module>
path('', views.index, name='index')
AttributeError: module 'guestbook.views' has no attribute 'index'
here is my file setting
main urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
# main url, folder url
path('admin/', admin.site.urls),
path('hello/', include('hello.urls')),
path('guestbook/', include('guestbook.urls'))
]
guestbook/urls.py
from django.urls import path
# import everything from views
from . import views
urlpatterns = [
path('', views.index, name='index')
]
guestbook/views.py
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'guestbook/index.html')
so what is problem here ? the index.html are inside the folder
I had the same error. I Tried almost everything to solve the issue but couldnt.
I just changed the name of function index from views.py to index2(guestbook/views.py)in your case!! Then i replicated those changes to (guestbook/urls.py) as
urlpatterns = [
path('', views.index2, name='index')
]
It happened miraculously. And the console showed no errors anymore!! When i switched back again to whatever previously was, (that is to index from from index2) everything was running correctly

Custom admin interface in Django

Django's documentation provides an easy way of installing admin app.
It assumes the structure of files as follows:
mysite/
manage.py
mysite/
settings.py #adding `admin` under `INSTALLED_APPS`
__init__.py
urls.py #adding urls
wsgi.py
myapp/
__init__.py
admin.py #creating this file
models.py
views.py
My question is how to get the admin interface to work if my structure is as follows:
mysite/
manage.py
settings.py
__init__.py
urls.py
myapp/
__init__.py
forms.py
models.py
views.py
What will be the various changes that I will have to incorporate to get the admin interface working. [my other apps are working].
I have read and read the documentation several times.
I'm using Django 1.4.
EDIT#1
I'm getting this error on running localhost:8000/admin/:
error at /admin/
unknown specifier: ?P[
Whole error here.
My urls.py file has the lines [as in the docs]:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/(.*)', include(admin.site.urls)),
)
My admin.py file in the myapp folder has the code:
import models
from django.contrib import admin
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
admin.site.register(models.Article, PostAdmin)
This is how you're supposed to include the admin urls:
url(r'^admin/', include(admin.site.urls)),
The documentation shows this.
The error that you're getting is coming straight from the re python module, complaining about this part of a url:
?P[
The URLs you've posted in your comment beneath show this:
url(r'^(?P[-a-zA-Z0-9]+)/?$', 'myapp.views.getPost')
Try changing that url by giving the match group a name:
url(r'^(?P<slug>[-a-zA-Z0-9]+)/?$', 'myapp.views.getPost')
And in your getPost view, include a slug argument.

Django App URL model not importing

Im certain that this is something simply that Im overlooking but Im too irritated to figure it out alone so thanks in advance.
Project Directory Structure
*UPDATED*
myproject/
manage.py
myproject/
apps/
geo/
urls.py
settings.py
urls.py
urls.py
from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.gis import admin
admin.autodiscover()
from pinax.apps.account.openid_consumer import PinaxConsumer
handler500 = "pinax.views.server_error"
urlpatterns = patterns("",
url(r"^$", direct_to_template, {'template' : 'home.html' }, name="home"),
url(r"^admin/invite_user/$", "pinax.apps.signup_codes.views.admin_invite_user", name="admin_invite_user"),
url(r"^admin/", include(admin.site.urls)),
url(r"^about/", include("apps.about.urls")),
url(r"^account/", include("pinax.apps.account.urls")),
url(r"^openid/", include(PinaxConsumer().urls)),
url(r"^profiles/", include("idios.urls")),
url(r"^notices/", include("notification.urls")),
url(r"^announcements/", include("announcements.urls")),
url(r"^products/", include("products.urls")),
url(r"^locate/", include("geo.urls")),
url(r"^sectors/", include("sectors.urls")),
)
if settings.SERVE_MEDIA:
urlpatterns += patterns("",
url(r"", include("staticfiles.urls")),
)
settings.py
INSTALLED_APPS = [
# project
"tulsa-site.apps.about",
"tulsa-site.apps.profiles",
"tulsa-site.apps.geo",
"tulsa-site.apps.sectors",
]
When I go to the url path "http://127.0.0.1:8000/locate/" is receive the error message: I recieve the exception value "No module named geo.urls." What am I missing?
include("geo.urls") tells Django to look for geo.urls relative to the manage.py file. So its essentially looking for this file:
myproject/
manage.py
myproject/
apps/
settings.py
urls.py
geo/
urls.py <- this file
That is sort of the new directory structure starting with Django 1.4 which encourages to have apps independent of the Django project. However if you still follow the old layout where the apps folders are within the project folder, then you have to change your imports to reflect that:
include("myproject.geo.urls")
EDIT
Following your updated layout:
include("myproject.apps.geo.urls")
url(r"^locate/", include("tulsa-site.apps.geo.urls"))