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 %}
Related
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)})
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)
In my Django project, I am trying to register a student. When I submit the registration form on the live server I got a Page not found (404) error. But it working perfectly on my local server. I think I got this problem for upload image because when I try to submit another form without any image it saves on the database perfectly.
This is the exact error I got.
Page not found (404)
Request Method: POST
Request URL: https://xxxxx.com/accounts/registration/student/
Raised by: accounts.views.register_student
Using the URLconf defined in coaching.urls, Django tried these URL patterns, in this order:
ad/
accounts/
students/
teachers/
admin/
vedios/
[name='landingpage']
error [name='error_page']
^media\/(?P<path>.*)$
The current path, registration/student/, didn't match any of these.
This is the URL patterns related to this problem
from django.urls import path,include
from accounts import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('registration/student/', views.register_student, name='student_registration'),
path('registration/teacher/', views.register_teacher, name='teacher_registration'),
path('login/', views.login_view, name='login'),
path('logout/',views.logout_view,name="logout")
]
And this the view's method for that I got this error.
def register_student(request):
context={}
if request.POST:
form = RegistrationForm(request.POST,request.FILES)
if form.is_valid():
user = form.save(commit=False)
user.is_student = True
user.save()
# login(self.request, user)
return redirect('login')
else:
context['form'] = form
else:
form = RegistrationForm()
context['form'] = form
return render(request, 'accounts/student_register.html',context)
And finally, this is the RegistrationForm() method
class RegistrationForm(UserCreationForm):
"""docstring for ."""
image = forms.ImageField(label="Upload Your Image",widget = forms.FileInput(attrs={'class':'form-control','placeholder':"Your Image"}))
name = forms.CharField(label="Full Name",widget= forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Full Name'}))
email = forms.EmailField(label="Email Address",help_text="We'll never share your email with anyone else.", widget= forms.EmailInput(attrs={'class': 'form-control','aria-describedby':'emailHelp','placeholder':'Enter email'}))
phone_number = forms.CharField(label="Phone Number",widget= forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Phone Number'}))
address = forms.CharField(label="Current Address",widget= forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Current Address'}))
password1 = forms.CharField(label="Password",help_text="Don't share your password with others",widget= forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Enter Password'}))
password2 = forms.CharField(label="Confirm Password",help_text="",widget= forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Re-Enter Password'}))
class Meta:
"""docstring for ."""
model = get_user_model()
fields = ('image','name','email','phone_number','address','password1','password2')
This is the html form page I used
<form method="post" enctype="multipart/form-data" action="{%url 'student_registration' %}">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
{% if field.help_text %}
<small id="{{field.id_for_label}}" class="form-text text-muted">{{ field.help_text|safe }}</small>
{% endif %}
</div>
{% endfor %}
<div class="text-center">
<input type="submit" class="btn btn-success" value="Register as student"><a class="btn btn-secondary ml-1" href="{% url 'teacher_registration' %}">Register as teacher</a>
</div>
</form>
This is my settings.py file if you need this.
"""
Django settings for coaching project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.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
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
STATIC_DIR = os.path.join(BASE_DIR, "static")
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'og3h%0!(#zaxic7ap%o5)#pc8%-2a4(+wq0n!8it^0dssbst+('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['xxx.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'mainadmin',
'student',
'teacher',
'accounts',
'vedios',
'classlinks',
'frontend',
'notices',
'notification'
]
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 = 'coaching.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'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 = 'coaching.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'accejakr_coaching',
'USER': 'accejakr_coaching',
'PASSWORD': 'a3w~$Zk%H_TP',
'HOST': 'localhost',
'PORT': 3306
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_USER_MODEL = 'accounts.User'
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.1/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.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = 'media/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
This is the global URLs patterns of my project
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('ad/', admin.site.urls),
path('accounts/', include('accounts.urls')),
path('students/', include('student.urls')),
path('teachers/', include('teacher.urls')),
path('admin/', include('mainadmin.urls')),
# path('class/', include('classlinks.urls')),
path('vedios/', include('vedios.urls')),
path('', include('frontend.urls')),
# path('notifications/', include('notify.urls', 'notifications')),
]
urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root =settings.MEDIA_ROOT)
The problem is in the settings.py.
You have to change this code
MEDIA_URL = 'media/'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media')
to this code
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
This should work OK now.
There is Problem
Hello I'm creating a project, I created a register form, but I tried to create an email authentication submit button in the form near EmailInput, but I could not find it
I'm currently using {% bootstrap_form form%} to render automatically in a register form
What I want
I would like to have the Submit Email Authentication button appear on the form near EmailInput,
When the user clicks the Send Email Authentication button, it sends an authentication email to the user's email
Then, when the user clicks the link attached to the mail, the user is informed that the confirmation has been made on the register window
and When the user clicks the sign up button, the registration is completed
What I've tried
I created a register form using UserCreationForm supported by django,
I tested using gmail smtp to send email from django. It works well
The Code in /django-blog/blog/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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y$a)3faq3*h#r0g5b^cxsw^lgdxbbu&#lsqek!_0ju+d*c!ups'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 내가 만든 앱
'my_blog',
#USER APP
'users',
# Apps created by others
'bootstrap3',
# Restful api Framework
'rest_framework',
# Social
'social_django',
"social_core",
]
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',
'social_django.middleware.SocialAuthExceptionMiddleware',
]
ROOT_URLCONF = 'blog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'blog/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',
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
},
},
]
WSGI_APPLICATION = 'blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/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.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/2.1/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/2.1/howto/static-files/
STATIC_URL = '/static/'
# 내 설정
LOGIN_URL = '/users/login/'
# django-bootstrap3 settings
BOOTSTRAP3 = {
'include_jquery' : True,
}
# Heroku settings
cwd = os.getcwd()
if cwd == '/app' or cwd[:4] == '/tmp':
import dj_database_url
DATABASES = {
'default': dj_database_url.config(default='postgres://localhost')
}
# request.is_secure()에 대해 'X-Forwarded-Proto'를 우선적으로 사용한다.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# 모든 호스트 헤더를 허용한다.
ALLOWED_HOSTS = ['choco-blog.herokuapp.com']
DEBUG = False
# Static asset configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# AUTHENTICATION_BACKENDS settings
AUTHENTICATION_BACKENDS = [
'social_core.backends.open_id.OpenIdAuth', # for Google authentication
'social_core.backends.google.GoogleOpenId', # for Google authentication
'social_core.backends.google.GoogleOAuth2', # for Google authentication
'social_core.backends.github.GithubOAuth2', # for Github authentication
'social_core.backends.kakao.KakaoOAuth2', # for Kakaotlak authentication
'django.contrib.auth.backends.ModelBackend', # Django 기본 유저모델
]
SOCIAL_AUTH_URL_NAMESPACE = 'social'
LOGIN_REDIRECT_URL='/'
# Google login
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY ='843562355161-3atsmmageh4j0758g4am6e4ncefckupf.apps.googleusercontent.com'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET ='ZVKObQDFPhTdz1GXWfaYuulq'
# Github Login
SOCIAL_AUTH_GITHUB_KEY = 'e2fc4a9cf1f213b0a10f'
SOCIAL_AUTH_GITHUB_SECRET = 'c4d1efe407175230a47d7fa547db0667b4f08721'
# Kakaotalk login
SOCIAL_AUTH_KAKAO_KEY = '490c43bc63dd3351e6068f6bbf4e0bfd'
# Verification Email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = 'True'
EMAIL_PORT = 587
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'user#gmail.com'
EMAIL_HOST_PASSWORD = os.environ.get('KBOARD_PASSWORD')
SERVER_EMAIL = 'user#gmail.com'
DEFAULT_FROM_MAIL = 'my_blog'
/django-blog/user/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
class UserCreationForm(UserCreationForm):
"""유저 가입양식 정의"""
first_name = forms.CharField(widget = forms.TextInput(
attrs={'class': 'form-control', 'placeholder': 'First Name'}),
max_length=32, help_text='First name', label='이름')
last_name = forms.CharField(widget =
forms.TextInput(attrs={'class':'form-control', 'placeholder':'Last Name'}),
max_length=32, help_text='Last name', label='성')
email = forms.EmailField(widget = forms.EmailInput(attrs=
{'class':'form-control', 'placeholder': 'Email',}),
max_length=64, help_text='유효한 이메일 주소를 입력하세요',
error_messages={'invalid': ("Email 이 비어있습니다")},)
terms = forms.BooleanField(
label =('My blog of service'),
widget=forms.CheckboxInput(
attrs={
'required': 'True',
}
),
error_messages={
'required':('당신의 My blog of service 에 대한 동의가 필요합니다. ')
}
)
privacy = forms.BooleanField(
label=('Privacy policy'),
widget=forms.CheckboxInput(
attrs={
'required':'True',
}
),
error_messages={
'required=':('당신의 Privacy policy 동의가 필요합니다.')
}
)
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields + ('first_name',
'last_name', 'email')
/django-blog/user/urls.py
"""users 앱의 URL 패턴을 정의하는 파일"""
from django.urls import re_path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'users'
urlpatterns = [
# 로그인 페이지
re_path(r'^login/$',
auth_views.LoginView.as_view(template_name='users/login.html'),
name = 'login'),
# 로그아웃 페이지
re_path(r'^logout/$',views.logout_view, name='logout'),
# 유저 등록 페이지
re_path(r'^register/$', views.register, name='register'),
]
/django-blog/user/templates/user/register.html
{% extends "my_blog/base.html" %}
{% load bootstrap3 %}
{% block header %}
<h2>회원가입</h2>
{% endblock %}
{% block content %}
<form method='post' action="{% url 'users:register' %}" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button name="submit" class="btn btn-success">유저 등록하기</button>
{% endbuttons %}
<input type="hidden" name="text" value="{% url 'my_blog:index' %}">
</form>
{% endblock %}
/django-blog/user/views.py
from django.shortcuts import render
from django.urls import reverse
from django.contrib.auth import login, logout, authenticate
from django.http import HttpResponseRedirect
from .forms import UserCreationForm
def logout_view(request):
"""사용자 로그아웃"""
logout(request)
return HttpResponseRedirect(reverse('my_blog:index'))
def register(request):
"""새 사용자를 등록한다."""
if request.method != 'POST':
# 빈 폼을 보여준다.
form = UserCreationForm()
else:
# 전송받은 폼을 처리한다.
form =UserCreationForm(data = request.POST)
if form.is_valid():
new_user = form.save()
# 사용자를 로그인시키고 홈페이지로 리다이렉트한다.
authenticated_user = authenticate(username=new_user.username,
password=request.POST['password1'])
login(request, authenticated_user)
return HttpResponseRedirect(reverse('my_blog:index'))
context = {'form' : form}
return render(request, 'users/register.html', context)
I have attached a register screen photo
enter image description here
If you need information to solve this problem, please ask me :)
You can use Widget Tweaks. With help of this you can add classes to your input and edit other attribute also. Here is good tutorial.
I think you can customize it in a bootstrap field:
https://django-bootstrap3.readthedocs.io/en/latest/templatetags.html?highlight=layout#bootstrap-field
Like this with new css w3-css
{% bootstrap_form form layout='inline' form_group_class='w3-input w3-border-0 w3-large'%}
I project is supposed to be able to upload an image with a name then display the uploaded image and name. I have tried looking online for an answer to my problem but have found none. The problem basically is my django webapp is not saving a name(CharField)an and image(ImageField) to the database. I tried to do everything necessary for it to work but it's still not working. The following is my project. Thanks for your time.
My projectl directories:
Image shows project structure
views.py
from django.shortcuts import render
from ImgApp.forms import ImageForm
from ImgApp.models import ImageModel
from django.http import HttpResponseRedirect
def upload(request):
if request.method == "POST":
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('ImgApp:home')
else:
form = ImageForm()
con = {"var_form": form}
return render(request, 'upload.html', con)
models.py
from django.db import models
class ImageModel(models.Model):
name = models.CharField(max_length=44)
image = models.ImageField(upload_to='media/',null=True)
def __str__(self):
return self.name
forms.py
from django import forms
from ImgApp.models import ImageModel
class ImageForm(forms.ModelForm):
class Meta:
model = ImageModel
fields = "__all__"
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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'e3d)3&+&3!xkh_zz_l#uc9ly8uh#wio1g+zh59_mt&v-0xyubp'
# 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',
'debug_toolbar',
'ImgApp',
]
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',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
ROOT_URLCONF = 'ImgProject.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',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'ImgProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/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.11/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.11/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.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATICFILES_DIR = [
os.path.join(BASE_DIR,'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = "/media/"
INTERNAL_IPS = ['127.0.0.1']
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from ImgApp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^app/',include('ImgApp.urls')),
url(r'^$',views.home),
url(r'^upload/$',views.upload),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
upload.html
<form method="post" enctype="multipart/form-data" action="{% url 'ImgApp:index' %}">
{% csrf_token %}
{{var_form.as_p}}
<input type="submit" value="upload" class="btn btn-primary">
</form>
index.html
<!DOCTYPE html>
{% load static %}
........
{% if var_db %}
{% for img in var_db %}
<b>Name:</b>{{img.name}}
<br>
<img src="{{MEDIA_URL}}/{{img.image}}" alt="Image here" height="200" width="300">
{% endfor %}
{% else %}
<p>No Images uploaded yet</p>
<p>Fill this lonely area with happiness</p>
{% endif %}
It looks as if you are posting the form to the index. You should post it to the upload view.
<form method="post" enctype="multipart/form-data" action="{% url 'ImgApp:upload' %}">
You need to add a name to the URL pattern for this to work.
url(r'^upload/$',views.upload, name='upload'),
In your view, you need to move the context line out of the else block so that it runs for GET and POST request. That means that if the form is invalid, you'll see the errors on the template.
def upload(request):
if request.method == "POST":
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('ImgApp:home')
else:
form = ImageForm()
context = {"form": form}
return render(request, 'upload.html', context)
I've renamed a couple of variables to match the usual Django style (con to context, var_form to form). If you rename var_form, remember to update your template as well.