Django (Password_change) doesn't work url - python

I'm learning Django book named by (Django for beginners)
I have a problem with password _change
Below my code from urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('',include('pages.urls')),
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
path('users/',include('django.contrib.auth.urls')),
]
Next is password_change_form.html
{% extends 'base.html' %}
{% block title %}
Password Change
{% endblock %}
{% block content %}
<h1>Password change</h1>
<p>Please enter your old password, for security's sake, and then enter your
new password twice so we can verify you typed it in correctly.</p>
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<input type="submit" class="btn btn-success" value="Change my password">
</form>
{% endblock %}
my content does'nt linking to password_change_form.html
Via versa linking to password_change from Django adminstration

Try this:
Crete an app named 'registration'
python manage.py startapp registration
Set it in the first position of your installed Apps:
INSTALLED_APPS = [
'registration',
....
]
Inside the app 'registration', create a the folder 'templates/registration'
Inside the folder created in the previous step, you can now set all your custom templates, 'password_change_form.html', 'password_change_done.html', etc....
import the urls inside the main urls, I would prefer using like this:
urlpatterns = [
... # your urls
path('accounts/',include('django.contrib.auth.urls')),
]

Related

Why this form doesn't change the language of the website?

This is my language-switching form.
{% get_current_language as lang_code %}
{% get_available_languages as languages %}
{% get_language_info_list for languages as langs %}
<form action="{% url 'set_language' %}" method="POST">
{% csrf_token %}
<select name="language" title="{% translate 'Language' %}">
{% for lang in langs %}
<option value="{{ lang.code }}"{% if lang.code == lang_code %} selected{% endif %}>
{{ lang.name_local }} ({{ lang.name_translated }})
</option>
{% endfor %}
</select>
<input type="submit" value="OK" />
</form>
I include this in the footer of my base template.
Then, here is my courses/urls.py (app urls).
from django.contrib import admin
from django.urls import path
from django.utils.translation import gettext_lazy as _
from . import views
admin.site.site_header = _("FilFak administration")
admin.site.site_title = _("FilFak admin")
admin.site.index_title = _("Manage FilFak")
urlpatterns=[
path("courses/", views.CourseList.as_view(), name="course_list"),
path("professors/", views.ProfessorList.as_view(), name="professor_list"),
path("exams/", views.ExamList.as_view(), name="exam_list"),
path("courses/<slug:slug>", views.CourseDetails.as_view(), name="course_details"),
path("professors/<slug:slug>", views.ProfessorDetails.as_view(), name="professor_details"),
path("exams/<slug:slug>", views.ExamDetails.as_view(), name="exam_details"),
path("", views.Index.as_view(), name="index"),
]
filfak/urls.py (project urls.py)
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.conf import settings
from django.utils.translation import gettext_lazy as _
urlpatterns = [
path("admin/", admin.site.urls),
path("lang/", include("django.conf.urls.i18n")),
]
urlpatterns += i18n_patterns(
path("", include("courses.urls")),
prefix_default_language=False
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And here's the list of middlewares from settings.py.
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
When I click OK on the language-switching form, it actually changes the language only on the homepage of the default language. On any other URL it just refreshes the page, without changing the language.
Am I doing something wrong?
Check the flag value of USE_I18N, look like its set to False and thats why the language are not setting properly.
Change it to :-
USE_I18N = True
As per Django document :-
If you don’t use internationalization, you should take the two seconds to set USE_I18N = False in your settings file.

no such table: (Django)

when i run my code (its for a project) i get this error: "no such table: encyclopedia_article". The error appears to come from 9 line of views.py (obj = article.objects.get(id=1). here is the code:
views.py
from django.shortcuts import render
from django.http import HttpResponse
from . import util
import random
from .models import article
from .forms import ArticleForm
def index(request):
obj = article.objects.get(id=1) #THIS IS WHAT APPERS TO CAUSE THE ERROR
context = {
'object': obj
}
entries = util.list_entries()
random_page = random.choice(entries)
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries(),
"random_page": random_page,
})
def CSS(request):
return render(request, "encyclopedia/css_tem.html", {
"article_css": "css is slug and cat"
})
def Python(request):
return render(request, "encyclopedia/python_tem.html", {
"article_python": "python says repost if scav"
})
def HTML(request):
return render(request, "encyclopedia/HTML_tem.html", {
"article_HTML": "game theory: scavs are future humans"
})
def Git(request):
return render(request, "encyclopedia/Git_tem.html", {
"article_Git": "github is git"
})
def Django(request):
return render(request, "encyclopedia/Django_tem.html", {
"article_Django": "this is a framework"
})
def new_article(request):
form = ArticleForm(request.POST or None)
if form.is_valid():
form.save()
context = {
'form': form
}
return render(request, "encyclopedia/new_article_tem.html", context)
models.py:
class article(models.Model):
title = models.CharField(max_length = 120)
description = models.TextField(blank=True, null = False)
forms.py:
from django import forms
from .models import article
class ArticleForm(forms.ModelForm):
class Meta:
model = article
fields = [
'title',
'description'
]
urls:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("", views.CSS, name="CSS"),
path("", views.Python, name="Python"),
path("", views.HTML, name="HTML"),
path("", views.Git, name="Git"),
path("", views.Django, name="Django"),
path("", views.new_article, name="new_article")
]
second urls (in other directory (there is encyclopedia and wiki this one is in wiki the last one in encyclopedia)):
"""wiki URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
from encyclopedia import views
from encyclopedia.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("encyclopedia.urls")),
path('CSS/', views.CSS, name="CSS"),
path('Python/', views.Python, name="Python"),
path('HTML/', views.HTML, name="HTML"),
path('Git/', views.Git, name="Git"),
path('Django/', views.Django, name="Django"),
path('new_article/', views.new_article, name="new_article"),
path('main/', index)
]
new_article_tem.html:
{% extends "encyclopedia/layout.html" %}
{% block title %}
New Article
{% endblock %}
{% block body %}
<h1>Create Article</h1>
<form method = 'POST' action = "{% url 'index' %}"> {% csrf_token %}
<input type = 'submit' value='Save'>
</form>
{% endblock %}
IM NOT SURE IF THIS ONES ARE USEFULL BUT STILL IM PUTTING ALMOST EVERYTHING:
index.html:
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia
{% endblock %}
{% block body %}
<h1 id="demo" onclick="add_article()">Add article</h1>
<ul>
{% for entry in entries %}
<li><a href = /{{entry}}>{{ entry }}</a></li>
{% endfor %}
{% for article_title in created_articles %}
<li>{{article_title}}</li>
{% endfor %}
<li>{{title}}</li>
</ul>
{% endblock %}
layout.html:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
</head>
<body>
<div class="row">
<div class="sidebar col-lg-2 col-md-3">
<h2>Wiki</h2>
<form>
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
<div>
Home
</div>
<div>
<a href = "/new_article" >Create New Article</a>
</div>
<div>
Random Page
</div>
{% block nav %}
{% endblock %}
</div>
<div class="main col-lg-10 col-md-9">
{% block body %}
{% endblock %}
</div>
</div>
</body>
</html>
Try to use this :-
python manage.py makemigrations
and then
python manage.py migrate

django Custom Template is not rendering for password_change_form.html

I have a password_change_form.html which is custom formatted on the website.
I'm overriding the Django default template with my template. But, it is not rendering my template. It just rendering the default template as below.
I have created a custom formated template
base.html
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{% url 'password_change' %}">Change password</a>
<div class="dropdown-divider"></div>
password_change_form.html
{% extends 'home/base.html' %}
{% block body %}
<h2>
Change password
</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Change password</button>
</form>
{% endblock %}
urls.py
from django.contrib import admin
from django.urls import path, include
from Shopping.cart import urls
urlpatterns = [
path('', include('Shopping.cart.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('admin/', admin.site.urls),
]
I wanted to see my template overrides the Django default template
Resolved
I made a mistake that I placed my templates folder inside the app. this was causing the problem. Now I moved my template folder to the Project folder. Now everything working fine. Thank you.
The solution for me was to point the "users" app above the built-in django apps in "INSTALLED_APPS = []".
upd 11/12/2020:
Python reads the code from top to bottom.
From Django official docs on INSTALLED_APPS settings:
When several applications provide different versions of the same
resource (template, static file, management command, translation), the
application listed first in INSTALLED_APPS has precedence.
If the "users" app is located below 'django.contrib.admin', then Django will go to the "admin" application and find there templates/registration/password_change_form.html
Therefore, the "users" app must go before the admin application in INSTALLED_APPS.

Django - template not being detected

I'm using this library to handle two factor auth for a django project, but i'm having some troubles: in my site, i added a setup.html page, i set the url on my urls.py file but i keep getting this error:
In template C:\Users\Us\lib\site-packages\allauth\templates\base.html, error at line 26
Reverse for 'account_email' not found. 'account_email' is not a valid view function or pattern name.
<li>Change E-mail</li>
Which is completely weird because i'm not trying to load a file called base.html but my own setup.html file, which is located in my project's folder (the path is project-folder>templates>setup.html). This is the setup.html that i would like to load from my own templates:
{% extends 'main/header.html' %}
{% load i18n %}
{% block content %}
<h1>
{% trans "Setup Two-Factor Authentication" %}
</h1>
<h4>
{% trans 'Step 1' %}:
</h4>
<p>
{% trans 'Scan the QR code below with a token generator of your choice (for instance Google Authenticator).' %}
</p>
<img src="{{ qr_code_url }}" />
<h4>
{% trans 'Step 2' %}:
</h4>
<p>
{% trans 'Input a token generated by the app:' %}
</p>
<form method="post">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.token.label }}: {{ form.token }}
<button type="submit">
{% trans 'Verify' %}
</button>
</form>
{% endblock %}
It looks like the module that i'm using, instead of loading MY setup.html will load something else, but i can't find a way to fix this.
Here is the view that i'm calling to handle the setup (it' the module's view):
https://github.com/percipient/django-allauth-2fa/blob/master/allauth_2fa/views.py
And here is my own urls.py, where the view that i mentioned is being called:
from django.urls import path
from . import views
from django.conf.urls import url, include
from django.conf.urls import url
from allauth_2fa import views as allauth_2fa_views
app_name = "main"
urlpatterns = [
path("setup/", allauth_2fa_views.TwoFactorSetup.as_view(), name="setup"),
path("", views.homepage, name="homepage"),
path("register/", views.register, name="register"),
path("logout/", views.logout_request, name="logout"),
path("login/", views.login_request, name="login"),
]
The TwoFactorSetup view is using a template setup.html in a folder allauth_2fa. So all you need to do is place your setup.html inside a folder with the same name: app_folder/templates/allauth_2fa/setup.html to override it.
Alternatively, subclass TwoFactorSetup and just change the template_name attribute to point to your template and use that view in your urls.py:
from allauth_2fa.views import TwoFactorSetup
class MySetup(TwoFactorSetup):
template_name = 'my_app/setup.html'

Django authentication system

i'm using the django built in authentication system and in my login template i have this code :
login.html:
{% block title %}Login{% endblock %}
{% block content %}
<h2>Login</h2>
{% if user.is_authenticated%}
you are already logged in
{% else %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
{% endif %}
{% endblock %}
but what i really want to do is to redirect the user to the home page if he tries to access login page while already logged in, but i am new to django so i don't know how to do that.
For django>=1.11 you can set redirect_authenticated_user parameter to True in its url in url_patterns to do the redirect, like this:
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^login/', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'),
]
read the document for more information.
and also set LOGIN_REDIRECT_URL in your setting file to your index url or its name:
LOGIN_REDIRECT_URL = '/index/'
In your `settings.py' add this:
LOGIN_REDIRECT_URL = 'index'
if the url name of your index is 'index', else put the correct url name
You can do it in your views.py file.
def login(request):
if request.method =="get":
if request.user.is_authenticated:
return render(// youre code)

Categories