I'm trying to use django messages to notify user if form was submitted successfully or not. But nothing pops up when I submit the form no matter what. I've gone through the views.py code and template and I don't seem to anything wrong. I've even tried changing the default messages backend storage to session yet nothing.
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
views.py:
from django.shortcuts import render, HttpResponse, HttpResponseRedirect, redirect
from django.contrib import messages
from .forms import MyUserCreationForm
import bcrypt
def register(request):
if request.method == "POST":
# Populate form using submitted data
form = MyUserCreationForm(request.POST)
if form.is_valid():
# Clone form model
user = form.save(commit=False)
password = user.password
# Validate password length
if len(password) > 25:
messages.error(
request, "PASSWORD MUST BE LESS THAN OR EQUAL TO 25 CHARACTER LENGTH")
# Hash user password
bytes = password.encode('utf-8')
salt = bcrypt.gensalt()
hash = bcrypt.hashpw(bytes, salt)
# Save modified form to database
user.password = hash
user.save()
messages.success(request, "ACCOUNT CREATED SUCCESSFULLY!")
messages.add_message(request, messages.INFO,
'Thanks for reaching out! We will be in contact soon!',
extra_tags='ex-tag')
return redirect('register')
# Create empty form
form = MyUserCreationForm()
return render(request, 'register.html', {'form': form})
templates/register.html:
{% extends "layout.html" %}
{% block title %}
Testing Registration
{% endblock %}
{% load static %}
{% load crispy_forms_tags %}
{% block main %}
<div class="container p-2 px-4 p-md-3">
<div class="container-fluid p-0" style="height: 40px;"></div>
</div>
<div class="container">
<div class="mx-auto ">
<form method="POST" action="/register/">
{% csrf_token %}
{{ form | crispy }}
<input type="submit" value="Submit" class="btn btn-primary mb-3">
</form>
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger d-flex align-items-center alert-dismissible fade show" role="alert">
<svg class="bi flex-shrink-0 me-2" role="img" aria-label="Danger:">
<use xlink:href="#exclamation-triangle-fill" />
</svg>
<div>
{{ message }}
</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}
</div>
</div>
{% endblock %}
settings.py:
"""
Django settings for setup project.
Generated by 'django-admin startproject' using Django 4.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-)9-rgl0du=62az)siilt%1qgacbtmgxt!ew97t8$&nzd1v)x53'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite.apps.MysiteConfig',
'crispy_forms',
"crispy_bootstrap5",
"phonenumber_field",
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'setup.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'setup.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'emmanuel',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Crispy-forms template pack
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
CRISPY_TEMPLATE_PACK = 'bootstrap5'
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.ScryptPasswordHasher',
]
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
Documentations:
If you’re using the context processor, your template should be
rendered with a RequestContext. Otherwise, ensure messages is
available to the template context.
https://docs.djangoproject.com/en/4.1/ref/contrib/messages/#displaying-messages
you don't send messages or RequestContext in your context:
return render(request, 'register.html', {'form': form})
Probably it should be something like that:
return render(request, 'register.html', {'form': form, 'messages':get_messages(request)})
Related
Regarding the question after the CURD Update test,
The bottom is my program. I create the editing part but when I want to save it after editing, it will keep reminding me that the email part is duplicated, but if I have id=5 (http://127.0.0.1:5757/polls) /5/edit/) Edit, but if I change the email, it will be a new ID after the update. How can I change it? Could you please remind me which error is wrong?
error message: This mail box already exists in the Store.
ps: You can read the pictures to understand the situation first.
update test Before modification: Before the modification, my content was empty .
update test after modification : After the modification, I fill in the text into the content field, it will show that This mail box already exists in the Store.
--models.py--
class Store(models.Model):
store_name = models.CharField(max_length=10)
store_holder = models.CharField(max_length=50)
store_phoneNumber = models.CharField(max_length=10)
store_address = models.CharField(max_length=100)
▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
store_email = models.EmailField(max_length=60,
default='',
help_text='need u', verbose_name='email account',
unique=True, )
▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
store_notes = models.TextField(blank=True, default='')
def __str__(self):
return self.store_name
def get_absolute_url(self):
return reverse('polls:polls_detail', kwargs={'id': self.id})
--froms.py--
from django import forms
from .models import *
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class StoreForm(forms.ModelForm):
class Meta:
model = Store
fields = '__all__'
--views.py--
def polls_edit(request, id=None):
# basic use permissions
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Store, id=id)
form = StoreForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
# message success
return HttpResponseRedirect(instance.get_absolute_url())
context = {
'title': 'edit',
'instance': instance,
'form': form,
}
return render(request, 'polls/polls_form.html', context)
--urls.py--
from django.urls import path
from . import views
from django.contrib.auth import views as auth_view
# Create your urls here.
app_name = 'polls'
urlpatterns = [
path('profile/', views.polls_profile, name='polls_profile'), # http://127.0.0.1:8000/posts/list
path('edit/', views.polls_profile_edit, name='polls_profile_edit'), # http://127.0.0.1:8000/posts/3/edit/
path('changePassword/', views.changePassword, name='changePassword'), # http://127.0.0.1:8000/posts/3/edit/
# CURD
path('<int:id>/detail/', views.polls_detail, name='polls_detail'), # http://127.0.0.1:8000/posts/9/
path('create/', views.polls_create, name='polls_create'), # http://127.0.0.1:8000/posts/create
path('list/', views.polls_list, name='polls_list'), # http://127.0.0.1:8000/posts/list
path('<int:id>/edit/', views.polls_edit, name='polls_edit'), # http://127.0.0.1:8000/posts/3/edit/
# path('<int:id>/delete/', views.polls_delete, name='polls_delete'), # http://127.0.0.1:8000/posts/delete
path('delete/', views.polls_delete, name='polls_delete'), # http://127.0.0.1:8000/posts/delete
# else views
path('contact/', views.contact, name='contact'),
# path('', views.login_redirect, name='login_redirect'),
# path('register/', views.registration_view, name='register'),
path('register/', views.register, name='register'),
path('', views.starter, name='starter'),
path('login/', auth_view.LoginView.as_view(template_name='registration/login.html'), name='login'),
path('logout/', auth_view.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'),
# pw change
path('password_change/', auth_view.PasswordChangeView.as_view(), name='password_change'),
# pw change success
path('password_change/done/', auth_view.PasswordChangeDoneView.as_view(), name='password_change_done'),
# forget pw / set pw
path('password_reset/', auth_view.PasswordResetView.as_view(), name='password_reset'),
# forget pw / set pw success
path('password_reset/done/', auth_view.PasswordResetDoneView.as_view(), name='password_reset_done'),
#
path('reset/<uidb64>/<token>/', auth_view.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
# pw already change
path('reset/done/', auth_view.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
# pw sent
# path('reset_password_sent/', auth_view.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]
--polls_forms.html
{% extends 'base_generic.html' %}
{% block body %}
<title>Form Page</title>
<!-- Content Wrapper. Contains page content -->
<div class='content-wrapper'>
{% if user.is_authenticated %}
<!-- Content Header (Page header) -->
<div class='content-header'>
<div class='container-fluid'>
<div class='row mb-2'>
<div class='col-sm-6'>
<h1 class='m-0'>Form Page</h1>
</div><!-- /.col -->
<div class='col-sm-6'>
<ol class='breadcrumb float-sm-right'>
<li class='breadcrumb-item'><a href='#'>Form</a></li>
<li class='breadcrumb-item active'>Form Page</li>
</ol>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</div>
<!-- /.content-header -->
<!-- Main content -->
<div class='content'>
<div class='container-fluid'>
<div class='row'>
<div class='col-lg-6'>
<div class='card'>
<div class='card-body'>
<h1>Test</h1>
<form method='post' action='{% url 'polls:polls_create' %}'>
{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='save'>
</form>
<div class='main'>
<!-- Display attributes of instance -->
{{ data.city }} <br/>
{{ data.description }}
</div>
<h5 class='card-title'>user account : {{ user|capfirst }}</h5><br>
{% if author_list %}
<ul>
{% for author in author_list %}
<li>
<a href='{{ author.get_absolute_url }}'>
{{ author }} ({{ author.date_of_birth }} -
{% if author.date_of_death %}{{ author.date_of_death }}{% endif %})
</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no authors available.</p>
{% endif %}
</div>
<!-- /* card-body -->
</div>
</div>
<!-- /.col-md-6 -->
</div>
<!-- /.row -->
</div><!-- /.container-fluid -->
</div>
<!-- /.content -->
{% else %}
<!-- Content Wrapper. Contains page content -->
<div class='content-wrapper pt-5'>
<h4>Register</h4>
</div>
<!-- /.content-wrapper -->
{% endif %}
</div>
<!-- /.content-wrapper -->
{% endblock %}
--settings.py--
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-7r4mj*$^bv(zj##+$d42&k$ax_6ps3*f=wc8f)96s1yn3!%^4$'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
'accounts',
'shops',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'restA_db',
'USER': 'postgres',
'PASSWORD': 'postgres5',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'zh-Hant'
TIME_ZONE = 'Asia/Taipei'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
'/var/www/static/',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/dist/media_cdn')
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Redirect to home URL after login (Default redirects to /accounts/profile/)
LOGIN_REDIRECT_URL = '/polls/'
LOGIN_URL = '/accounts/login/'
# LOGOUT_REDIRECT_URL = '/accounts/logout/'
# crispy_forms
# CRISPY_TEMPLATE_PACK = 'bootstrap4'
# STMP Configuration
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'georgiawang5332#gmail.com' # sender account
EMAIL_HOST_PASSWORD = '0704gta93julro' # sender password
--urls.py--
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
# from django.contrib.auth.views import login, logout
urlpatterns = [
path('polls/', include('polls.urls')),
path('shops/', include('shops.urls')),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
#Add URL maps to redirect the base URL to our application
from django.views.generic import RedirectView
urlpatterns += [
path('', RedirectView.as_view(url='/polls/', permanent=True)),
]
# Add Django site authentication urls (for login, logout, password management)
urlpatterns += [
path('accounts/', include('django.contrib.auth.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So, I have been trying to do this problem for a couple of days, but I seem to be having no luck, in actually solving it.
For my side-project, I am creating a student grade management system in Django, and the problem that I am getting is that everytime the user clicks on the signup button on the homepage/login page, I get an error, because I haven't re-routed the user successfully. Specifically, the error I get is that it says, Page not Found.
The page that I am trying to re-route the user to is in another app. So, I'm trying to route the user to the base url of that app, which from there, it will pop open a view.
Here is the code for my urls.py on the loginpage/homepage (App1)
from django.urls import re_path
from django.shortcuts import redirect
# import signUpPage.views as signupview
from . import views
urlpatterns = [
re_path(r'^$', views.login, name='login'),
# re_path('signUpPage', signupview.register, name='signUpPage')
# re_path('')
]
Here is the code for my forms.py on the loginpage/homepage (App1)
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Fieldset, Layout
class loginForm(forms.Form):
UserName = forms.CharField(
label="Username",
help_text="Please enter your username",
widget=forms.TextInput(attrs={"placeholder":"Username"}),
required=False
)
Password = forms.CharField(
label="Password",
help_text="Enter your password",
widget=forms.TextInput(attrs={"placeholder":"Password"}),
required=False
)
Here is the code for my views.py on the loginpage/homepage (App2)
from django.shortcuts import render, redirect, HttpResponseRedirect
from . forms import loginForm
from django.urls import re_path
from signUpPage.views import register
# from .models import <Insert whatever it is you want to import, but it might not be nexessary>
def login(request):
if request.method == "POST":
redirect('signUpPage')
if request.POST.get("signup"):
register()
else:
form = loginForm(request.GET)
return render(request, 'homePage/homePage.html', {"form": form})
Here is the html for the loginpage/homepage (App1)
{% load static%}
{% load crispy_forms_tags %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}Home{% endblock %}</title>
<link rel="shortcut icon" type="image/png" href="{% static 'homePage/favicon.png' %}">
{% load bootstrap4 %}
<link href="../../static/homePage/homePage.css" type="text/css" rel="stylesheet">
</head>
<body>
<div class="homePage-background"> <!-- animation area-->
<svg class="container-sm" width="25%" height="760" style="position:absolute; margin-left: 35%; margin-top:35px">
<rect id="loginRect" width="100%" height="100%" rx="40px" ry="40px" style="fill: cornflowerblue; stroke: pink; stroke-opacity: 0.0; stroke-width: 3px; "/>
<foreignObject height="760" width="100%">
<div class="loginpage-form">
{% block content %}
<form action="homePage/forms.py" method="post">
{% csrf_token %}
{{forms|crispy}}
{% for field in form %}
<div class="fields">
<div class="label">{{field}}</div>
</div>
{% endfor %}
<button type="submit" name="login" class="btn btn-success" id="loginButton" formmethod="post">Login</button>
<button type="submit" name="signup" class="btn btn-success" id="signUpButton" formmethod="get">Sign Up</button>
</form>
{% endblock %}
</div>
</foreignObject>
</svg>
<ul class="animation"> <!-- box area-->
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
</html>
Here is the code for my urls.py on the signuppage (App2)
from django.urls import re_path
from . import views
urlpatterns=[
re_path('^$', views.register, name='register'),
]
Here is the html for the signup page (App2)
<!DOCTYPE html>
<html lang="en">
{% load static %}
{% load crispy_forms_tags %}
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../../static/signUpPage/signUpPage.css" type="text/css"/>
{% load bootstrap4 %}
<title>{% block title %}SignUp{% endblock %} </title>
</head>
<body>
<div id="backGround">
<div class="container-sm">
<h2>Sign Up</h2>
</div>
<div id="inputs">
<img src="../../static/signUpPage/SignUp-Person.png" alt="Signup Person Image" id="image">
<p id="inputText">Please enter your Email Address,<br/> Username, and Password.</p>
<div class="form-group">
{% block content %}
<form method="post">
{% csrf_token %}
{{ forms|crispy}}
{% for field in form %}
<div class="fields">
<label for="{{ field.id_for_label }}" class="label">{{field.html_name}}</label>
{{field}}
</div>
{% endfor %}
<button type="submit" class="btn btn-success" id="signup-button" value="user-credentials">Sign Up</button>
</form>
{% endblock %}
</div>
</div>
</div>
</body>
EDIT: Here is the settings.py file
"""
Django settings for GradingSystem project.
Generated by 'django-admin startproject' using Django 3.0.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'h#yn1kty8in#qx#f#y4k6n$mzyc6q9o$ovlt5p=u=974ny#nq-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'signUpPage.apps.SignuppageConfig',
'homePage.apps.HomepageConfig',
'grades.apps.GradesConfig',
'newcourse.apps.NewcourseConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap4',
'crispy_forms',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'GradingSystem.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '/templates'), os.path.join(BASE_DIR, 'homePage', 'templates', 'homePage'),
os.path.join(BASE_DIR, 'signUpPage', 'templates', 'signUpPage'),
os.path.join(BASE_DIR, 'grades', 'templates', 'grades')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'GradingSystem.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'student_accounts',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
#This asks me for my password on runtime, because I do not feel comfortable writing my password here.
'PASSWORD': input("Password:"),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
in your urls.py file, you can add a constant with the name app_name="app_name" and in your HTML link or button, you can simply use the url tag like {% url app_name:path_name %}.
It tells the Django which specific urls.py file you are talking about.
I have pushed my app to a production build using Heroku and since I was previously logged in, I am taken to my home page as my current user, however if I go to logout it re-renders the homepage and I get a messages.error of 'User does not exist'. The app can be found at https://micro-blog-site.herokuapp.com and other details can be found below.
EDIT: I was able to logout through the admin app and it appears that neither the login, or register links work.
Here are the Heroku logs when clicking Logout
2019-05-21T20:45:28.529489+00:00 heroku[router]: at=info method=GET path="/" host=micro-blog-site.herokuapp.com request_id=640f08ae-f865-47ac-bb92-5f3cef07250d fwd="174.115.122.102" dyno=web.1 connect=0ms service=33ms status=200 bytes=2532 protocol=https
2019-05-21T20:45:28.433881+00:00 heroku[router]: at=info method=GET path="/logout" host=micro-blog-site.herokuapp.com request_id=24447334-9a94-4db6-98be-97033077a513 fwd="174.115.122.102" dyno=web.1 connect=0ms service=10ms status=302 bytes=376 protocol=https
2019-05-21T20:45:28.432504+00:00 app[web.1]: True
2019-05-21T20:45:28.435933+00:00 app[web.1]: 10.93.215.14 - - [21/May/2019:16:45:28 -0400] "GET /logout HTTP/1.1" 302 0 "https://micro-blog-site.herokuapp.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.1 Safari/605.1.15"
2019-05-21T20:45:28.531462+00:00 app[web.1]: 10.93.215.14 - - [21/May/2019:16:45:28 -0400] "GET / HTTP/1.1" 200 2077 "https://micro-blog-site.herokuapp.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.1 Safari/605.1.15"
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import login, logout, authenticate
from .forms import CustomUserCreationForm, CustomAuthForm, PostForm
from django.contrib import messages
from .models import Post, User, UserProfile
from datetime import datetime
# Create your views here.
############################################
#
# Homepage view with form to create a post
# and display a feed of post by most recent
# published
#
############################################
def homepage(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.published = datetime.now()
post.save()
return redirect('micro:homepage')
else:
messages.error(request, "Error!")
form = PostForm()
if request.user.is_authenticated:
return render(request, 'micro/home.html', {"posts":Post.objects.order_by('-published'), "form":form, "following":[following for following in request.user.userprofile.follows.all()]})
else:
return render(request, 'micro/home.html', {"posts":Post.objects.order_by('-published'), "form":form})
###########################################
#
# Register view with a form to register a
# user
#
##########################################
def register(request):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save()
UserProfile.objects.create(user=user)
username = form.cleaned_data.get('username')
login(request, user)
messages.success(request, f"New account created: {username}")
return redirect('micro:homepage')
else:
for msg in form.errors:
for message in form.errors[msg]:
messages.error(request, f"{message}")
return render(request, 'micro/register.html', {"form":form})
form = CustomUserCreationForm()
return render(request, 'micro/register.html', {"form":form})
###########################################
#
# Logout request, redirects to homepage
#
###########################################
def logout_request(request):
logout(request)
return redirect('micro:homepage')
###########################################
#
# Login view with a form for a user to
# enter username and password
#
##########################################
def login_request(request):
if request.method == "POST":
form = CustomAuthForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect(f'/{user.username}')
else:
messages.error(request, "Invalid username or password")
else:
messages.error(request, "Invalid username or password")
form = CustomAuthForm()
return render(request, 'micro/login.html', {"form":form})
#########################################
#
# Profile view displays the user profile
# of a specified user and their posts
#
#########################################
def profile(request, username):
print(request.user.is_authenticated)
if request.user.is_authenticated:
if username in [user.username for user in User.objects.all()]:
userposts = Post.objects.filter(user__username=username).order_by('-published')
return render(request, 'micro/profile.html', {"userposts":userposts, "username":username})
else:
messages.error(request, "User does not exist")
return redirect('micro:homepage')
else:
messages.error(request, "Login or signup to view this page")
return redirect('micro:homepage')
settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'yd#19!!nf4)-4s9(f=y9ou41s2$6g&(#4(*o!4b-zgkeip(^5-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['micro-blog-site.herokuapp.com','127.0.0.1', '0.0.0.0']
# Allows creation of custom User model
AUTH_USER_MODEL = 'micro.User'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'micro.apps.MicroConfig',
]
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Logging
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
},
},
}
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Toronto'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
PROJECT_ROOT = os.path.join(os.path.abspath(__file__))
APP_DIR = os.path.join(BASE_DIR, 'micro')
STATIC_ROOT = os.path.join(APP_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra lookup directories for collectstatic to find static files
STATICFILES_DIRS = (
os.path.join(APP_DIR, 'static'),
)
# Add configuration for static files storage using whitenoise
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
import dj_database_url
prod_db = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(prod_db)
urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
app_name = 'micro'
urlpatterns = [
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"),
path('<username>', views.profile, name="profile"),
]
header.html
<head>
{% load static %}
<link href="{% static 'micro/css/materialize.css' %}" rel="stylesheet">
<link href="{% static 'micro/css/styles.css' %}" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Titillium+Web" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="{% static 'micro/js/materialize.js' %}"></script>
<!-- <script src="{% static 'micro/js/jquery.js' %}"></script>-->
</head>
<body class="green lighten-5">
{% include 'micro/includes/nav.html' %}
<br>
{% include 'micro/includes/messages.html' %}
<div class="container">
<br>
{% block content %}
{% endblock %}
</div>
</body>
nav.html
<nav class="green lighten-3">
<div class="nav-wrapper">
Logo
<ul id="nav-mobile" class="right hide-on-med-and-down">
{% if user.is_authenticated %}
<li>{{user.username|title}}</li>
<li>Logout</li>
{% else %}
<li>Login</li>
<li>Register</li>
{% endif %}
</ul>
</div>
</nav>
home.html
{% extends 'micro/header.html' %}
{% block content %}
<div class="row">
{% if request.user.is_authenticated %}
<div class="col l4 m8 offset-m2 s12 center-align">
<h2>Welcome {{user.username}}!</h2>
{% include 'micro/includes/post-form.html' %}
</div>
<div class="col l7 offset-l1 m8 offset-m2 s12 center-align">
<h2>This is your feed</h2><br>
{% include 'micro/includes/feed.html' %}
</div>
{% else %}
<div class="col m6 offset-m3 s12 center-align">
<h3>Welcome!</h3>
Login
<p class="col s2"><strong>or</strong></p>
Register
</div>
{% endif %}
</div>
</div>
{% endblock %}
I am trying to figure out how sessions work. Basically I am trying to make a restaurant menu and store ordered food into session for further use. However, I ran into a problem and I cant figure out what might be the problem.
The problem is that if I submit the form 1st time. The success view shows the correct data.
I click Submit (pridat) and it works correctly
The output is:
('2', 1)
Where number 2 is food ID and 1 is the quantity.
Then I go back to the menu and I want to update the quantity to lets say 3
I change quantity (mnozstvo) to 3 and submit
But the output is still:
('2', 1)
The weirdest thing that has me confused is the fact that for example different food, even though it should be generated the same way works and updates just fine.
If I want to "order" multiple things it works fine with some and sometime one or multiple just refuse to update properly. As I am writing this 3 out of 4 works just fine.
('3', 5)('4', 8)('1', 15)('2', 1)
I can change 3-5, 4-8 and 1-15 but the 2-1 just never ever changes.
If I restart the built in django server sometimes different pair does not update properly. This time it is 2-1 but I also had an issue that 3-5 would not update.
So I would be really happy if someone could tell me what am I doing wrong? I know I am not letting django generate form but I rather do it manually in html, but that should not be the problem, should it?
menu.html with form separated for better visibility
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'restaurant/style.css' %}" />
{% if all_food_list %}
<center>
<ul>
<li>Home</li>
<li>Menu</li>
<li style="float:right"><a class="active" href="#about">Objednavka</a></li>
</ul>
<div class="clearfix">
{% for food in all_food_list %}
<div class="div1">
<center>
<img src="{{ MEDIA_URL }}{{ food.picture.url }}" alt="{{ food.name }}">
<h2> {{ food.name}} </h2>
<p>Cena: {{ food.price }}czk</p>
<p>Hmotnost: {{ food.weight}}g</p>
<p>Zlozenie: {{ food.ingredients}}</p>
<form action="/get_food/" method="post">
{% csrf_token %}
Mnozstvo: <input id="test" type="number" name="quantity" min="0" max="30" step="1" value="1">
<input type="hidden" name="food_type" value="{{ food.id }}">
<input type="submit" value="Pridat">
</form>
</center>
</div>
{% endfor %}
TODO: Funkcny formular, view pre objednavku, nastavit limity div-ov.
</div>
</center>
{% else %}
<p>No food available.</p>
{% endif %}
My views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from .models import Food
from .forms import FoodOrder
def index(request):
template = loader.get_template('restaurant/index.html')
request.session.flush()
return HttpResponse(template.render(request))
def menu (request):
all_food_list = Food.objects.order_by('name')
template = loader.get_template('restaurant/menu.html')
context = {
'all_food_list': all_food_list,
}
return HttpResponse(template.render(context, request))
def get_food(request):
if request.method == 'POST':
form = FoodOrder(request.POST)
if form.is_valid():
quantity = form.cleaned_data['quantity']
#Food_type is db food id
food_type = form.cleaned_data['food_type']
#add to the session
request.session[food_type] = quantity
return HttpResponseRedirect('/success/')
else:
return HttpResponseRedirect('/index/')
def success(request):
#just writes the content of session
obsah = request.session.items()
return HttpResponse(obsah)
# Create your views here.
forms.py
from django import forms
class FoodOrder(forms.Form):
quantity = forms.IntegerField()
food_type = forms.IntegerField()
settings.py
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'restaurant.apps.RestaurantConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'iis_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'iis_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = 'D:\Škola\IIS\Projekt - Restaurace\media'
MEDIA_URL = '/media/'
I just installed Django AllAuth to my project, but cant find default login or signup page.
1) I logged out from admin panel, but still didn't find it.
2) Added signup.html template, but nothing
Picture of error in localhost/accounts http://prntscr.com/9oyu00
Here's my code:
settings.py
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'profiles',
'contact',
'crispy_forms',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'src.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'src.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
STATICFILES_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "static", "static"),
)
# Location of templates
CRISPY_TEMPLATE_PACK = 'bootstrap3'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
SITE_ID = 1
LOGIN_URL = '/accounts/login'
LOGIN_REDIRECT = '/'
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
ACCOUNT_CONFIRM_EMAIL_ON_GET = False
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGIN_URL
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
ACCOUNT_EMAIL_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = None
ACCOUNT_EMAIL_SUBJECT_PREFIX = "My subject: "
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http"
ACCOUNT_LOGOUT_ON_GET = False
ACCOUNT_LOGOUT_REDIRECT_URL = "/"
ACCOUNT_SIGNUP_FORM_CLASS = None
ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_USERNAME_FIELD = "username"
ACCOUNT_USER_MODEL_EMAIL_FIELD = "email"
ACCOUNT_USERNAME_MIN_LENGTH = 5
ACCOUNT_USERNAME_BLACKLIST = []
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_PASSWORD_INPUT_RENDER_VALUE = False
ACCOUNT_PASSWORD_MIN_LENGTH = 6
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from contact import views
urlpatterns = [
url(r'^$', 'profiles.views.home', name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^accounts/', include('allauth.urls')),
url(r'^admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
signup.html
{% extends "account/base.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% block head_title %}{% trans "Signup" %}{% endblock %}
{% block content %}
<h1>{% trans "Sign Up" %}</h1>
<p>{% blocktrans %}Already have an account? Then please sign in.{% endblocktrans %}</p>
<form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
{% csrf_token %}
{{ form|crispy }}
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<button class='btn btn-default' type="submit">{% trans "Sign Up" %} »</button>
</form>
{% endblock %}
I had the same problem. The source of it all was that I had already defined a base.html file without a 'block content' block. You need the following structure inside the body of your base.html file:
<body>
{% block body %}
{% block content %}
{% endblock content %}
{% endblock body %}
</body>
I used this source to find a suitable example, but it's not very helpful other than that. This other page was a bit better though.
Because you are requesting only the /accounts/ and if you see closely to your debugger (the screen) there is no URL for this (pattern ^accounts/ ^ ^$).
Your login & sing up page is located on /accounts/login/ and /accounts/singup/.
About editing default templates I am not able to help you with it (never used the AllAuth package) so hope someone skilled will help you.