if condition in urls.py - django - python

I want to check if user not loged(don't have a session) he go to login.html file and if he loged(have a session) he go to profile.html , but i want to check it at urls.py
My projects Tree :
manage.py
url
----setting.py
mr_url
-----templates
---------url
------------profile.html
------------login
-----------------logon.html
-----views.py
-----models.py
-----urls.py
My urls.py :
from django.conf.urls import url
from . import views
from django.views.generic import TemplateView
urlpatterns =[
url(r'^$', views.profile, name='profile'),
]
How i can check set session for user or not in urls.py ????
Note : i can do it in views.py but i don't want!

You can use login_required decorator:
from django.contrib.auth.decorators import login_required
urlpatterns =[
url(r'^$', login_required(views.profile), name='profile'),
]
If the user is not logged in, he will be redirected to the login page whose default is accounts/login. You can customize it by setting LOGIN_URL in your settings.
Hope it helps!

Related

django admin send back to homepage

i am new to django and i am makeing my first site i tried to get on my admin for my site but when i go to 127.0.0.1/admin it sends me back to the home page i have look over my code multiple times and i just cant find anything wrong about it
here is my mysite urls
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
# this is mysite not main
from django.conf.urls import url,include
from django.contrib import admin
#url('^admin/', admin.site.urls),
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('main.urls')),
url('tinymce/', include('tinymce.urls')),
]
here is my main.urls
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
# this is the main not mysite
from django.conf.urls import url
from django.contrib import admin
from . import views
app_name = 'main'
urlpatterns = [
url('',views.homepage, name="homepage"),
url("register/", views.register,name='register'),
]
urlpatterns = [
url("register/", views.register,name='register'),
url('',views.homepage, name="homepage"),
]
this is my views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .models import cooking
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, logout, authenticate
# Create your views here.
def homepage(request):
return render(request=request,template_name='main/home.html',context={"cooking": cooking.objects.all})
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("main:homepage")
else:
for msg in form.error_messages:
print(form.error_messages[msg])
form = UserCreationForm()
return render(request,"main/register.html",context={"form":form })
please tell me if you need more info thankyou
Change this url('tinymce/', include('tinymce.urls', ,namespace = "main")) to your url mysite

Django After login succeed, redirect again to login page

My Django project has 5 apps: app1, app2 ......
each app has one template index.html and 1 view named index.
project/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', include('main.urls')),
url(r'^accounts/', include('django.contrib.auth.urls')),
app1/urls.py
from django.conf.urls import url, include
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^accounts/login/$', auth_views.login, name='login'),
app1/views.py
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required, user_passes_test
def is_member(user):
return user.groups.filter(name='group1').exists()
#login_required
#user_passes_test(is_member)
def index(request):
getting our template
template = loader.get_template('app1/index.html')
rendering the template in HttpResponse
return HttpResponse(template.render())
setting.py
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/'
The 5 apps requirer login based on group
app one I have no problem to login but the reset of the apps after login succeed, I will be redirected to login page again.
The reset of the apps has exactly the same code except the group name and template location.
Also the logger result show me that there is no problem with credential.
I tried to change the group nae for other app as app1 and still I am getting same result.
Please advice me how to solve this problem.

Django 1.9.1 NoReverseMatch when using django.auth

I'm trying to learn django by following the book "Django by Example" and probably due to conflicting versions i'm running into this problem when trying to use django.auth together with some URL settings in
settings.py.
Im getting totally frustrated by now since i have no idea how to even begin debugging this error. Any help or advice would be much appreciated
Here's the relevant part of the settings.py file
from django.core.urlresolvers import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
app views.py:
from django.shortcuts import render, redirect
from django.shortcuts import HttpResponse
from django.contrib.auth import authenticate, login, logout
from .forms import LoginForm
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html', {'section': 'dashboard'})
urls.py
from django.conf.urls import url
from . import views
app_name = 'account'
urlpatterns = {
url(r'^$', views.dashboard, name='dashboard'),
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'),
}
Main urls.py :
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^account/', include('account.urls')),
]
Error Message
updated settings.py :
LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('account:login')
LOGOUT_URL = reverse_lazy('account:logout')
When you use app_name that sets up a namespace that will be used when you include() that urls.py somewhere else.
So there's no url with the name "login", instead it's called "account:login", and that's the name you have to pass to reverse().
LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('account:login')
LOGOUT_URL = reverse_lazy('account:logout')
Relevant docs: URL namespaces and included URLconfs
If you are using django-extensions (you should), you can use the management command show_urls to get a nicely formatted list of all the url routes that are registered in your project.

How to configure Django views and urls to render specific templates

When I bring up 127.0.0.1:8000, the current page that show up is something.html template.
I would need to make it appear index.html at first launch, then when I click on other parts,it should go to 127.0.0.1:8000/something.html (or 127.0.0.1:8000/myapp/something.html).
What would be the structure to achieve this?
I frequently get error message : The current URL didn't match any of these.
Currently, my structure is
project
---myapp
---admin.py
---models.py
---url.py
---views.py
---static
---templates
---myapp
---html files
---mysite
---settings.py
--- url.py
under my settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
under mysettings/url.py
urlpatterns = [
# Examples:
url(r'^$', 'mysite.views.home', name='home'),
url(r'^myapp/', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
]
mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls import patterns
from django.views.generic import TemplateView
urlpatterns = [
# Examples:
url(r'^', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
]
admin.site.site_header = 'Admin'
myapp/url.py
from . import views
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
urlpatterns = patterns('',
#brings up something.html when we comment it out. No module found if included.
#url(r'^$', views.home, name='home'),
url(r'^$', views.post_list, name='post_list'),
)
Include urls of your myapp app in mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
]
Now, all urls, starting by 127.0.0.1:8000, will check if there is a view that can handle the request. I recommend you to read this to understand how Django URL dispatcher works : [Django documentation - URL Dispatcher] (https://docs.djangoproject.com/en/1.8/topics/http/urls/).
2. Add new route in your myapp.urls:
from django.conf.urls import url, patterns
from . import views
urlpatterns = patterns('',
url(r'^$', views.home, name='home'),
url(r'^something$', views.something, name='something'),
url(r'^posts$', views.post_list, name='post_list'),
)
Now :
127.0.0.1:8000/ will executed code of views.home
127.0.0.1:8000/something will executed code of views.something
127.0.0.1:8000/posts will executed code of views.post_list
Let's define these view now
3: Define the views in myapp.views :
from django.shortcuts import render
def home(request):
"""
Return home page
"""
return render(request, 'myapp/home.html')
def something(request):
"""
Return something page
"""
return render(request, 'myapp/something.html')
def post_list(request):
"""
Return something page
"""
# do what you want
Add your templates in myapp/templates/myapp/. Add home.html and something.html.
Now forget, the `.html
You create a url (with attached view to it).
In the view you render any html page you want.
If you use function based views your 'mysite.views.home' may look like:
def home(request):
...
return render(request, 'path/to/index.html')
and so on.
It's the basics so I won't talk about this much. You can find a good tutorial about mapping urls to views there.

What more do I need to do to have Django's #login_required decorator work?

I am trying to use Django's account system, including the #login_required decorator. My settings.py file includes django.contrib.auth and I have done a syncdb.
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/accounts/login/?next=/
Using the URLconf defined in dashboard.urls, Django tried these URL patterns, in this order:
^$ [name='home']
The current URL, accounts/login/, 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.
I see the above after trying to #login_required-decorate my home view.
It seems to be choking because it is redirected to accounts/login/, which I have not prepared for in my urls.py.
What can I add to urls.py or elsewhere so that the login_required decorator will do its usual behaviour?
Thanks,
Set the LOGIN_URL in your settings. The default value is '/accounts/login/'
The decorator also takes an optional login_url argument:
#login_required(login_url='/accounts/login/')
And, from the docs:
Note that if you don’t specify the login_url parameter, you’ll need to
ensure that the settings.LOGIN_URL and your login view are properly
associated. For example, using the defaults, add the following line to
your URLconf:
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
path('accounts/login/', admin.site.urls),
Add this line in your urls.py project folder. Then it will work fine.
from django.contrib.auth.decorators import login_required
#login_required(login_url='/accounts/login/')
Add above two lines in your views.py file.
What worked for me in Django 2.2.1 - include re_path('^accounts/', admin.site.urls), in my project urls.py:
urls.py
from django.conf import settings
from django.conf.urls import include
from django.conf.urls import re_path
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^accounts/', admin.site.urls),
]
And in my views.py:
views.py
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
#method_decorator(login_required, name='dispatch')
class HomePageView(TemplateView):
"""
Home Page View
"""
template_name = 'amp/home.html'
Hope that helps.
UPDATE: To avoid warnings from django in regards to admin urls being loaded twice, I used a redirect instead in urls.py:
urls.py
urlpatterns = [
re_path('^accounts/', admin.site.urls),
re_path(r'^admin/', RedirectView.as_view(url='/accounts/', permanent=True))
]
More on redirect view here.

Categories

Resources