How To Fix Auto Login In Django? - django

How To Fix Auto login When I go to this URL like this: 127.0.0.1:8000/profile/1 When I see If Someone go to that URL so Django login him without password and username
ERROR:
How To Fix Auto Login In Django
You Can See The Gif For More Details:
Views.py
def profile_detail(request,pk):
user = get_object_or_404(User, pk=pk)
model = user_register_model()
return render(request,'profile_detail_view.html',{'user':user,'model':model,})
urls.py
from . import views
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index,name='index'),
path('accounts/signup/', views.user_reg,name='register'),
path('profile/<int:pk>',views.profile_detail,name='profile'),
]
Here is my Base.html
<ul class="navbar-nav ml-auto">
{% if not user.is_authenticated %}
<li class="nav-item">
<a class="nav-link navaour" href="{% url 'register' %}"><i class="fa fa-check-square-o"></i> Sign up Free</a>
</li>
<li class="nav-item">
<a class="nav-link navaour" href="{% url 'login' %}"><i class="fa fa-user"></i> Login</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link navaour" href=""><i class="fa fa-user"></i> Profile</a>
</li>
<li class="nav-item">
<a class="nav-link navaour" href="{% url 'logout' %}"><i class="fa fa-power-off"></i> Logout</a>
</li>
{% endif %}
Here is my profile_detail_view.html
<div class="row">
<div class="col-sm-3 col-md-2 col-5">
<label style="font-weight:bold;">Full Name</label>
</div>
<div class="col-md-8 col-6">
{{user.username}}
</div>
</div>
Any Help Appreciated
Thanks!

replace {% if not user.is_authenticated %} with {% if not request.user.is_authenticated %} in your template. You missed request.

you can also use #login_required before the def in views.py and importing library
from django.contrib.auth.decorators import login_required
This will help in blocking those views of url for the users who aren't logged in.

Related

why my Python Django urls is not working?

I am working on a python django website and my urls are not working properly. I have included my urls.py and the nav links which are the same on each page.
Urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
]
navbar.html:
{% load static %}
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<img src="{% static 'images/logo.png' %}">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="{% url 'home' %}">Dashboard</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'products' %}">Products</a>
</li>
</ul>
</div>
</nav>
With minimum information provided, I can come to understand that you facing problem to visit another link or url using your navbar despite providing correct information. If that is the case, I think this can solve your issue.
Check your class nav-link :
<a class="nav-link" href="{% url 'products' %}">Products</a>
You must also provide the namespace of your application from the settings urls.py like this:
`<a class="nav-link" href="{% url 'app_namespace:products' %}">Products</a>`
This is the reference from documentation. https://docs.djangoproject.com/en/3.1/topics/http/urls/#url-namespaces

no reverse matching at / and crawler is not a registered namespace

I am trying to make a codeforces crawler and I am just adding user authentication in the somehow failed to implement. Reverse not match and crawler is not a registered namespace is the error I'm getting. I don't know what files exactly are needed to put here so please ask me I will post them if you need it. I'm just a beginner and I need help.
crawler/urls.py
app_name = 'crawler'
urlpatterns = [
path('',views.index,name='index'),
path('formpage/',views.search_form_view , name='searchform'),
path('formpage/<str:handle>',views.person, name= 'person'),
path('user_login/',views.user_login,name ="user_login"),
path('logout/',views.user_logout,name="logout"),
]
base.html
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="{% url 'crawler:index'%}">Crawler</a>
<!-- Links -->
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'crawler:searchform'%}">Search</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link 2</a>
</li>
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{%url 'crawler : logout'%}">Log Out</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{%url 'crawler :user_login'%}">Login</a>
{% endif %}
</li>
</li>
</ul>
</nav>
<br>
{% block body_block %}
{% endblock %}
</body>
views.py
#login_required
def user_logout(request):
logout(request)
return HttpResponse(reverse('index'))
webcrawler/urls.py
app_name = 'crawler'
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('crawler.urls',namespace= "crawler")),
]
A two-part answer here.
No reverse match at /
The point is that, in both your main and app urls.py, you registered both URLs to be '', which means that there will be a match at (empty string) but won't be one at '/'. To fix this, simply add '/' to the main urls.py as it's a better practice.
Crawler is not a registered namespace
As you call an URL, it should be {% url 'crawler:index' %} or {% url 'crawler:searchform' %} or something because crawler is the main namespace but there are multiple URLs under it so you need to pass an additional parameter after your crawler namespace.

Django 3.0.3: NoReverseMatch at / : Reverse for 'post_new' with no arguments not found. 1 pattern(s) tried:

Need Help. I am not passing an argument while using href but still url pattern is looking for an argument.
Master urls.py
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^$',include('portfolio.urls')),
re_path(r'accounts/login/$',LoginView.as_view(),name='login'),
re_path(r'accounts/logout/$',LogoutView,name='logout',kwargs={'next_page':'/'})
]
Portfolio.urls
urlpatterns = [
re_path(r'^$',views.PostListView.as_view(),name='post_list'),
re_path(r'^about/$', views.AboutView.as_view(),name='about'),
path ('post/new/',views.CreatePostView.as_view(),name='post_new'),
re_path (r'^drafts/$',views.DraftListView.as_view(),name='post_draft_list'),]
<nav class="navbar navbar-dark bg-dark">
<div class ="container">
<ul class= "navbar navbar-dark bg-dark">
<li><a class='navbar-brand' href="{% url 'post_list' %}"> My Blog </a>
<li>Github</li>
<li>Linkedin</li>
</ul>
<ul class='nav nsvbsr-right'>
{% if user.is_authenticated %}
<li>
New Post
Draft
Log Out
</li>
<li>
<a> Welcome : {{ user.username }} </a>
</li>
{% else %}
<li> <a class='nav nsvbsr-right' href="{% url 'login' %}"> Login </a> </li>
{% endif %}
</ul>
</div>
</nav>
I am getting the following error:
In Short: Page throws the error after user logs in (i.e. is_authenticated is true).
Models.py
class CreatePostView(LoginRequiredMixin, CreateView):
login_url="/login/"
redirect_field_name="portfolio/post_detail.html"
form_class = PostForm
model = Post
Remove the dollar from the URL pattern that includes portfolio.urls.
re_path(r'^',include('portfolio.urls')),
Or switch to path:
path('',include('portfolio.urls')),

Django context does not render in base template

I appreciate that similar questions have been asked before, but after looking at them, I still cannot seem to solve my issue.
By following the documentation, I have the below files:
views.py
from django.shortcuts import render
# Create your views here.
def base(request):
articles = 'articles'
dboard = 'dashboard'
pages = {'dboard':dboard, 'Articles':articles}
return render(request, 'collatedata/base.html', pages)
def dash(request):
return render(request, 'collatedata/dash.html')
collatedata/urls.py:
urlpatterns = [
path('', views.dash, name='dash'),
]
main urls.py:
urlpatterns = [
path('', include('collatedata.urls')),
path('admin/', admin.site.urls),
]
base.html:
...
<li class="nav-item">
<a href="#" class="nav-link text-white p-3 mb-2">
<i class="fas fa-home text-light fa-lg mr-3"></i>
{{ dboard }}
</a>
</li>
...
dash.html
{% extends "./base.html" %}
however, the output does not read {{ dboard }}
so returns this:
<li class="nav-item">
<a href="#" class="nav-link text-white p-3 mb-2">
<i class="fas fa-home text-light fa-lg mr-3"></i>
</a>
</li>
could it be to do with base.html being extended?

How to setup the url redirect correctly after user registration and login in django?

So, I have setup django-registration's simple backend where the user registers and is immediately logged in to the display to my other django app fileuploader. Here is the urls.py:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
from registration.backends.simple.views import RegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
# return "/upload/new"
return "/upload/" + user.get_absolute_url()
urlpatterns = patterns('',
url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^upload/', include('mysite.fileupload.urls')),
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
import os
urlpatterns += patterns('',
(r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
)
So after the user registers at accounts/register he/she is taken directly to the url upload/users/username
Here is the mysite.fileuplaod.urls that contains the url patterns for upload/:
from django.conf.urls import patterns, include, url
from mysite.fileupload.views import PictureCreateView, PictureDeleteView
from mysite.registration.backends.simple.views import RegistrationView
from django.contrib.auth.models import User
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from mysite.registration import signals
from mysite.registration.views import RegistrationView as BaseRegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
# return "/upload/new"
return "/upload/" + user.get_absolute_url()
urlpatterns = patterns('',
(r'$'+get_absolute_url(),PictureCreateView.as_view(), {}, 'upload-new'),
(r'^new/$', PictureCreateView.as_view(), {}, 'upload-new'),
(r'^delete/(?P<pk>\d+)$', PictureDeleteView.as_view(), {}, 'upload-delete'),
)
I want to setup the exact same view as upload/new for upload/users/username. r'$'+get_absolute_url() doesn't look like the right way to do it. I would really appreciate if someone could show me the right way to do this.
Also I would like to display the user name on the fileupload view page as something like "Welcome
{% extends "base.html" %}
{% load upload_tags %}
{% block content %}
<div class="container">
<div class="page-header">
<h1>Wordseer File Uploader</h1>
</div>
<form id="fileupload" method="post" action="." enctype="multipart/form-data">{% csrf_token %}
<div class="row fileupload-buttonbar">
<div class="span7">
<span class="btn btn-primary fileinput-button">
<i class="icon-plus icon-white"></i>
<span>Add files...</span>
<input type="file" name="file" multiple>
</span>
<button type="submit" class="btn btn-success start">
<i class="icon-upload icon-white"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="icon-ban-circle icon-white"></i>
<span>Cancel upload</span>
</button>
<button type="button" class="btn btn-danger delete">
<i class="icon-trash icon-white"></i>
<span>Delete files</span>
</button>
<input type="checkbox" class="toggle">
</div>
<div class="span5 fileupload-progress fade">
<div class="progress progress-success progres-striped active">
<div class="bar" style="width:0%"></div>
</div>
<div class="progress-extended"> </div>
</div>
</div>
<div class="fileupload-loading"></div>
<table class="table table-striped"><tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody></table>
</form>
<div class="fileupload-content">
<table class="files"></table>
<div class="fileupload-progressbar"></div>
</div>
<div>
{% if pictures %}
<h2>Already uploaded</h2>
<table class="table table-striped">
{% for picture in pictures %}
<tr>
<td class="preview">
<img src="{{ picture.file.url }}">
</td>
<td class="name">{{ picture.slug }}</td>
<td class="delete">
<a class="btn btn-danger" href="{% url 'upload-delete' picture.id %}">
<i class="icon-trash icon-white"></i>
<span>Delete</span>
</button>
</td>
</tr>
{% endfor %}
</table>
<p>(Removing from this list is left as an exercise to the reader)</p>
{% endif %}
</div>
</div>
<!-- modal-gallery is the modal dialog used for the image gallery -->
<div id="modal-gallery" class="modal modal-gallery hide fade" data-filter=":odd">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3 class="modal-title"></h3>
</div>
<div class="modal-body"><div class="modal-image"></div></div>
<div class="modal-footer">
<a class="btn modal-download" target="_blank">
<i class="icon-download"></i>
<span>Download</span>
</a>
<a class="btn btn-success modal-play modal-slideshow" data-slideshow="5000">
<i class="icon-play icon-white"></i>
<span>Slideshow</span>
</a>
<a class="btn btn-info modal-prev">
<i class="icon-arrow-left icon-white"></i>
<span>Previous</span>
</a>
<a class="btn btn-primary modal-next">
<span>Next</span>
<i class="icon-arrow-right icon-white"></i>
</a>
</div>
</div>
{% upload_js %}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="{{ STATIC_URL }}js/jquery.ui.widget.js"></script>
<script src="{{ STATIC_URL }}js/tmpl.min.js"></script>
<script src="{{ STATIC_URL }}js/load-image.min.js"></script>
<script src="{{ STATIC_URL }}js/canvas-to-blob.min.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap.min.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap-image-gallery.min.js"></script>
<script src="{{ STATIC_URL }}js/jquery.iframe-transport.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload-fp.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload-ui.js"></script>
<script src="{{ STATIC_URL }}js/locale.js"></script>
<script src="{{ STATIC_URL }}js/main.js"></script>
<script src="{{ STATIC_URL }}js/csrf.js"></script>
{% endblock %}
Thanks in advance.
To set url use something like:
url(r"^(?P<username>\w+)/$", PictureCreateView.as_view(), {}, 'upload-new')
and move it after 'new/' url.
To display user name in template use:
{{ request.user.username }} or {{ request.user.get_full_name }}