How do create url to django Admin within my user page (HTML) - django

I'm new to coding, I'm trying to create URL link in NavBar to redirect my Django Admin exmple:
<a class="nav-link" href="{% url 'admin'%}"> Admin site </a>
However, Django do find; No-Reverse-Match,
It works for other URL links
Things I had to try:
Is adding a name in project URL
including URL path in my App URL
My project URL code:
from Django.contrib import admin
from django.urls import path, include
urlpatterns = [
path(r'admin/', admin.site.urls, name='admin' ),
path(r'accounts/', include('django.contrib.auth.urls')),
path(r'api-auth/', include('rest_framework.urls'), name='rest_framework'),
path(r'', include('app.urls')),
My App URL code:
from django.urls import path, include
from . import views #function views
from django.contrib.auth.decorators import login_required, permission_required
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'tank', views.TankViewSet)
router.register(r'room', views.RoomViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path(r'',login_required(views.index), name='index'),
path (r'test/',views.Test),
path(r'^Water/',login_required(views.Lquid), name='tank'),
path(r'^Ambient/',login_required(views.Ambient), name='room'),
path(r'Rest-api/', include(router.urls)),
#path(r'admin/', admin.site.urls, name='admin' ), this somthing I had try
]
Basically, Django makes in a way that works and redirect to the URL link on any page
NAVBAR:
Admin site
App URL:
path(r'',login_required(views.index), name='index'),
With this two link it will redricet to the page you set.
Apprentice if you cold help

You need to specify the admin page you want to redirect to when doing a reverse lookup of admin. To get to the admin homepage you will want this reverse lookup
reverse('admin:index')
So to link to the admin homepage in your nav bar, it should look like this
<a class="nav-link" href="{% url 'admin:index' %}"> Admin site </a>
Check out the docs on how to reverse lookup admin pages

Related

How to redirect from a view in one app to a view in another?

I am trying to build a job-board type of website. Right now I have user authentication (login, logout, register, password change, etc) in one app (account) and the job model and all other views/templates in another app(job).
To have the user log in, I used the views found in django.contrib.auth(this is account/urls.py):
from django.urls import path
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name = 'login'),
]
In the job app I have created a urls.py file:
from django.urls import path
from . import views
urlpatterns = [
path('dashboard/', views.dashboard, name = 'dashboard'),
]
Upon logging in, I would like the user to be redirected to this dashboard URL/view found in the job app. How can I do this? I know that if I just put the dashboard view/url into the account app all I would need to do is add this to settings.py:
LOGIN_REDIRECT_URL = 'dashboard'
But, how can I redirect to a view in another app?
Final note: I separated this into two apps in the first place because I've read that is good practice, but am not sure if it's needed here.
Test this:
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
in settings.py:
LOGIN_REDIRECT_URL = reverse_lazy('job:dashboard')
This only works for redirection once logged in.
[settings.py]:
LOGIN_REDIRECT_URL = 'dashboard'
If you want to redirect urls from any app to another, you must use static tags.
[file.html]
{% load static %}
and then:
<a href="{% url 'dashboard' %}">

Multiple auth login pages in Django

I have multiple apps in one django project
/user
/manager
/business`
Each needs a separate set of login and registration. How do I use django.contrib.auth to satisfy this?
I have urlpatterns in main are:
urlpatterns = [
path('admin/', admin.site.urls),
path('user/', include('user.urls')),
path('user/', include('django.contrib.auth.urls')),
path('manager/', include('manager.urls')),
path('manager/', include('django.contrib.auth.urls')),
path('business/', include('business.urls')),
path('business/', include('django.contrib.auth.urls')),
Urlpatterns in the apps are like those:
urlpatterns = [
path('index', views.index, name='index'),
path('register', views.register, name='register'),
]
and I have different views for login and register, also have different templates in each app: /templates/register/register.html and /templates/register/login.html
However, login and register views seem to be shared between apps. Is there a way to separate them with ease?
First of all I would suggest you make use namespaces in your urls so you don't get any conflicts with the names in your urls. So add app_name to the urls.py of your apps, e.g.
#user urls.py
app_name='user'
urlpatterns = [
...
Then something like {% url 'user:register' %} will point to register view of your user app, {% url 'manager:register' %} will point to the register view of your manager app and so on.
If you have defined individual login views for each app the same goes for these views too, providing you have imported the correct views in you apps urls.py.
As you are also including the django.contrib.auth.urls in each of your apps there is of course a second 'login/' path coming from the default path in the auth.urls. However, as far as I know the resolution of urls is done top down by django, so if you keep the order of urls as in your post your custom 'login/' will be hit first and used. So no problem with that.
Where I see a problem is with your templates. If I understand it correctly all are located in a templates/register/ folder in your apps. The django template loader does not differentiate between a register.html template in your user app and a register.html template in your manager app. So it is likely that you do not get the correct template. What I would suggest is moving the templates to an app specific subfolder, e.g. /templates/user/register. Then you can fetch the correct templates in your views (e.g. 'user/register.html').
I understand that you have individual app specific views. Of course you can always subclass the views django provides and adapt them to your needs. For instance by overriding the form_valid() method of the LoginView. This SO post provides an example.
If on the other hand you want to use the default django login view just with a custom template you can pass the template as a kwarg to your view. E.g.:
# user urls.py
from django.urls import path
from django.contrib.auth.views import LoginView
app_name='user'
urlpatterns = [
path('login/', LoginView.as_view(template_name='user/login.html'), name='login'),
# more patterns
]
If you want to redirect to some custom site after successful login you can add an input called 'next' to your login form containing the url to where to redirect, e.g.
<!-- user/login.html -->
<form action="{% url 'user:login' %}" method="POST">
{% csrf_token %}
{{ form }}
<input type="hidden" name="next" value="/user/index/">
<button type="submit">Login</button>
</form>
In your apps you will propably be using the user_passes_test decorator or something similar to check whether the user is allowed to access the view in that app.

How to extend django.contrib.auth views?

How I've Arranged Templates : I have placed my login.html in /templates/registration folder of Django. So, the Django takes necessary care of accounts/login ,accounts/logout url requests and renders as per request. And I haven't to code for the individual login and logout functions.
What I am trying to Achieve : I want to authenticate users at login request, when they requests the login page:
If user is anonymous user, I want to render the normal login page.
However, If the user is authenticated thats already logged in. I want to display an error and not the logged page.
I want to achieve this in the views.py and urls.py and not in the templates by:
{% if user.is_authenticated %}
{% if user.is_anonymous %}
Urls.py
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
urlpatterns=[
url(r'^register/$', views.register, name='register'),
url(r'^logout/$', auth_views.logout, {'next_page' : 'Homepage'}, name='logout'),
]
You can wrap the view with your own, which either redirects or calls the original.
def wrapped_login(request):
if request.user.is_authenticated:
return redirect('whatever')
else:
return auth_views.login(request)
Provide LOGIN_REDIRECT_URL = '/' in settings.py. Then use the following url for login page:
urlpatterns = [
url(r'^login/',
auth_views.LoginView.as_view(redirect_authenticated_user=True),
name='login'),
]
This will redirect your user to the URL provided in settings file if they try to login even after being authenticated.

how to design Django url pattern to avoid 301

I have a project called blog, the url pattern shows below. I want to make the app "posts" to route all the traffic.
Url patterns of them shows below:
#blog/urls.py
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('posts.url', namespace='posts')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#posts/url.py
from django.conf.urls import url
from django.contrib import admin
from .views import (
home,
down,
get_data_by_post,
)
urlpatterns = [
url(r'^$', home, name='down'),
url(r'^api/$', ins_down, name='api'),
url(r'^p/(?P<slug>[-\w]+)/$', get_data_by_post, name='slug'),
]
When enter into home page, the home function in posts.views will generate some links with local data to render index.html.
def home(request):
final = get_local_suggest()
return render(request, "index.html", final)
Some of the code in index.html template likes below:
<a href="p/{{ results.code }}?From=homepage" class="portfolio-link" target="_blank">
So in home page , some links will show there: "http://example.com/p/code?From=homepage
But the tricky question here is that: when I click the url , the console of Django will print 301 like below. In browser, it will redirect from "/p/code" to "/p/code?From=homepage".
Not Found: /p/code [17/Apr/2017 15:05:23] "GET
/p/code?From=homepage HTTP/1.1" 301 0
There are must be something wrong with url pattern design, how to avoid it happened again?
Thanks!
Your url pattern ends with a slash, so your url should as well.
To make sure you always point your urls to the canonical url and avoid redirects, use the {% url %} template tag:
<a href="{% url 'posts:slug' results.code %}?From=homepage" class="portfolio-link" target="_blank">
Here 'slug' is the name of your url, and results.code is an argument to the url.
You can use request.GET.get('From', '') in your views, and clean your url pattern.

How can I fix my Wagtail URL namespace and explorer when adding wagtail to a current project?

My issue is my URL is coming up mysite.com/test-news-1/ instead of mysite.com/news/test-news-1/
I've started a new project using cookiecutter-django. I then wanted to add wagtail cms to the project and followed the docs to do so.
I get the wagtail admin page up fine, at /cms/ instead of /admin/ like it says to do on this page - http://docs.wagtail.io/en/v1.3.1/getting_started/integrating_into_django.html
I added a few apps just to practice and get used to wagtail, one directly copied from the wagtail blog example. This is where my issue starts.
The wagtail admin Explorer does not list my apps like it shows on the wagtail site https://wagtail.io/features/explorer/, instead it just says "Welcome to your new Wagtail site!" When I select Add Child Page it allows me to select the app pages I have set up and seems to go by my models just fine. But when I post something and click go to live site it comes up as mysite.com/blog1/ instead of mysite.com/blog/blog1/
I believe my problem that I dont understand the final part of the doc page that I linked above. It says,
Note that there’s one small difference when not using the Wagtail
project template: Wagtail creates an initial homepage of the basic
type Page, which does not include any content fields beyond the title.
You’ll probably want to replace this with your own HomePage class -
when you do so, ensure that you set up a site record (under Settings /
Sites in the Wagtail admin) to point to the new homepage.
I tried adding the homepage model from the doc page, but this didn't seem to help at all.
I'm very inexperienced, this is my urls.py file, if you need to see other files please let me know.
urls.py
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtaildocs import urls as wagtaildocs_urls
from wagtail.wagtailcore import urls as wagtail_urls
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name="home"),
url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name="about"),
# Django Admin, use {% url 'admin:index' %}
url(settings.ADMIN_URL, include(admin.site.urls)),
# User management
url(r'^users/', include("contestchampion.users.urls", namespace="users")),
url(r'^accounts/', include('allauth.urls')),
# Your stuff: custom urls includes go here
# Wagtail cms
url(r'^cms/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'', include(wagtail_urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception("Bad Request!")}),
url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception("Permission Denied")}),
url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception("Page not Found")}),
url(r'^500/$', default_views.server_error),
]
These two url confs are in conflict =
url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name="home"),
url(r'', include(wagtail_urls)),
One must change, otherwise Django will always resolve the base url of `yourdomain.com/' to the first entry. One easy way to fix this is to update the second-
url(r'^content/', include(wagtail_urls)),
Now your Wagtail root page will be accessible at yourdomain.com/content.
As for mysite.com/blog/blog1/ not coming up, that Url would assume that, from your Wagtail root page, there's a page w/ slug 'blog', and then a child page of that with slug blog1. The tree structure of your Wagtail site determines the URLs by default. If you want to override that you'll have to use the RoutablePageMixin as described here.