Having trouble with exempt url - python

Hi I am trying to exempt a url in my project so that the user can bypass the middleware and reset their password without being logged in. However the urls I have placed in LOGIN_EXEMPT_URLS don't seem to fix this, instead the link to reset-password redirects the user to account/login.
settings.py:
LOGIN_EXEMPT_URLS = {
r'^account/logout/$',
r'^account/register/$',
r'^account/reset-password$',
r'^account/reset-password/done/$',
r'^account/reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,23})/$',
r'^account/reset-password/complete/$',
}
middleware.py:
url_is_exempt = any(url.match(path)for url in EXEMPT_URLS)
if path == reverse('accounts:logout').lstrip('/'):
logout(request)
if request.user.is_authenticated and url_is_exempt:
return redirect(settings.LOGIN_REDIRECT_URL)
elif request.user.is_authenticated or url_is_exempt:
return None
else:
return redirect(settings.LOGIN_URL)
urls.py:
urlpatterns = [
url(r'^$', views.home),
url(r'^login/$', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
url(r'^logout/$', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),
url(r'^register/$', views.register, name='register'),
url(r'^profile/$', views.view_profile, name='view_profile'),
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
url(r'^change-password/$', views.change_password, name='change_password'),
url(r'^reset-password/$',
PasswordResetView.as_view(template_name='accounts/reset_password.html',
success_url=reverse_lazy('accounts:password_reset_done')), name='reset_password'),
url(r'^reset-password/done/$', PasswordResetDoneView.as_view(), name='password_reset_done'),
url(r'^reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,23})/$',
PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
url(r'^reset-password/complete/$', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]
main/urls.py:
urlpatterns = [
path('', views.login_redirect, name='login_redirect'),
path('admin/', admin.site.urls),
path('account/', include('accounts.urls', namespace='accounts')),
]
html: This is in {% else %} (user.is.authenticated)
<ul class="navbar-nav ml-auto">
<li class='nav-item'>
<a class="nav-link" href='{% url 'accounts:reset_password' %}'>Forgotten Password?</a>
Everything in html is properly formatted but I think some of the code is bugging out. Sorry about that
FYI: Register in exempt works!
So whats the problem? thnx

Your exempt regex r'^account/reset-password$' does not have a trailing slash. This is inconsistent with the regex in your URL pattern, r'^reset-password/$', which does have a trailing slash.

Related

Django 4.0 shows path not found even after configuring all urls and views properly

So my django app looks like this
-assaydash
--dashboard (app)
--members (app)
--djangobackend (django project directory)
--static
--manage.py
djangobackend/settings.py
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dashboard.apps.DashboardConfig',
'members.apps.MembersConfig',
]
djangobackend/urls.py
urlpatterns = [
path('admin/', admin.site.urls, name='admin'),
path('', include('dashboard.urls')),
path('members/', include('django.contrib.auth.urls')),
path('members/', include('members.urls')),
]
members/urls.py
urlpatterns = [
path('login_user', views.login_user, name="login"),
path('logout_user', views.logout_user, name='logout'),
]
members/views.py
def login_user(request):
if request.method == "POST":
...
else:
messages.success(request, ("There Was An Error Logging In, Try Again..."))
return redirect('login')
else:
return render(request, 'authenticate/login.html', {})
def logout_user(request):
logout(request)
messages.success(request, ("You Were Logged Out!"))
return redirect('home')
index.html
<a href="{% url 'login' %}" >
<span class="d-sm-inline d-none">Sign In</span>
</a>
On the index page when i click on the a tag it shows me a debug page with path not found. Even though the url exists and i have included it in my main urls.py and i have added the app in the settings.py as well. please help and let me know what is wrong here.
Notice that the url for name login was detected by the template but the path wasn't found. Also the other urls on the debug page are from my dashboard app which works fine
Because you have set the url path of django.contrib.auth.urls to members/ and the django.contrib.auth.urls include patterns of /members/login/ for name=login. Since urlpatterns will look from upper to lower your /members/login/ called instead of /members/login_userand look for corresponding page. So change your url path to others than members/ in
path('members/', include('django.contrib.auth.urls')),
and use members/ for include('members.urls').
If you have set
urlpatterns = [
path('accounts/', include('django.contrib.auth.urls')),
]
The django.contrib.auth.urls include urlpatterns as
accounts/login/ [name='login']
accounts/logout/ [name='logout']
accounts/password_change/ [name='password_change']
accounts/password_change/done/ [name='password_change_done']
accounts/password_reset/ [name='password_reset']
accounts/password_reset/done/ [name='password_reset_done']
accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/reset/done/ [name='password_reset_complete']
See Authentication Views[Django-doc]
So change your djangobackend/urls.py as
urlpatterns = [
path('admin/', admin.site.urls, name='admin'),
path('', include('dashboard.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('members/', include('members.urls')),
]
Also change your member urls.py as
urlpatterns = [
path('login_user', views.login_user, name="login-user"),
path('logout_user', views.logout_user, name='logout-user'),
]
Also in html
<a href="{% url 'login-user' %}" >
<span class="d-sm-inline d-none">Sign In</span>
</a>

How to switch HTML page in Python with Django

Template :
<a class="btn btn-primary" href="{% url 'edit' %}">Edit</a>รน
views.py:
def edit(request):
return render(request, "edit.html")
urls.py:
urlpatterns = [
path("", views.index, name="index"),
path("wiki/create", views.create, name="create"),
path("wiki/edit", views.edit, name="edit"),
path("wiki/<str:name>", views.entry, name="entry"),
path("search", views.search, name="search"),
path("save", views.save, name="save"),
path("random", views.random, name="random"),
]
I would like simply to switch from an HTML page on another, but the function gives me this error:
TemplateDoesNotExist at /wiki/edit
edit.html
But the template exist, I created it. I tryed a lot of changes but all of them gives me error. Thank you.
The Application name needs to be referenced in the template name.
Like so:
return render(request, "encyclopedia/edit.html")

Reverse for 'login' not found. 'login' is not a valid view function or pattern name

It gives the error: Reverse for 'login' not found. 'login' is not a valid view function or pattern name.
It says NoReverseMatch.
Tried replacing the url login with accounts:login and didn't work.
{% if user.is_authenticated %}
<form id="logoutForm" action="/logout/" method="post" class="navbar-right">
{% csrf_token %}
<ul class="nav navbar-nav navbar-right">
<li><span class="navbar-brand">Hello {{ user.username }}!</span></li>
<li>Log off</li>
</ul>
</form>
{% else %}
<ul class="nav navbar-nav navbar-right">
<li>Log in</li>
</ul>
{% endif %}
My accounts app urls file:
urlpatterns = [
path('login/',
LoginView.as_view
(
template_name='accounts/login.html',
authentication_form=forms.BootstrapAuthenticationForm,
extra_context=
{
'title': 'Log in',
'year' : datetime.now().year,
}
),
name='login'),
path('logout/', LogoutView.as_view(next_page='/'), name='logout'),
path('signup/', views.signup, name='signup'),
]
My main urls file:
urlpatterns = [
path('', views.home, name='home'),
path('', include('accounts.urls')),
path('contact/', views.contact, name='contact'),
path('about/', views.about, name='about'),
path('admin/', admin.site.urls),
]
I don't know what to do about this, tried many stuff.
accounts/urls.py file should add the auth_views:
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/',
auth_views.LoginView.as_view
(
template_name='accounts/login.html',
authentication_form=forms.BootstrapAuthenticationForm,
extra_context=
{
'title': 'Log in',
'year' : datetime.now().year,
}
),
name='login'),
path('logout/', auth_views.LogoutView.as_view(next_page='/'), name='logout'),
path('signup/', views.signup, name='signup'),
]
Please use the following code for login urls. Actually you are using the same route for two different urls:
urlpatterns = [
path('', views.home, name='home'),
path('accounts/', include('accounts.urls')),
path('contact/', views.contact, name='contact'),
path('about/', views.about, name='about'),
path('admin/', admin.site.urls),
]
ok got the solution. you were using
path('', include('accounts.urls')),
in main urls.py correct it to put a namespace
path('', include('accounts.urls', namespace='accounts')),
and then correct the template
<ul class="nav navbar-nav navbar-right">
<li>Log in</li>
</ul>

How to render Image on the web page using path from DB in Django?

So I am trying to display an image on the web page, i save the image path in the database as media/imagename and in my html page i am doing this :
{% for stuff in profile %}
<div class="alert alert-success" role="alert"> {{ stuff.text }} </div>
<img scr='/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media/{{ stuff.thumbnail }}' width="200">
{% endfor %}
And in my settings.py i do this:
MEDIA_ROOT = os.path.join(PROJECT_ROOT, '/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media')
But the image doesn't display. What am i doing wrong here? Thanks!
Edit:
#urls.py
from django.conf.urls import patterns, url
from django.conf import settings
from social import views
urlpatterns = [
# main page
url(r'^$', views.index, name='index'),
# signup page
url(r'^signup/$', views.signup, name='signup'),
# register new user
url(r'^register/$', views.register, name='register'),
# login page
url(r'^login/$', views.login, name='login'),
# user doesnt exist webpage
url(r'^user-doesnt-exist/$', views.login, name='user-doesnt-exist'),
#page to show that the password is incorrect
url(r'^wrongpass/$', views.login, name='wrongpass'),
#webpage to show an error when a user tries to input nothing in the fields when signing up
url(r'^novalues/$', views.register, name='novalues'),
# logout page
url(r'^logout/$', views.logout, name='logout'),
# members page
url(r'^members/$', views.members, name='members'),
#invites page
url(r'^invites/$', views.invites, name='invites'),
# friends page
url(r'^friends/$', views.friends, name='friends'),
# user profile edit page
url(r'^profile/$', views.profile, name='profile'),
# messages page
url(r'^messages/$', views.messages, name='messages'),
# Ajax: check if user exists
url(r'^checkuser/$', views.checkuser, name='checkuser'),
#commiting again
]
if settings.DEBUG:
urlpatterns += patterns(''(r'^media/(P<path>.*)$','django.views.static.serve',
{'document_root':settings.MEDIA_ROOT,'show_indexes':True})),
Try setting your MEDIA_ROOT to:
MEDIA_ROOT = os.path.join(BASE_DIR, 'social/static/social/media')
MEDIA_URL = '/media/'
And in your project urls.py file add:
from django.conf import settings
from django.conf.urls import patterns
if settings.DEBUG:
urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}))
Then, in your template call the image like:
{% if stuff.thumbnail %}
<img src="{{ object.thumbnail.url }}">
{% endif %}
And in models.py:
image = models.ImageField(upload_to='images/')
Here's some great documentation on serving media files, including how to serve them during development.

Django how to save model in view

I'm new to Django. I'm having an issue where I can't save my model in the views.py. The concept is to have an input field where a user can type in a name, then using request.POST.get('attribute_name') I can save my model, but it's not working. When I print a list of all the objects in that model there's nothing there, even though I don't get an error message during all of this.
template:
<form id="save_form" method="post" action="{% url 'project_view.views.projectz_save' %}">
{% csrf_token %}
<table>
<tr>
<td>Project Name</td>
<td><input name="projectz_name"/></td>
</tr>
</table>
<input type="submit" value="Save" />
</form>
views.py:
def projectz_save(request):
try:
p = Project(name=request.POST.get('projectz_name'))
p.save()
return redirect('http://www.google.com/')
except:
return redirect('http://www.google.com/')
app urls:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.register, name='register'),
url(r'^$', views.projectz_save, name='project_save'),
)
site urls:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^project_view/', include('project_view.urls')),
I even put in some silly redirect code to google.com just to see if the views.py was even executing, but it's not working, though like I said there are no error messages, the page just refreshes. I'm sure I'm doing wrong that's easy to fix, but I'm a noobie. :D
Ok I think maybe I spotted the problem. The view is not executing because you have defined three urls with the exact regex in your project urls.py:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.register, name='register'),
url(r'^$', views.projectz_save, name='project_save'),
)
Django match it's urls by iterating over the patterns in the way they appeared so in that file all urls will match index. That's probably the reason why the page appears to be refreshing. Try to modify this a little:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register$', views.register, name='register'),
url(r'^save$', views.projectz_save, name='project_save'),
)
This way you can execute the projectz_save method in the views.py if the action of the form matches the url regex.
Hope this helps!

Categories