Cannot populate django generated form in html template - python

I am trying to use django's form module to create and display a form. The following code I have executes without errors but an HTML form is not populated.
I have made sure that I am loading correct template. I also am certain that correct view is triggered when I go to a certain URL. I am posting some relevant code below from views, model, forms, and template files. I did debugging for quite a bit by trial-and-error but could not get to the root of issue.
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from app.forms import RegistrationForm
def registration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
pass
else:
''' user is not submitting the form, show them a blank registration form '''
form = RegistrationForm()
context = {'form': form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
register.html
{% extends "base.html" %}
{% block content %}
<form action="/register/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
form.py
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from app.models import Agent
class RegistrationForm(ModelForm):
username = forms.CharField( label=(u'User Name'), required=True )
first_name = forms.CharField( label=(u'First Name'), required=True )
last_name = forms.CharField( label=(u'Last Name'), required=True )
birthday = forms.DateField( label=(u'Date of birth'), required=True )
email = forms.EmailField( label=(u'Email Address'), required=True )
password = forms.CharField( label=(u'Password'), widget=forms.PasswordInput(render_value=False), required=True )
password_confirm = forms.CharField( label=(u'Confirm Password'), widget=forms.PasswordInput(render_value=False), required=True )
class Meta:
model = Agent
#exclude = ['username',]
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("That username is already taken, please select another.")
def clean(self):
if self.cleaned_data['password'] != self.cleaned_data['password_confirm']:
raise forms.ValidationError("The passwords did not match. Please try again.")
return self.cleaned_data
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class Agent(models.Model):
username = models.OneToOneField(User)
birthday = models.DateField()
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField()
def __unicode__(self):
return self.last_name + ", " + self.first_name

Had to add content block ref in base.html
{% block content %}
{% endblock %}

Related

Exception Type: KeyError when registering a new user using a custom made register model

Whenever I try to register a new user when i receive an Exception Type: KeyError error. There seem to be something wrong with the submitted password but I don't understand the issue in depth. Can someone please explain this error to me? And perhaps how to solve it as well.
The user is created, I can see that in the admin page. I also want the user to sign in when the account is created.
I appreciate all inputs! <3
My model:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, User, PermissionsMixin
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from generalpage.managers import CustomUserRegisterManager
from django.conf import settings
from generalpage.managers import CustomUserRegisterManager
class UserRegister(AbstractBaseUser, PermissionsMixin):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
username = models.CharField(_("Användarnamn"), max_length=100, null=True, unique=True)
age = models.IntegerField(_("Ålder"),null=True, blank=False)
email = models.EmailField(_("E-mail"), unique=True, null=False)
country = models.CharField(_("Land"),max_length=50, null=True, blank=True)
county = models.CharField(_("Län"),max_length=50, null=True, blank=True)
city = models.CharField(_("Stad"),max_length=50, null=True, blank=True)
profile_picture = models.ImageField(_("Profilbild"),null=True, blank=True, default="avatar.svg", upload_to = "static/images/user_profile_pics/")
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'email' # defines the unique identifier for the User model
REQUIRED_FIELDS = ["username"] # A list of the field names that will be prompted for when creating a user via the createsuperuser management command
objects = CustomUserRegisterManager()
def __str__(self):
return self.username
My form:
from dataclasses import field, fields
from django import forms
from .models import User, UserInfo, Room, UserRegister
from generalpage import models
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
# User register account page
class CustomUserRegisterForm(UserCreationForm):
class Meta:
model = UserRegister
exclude = ["is_staff", "is_active", "user", "password", "last_login", "user", "groups", "user_permissions", "date_joined", "is_superuser"]
#fields = "__all__"
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = UserRegister
exclude = ["is_staff", "is_active", "user", "password", "last_login", "user", "groups", "user_permissions", "date_joined", "is_superuser"]
#fields = "__all__"
My view:
import email
from django.http import HttpResponse
from multiprocessing import context
from pydoc_data.topics import topics
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from .forms import CustomUserRegisterForm, UserCreateRoomForm, UserInfoForm, UserProfilePageForm, RoomForm
from generalpage.models import Message, UserInfo, Room, Topic, UserRegister
from django.conf import settings
from django.contrib.auth.models import User
def createaccount(request):
page = "create-account"
form = CustomUserRegisterForm()
if request.method == "POST":
form = CustomUserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
login(request, user)
return redirect("profilesettings:profile-page")
else:
form = CustomUserRegisterForm()
context = {"form": form, "page": page}
return render(request, "generalpage/create_account.html", context)
My URLS:
from django.urls import path
from . import views
app_name = "generalpage"
urlpatterns = [
path("hem/", views.home, name="home-page"),
path("registrering/", views.registerprofile, name="register-page"),
path("logga-in/", views.loginpage, name="login-page"),
path("logga-ut", views.logoutuser, name="logoutuser"),
path("skapa-annons/", views.createroom, name="createroom-page"),
path("skapa-konto/", views.createaccount, name="createaccount-page"),
path("radera-rum/", views.deleteroom, name="deleteroom"),
path("uppdatera-rum/", views.updateroom, name="updateroom"),
]
And the manager for the custom made UserRegister model:
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import gettext_lazy as _
class CustomUserRegisterManager(BaseUserManager):
"""
Custom user model manager where username is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, username, password, **extra_fields):
"""
Create and save a User with the given username and password.
"""
if not username:
raise ValueError(_('Du måste ange ett användarnamn'))
if not email:
raise ValueError(_('Du måste ange ett email'))
if not password:
raise ValueError(_('Du måste ange ett lösenord'))
email = self.normalize_email(email)
user = self.model(username=username, email=email, password=password, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, username, password, **extra_fields):
"""
Create and save a SuperUser with the given username, email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superanvändare måste ha is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superanvändare måste ha is_superuser=True.'))
if extra_fields.get('is_active') is not True:
raise ValueError(_('Superanvändare är inte aktiv'))
return self.create_user(username, email, password, **extra_fields)
The template I'm using:
{% extends 'generalpage/main.html' %}
{% load static %}
{% block content %}
{% if page == 'login_page' %}
<p>HEELLLLLLOOOOO</p>
<div>
<form method="POST" action="">
{% csrf_token %}
<label>Användarnamn:</label>
<input type="text" name="username" placeholder="Ange ditt användarnamn" />
<label>Lösenord:</label>
<input type="password" name="password" placeholder="Ange ditt lösenord" />
<input type="submit" value="Login" />
</form>
<p>Är du inte medlem?</p>
Skapa konto
</div>
{% else %}
<div>
<form method="POST" action="">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Register" />
</form>
<p>Redan medlem?</p>
{% comment %} Logga in {% endcomment %}
</div>
{% endif %}
{% endblock content %}
The error:
KeyError at /skapa-konto/
'password'
Request Method: POST
Request URL: http://127.0.0.1:8000/skapa-konto/
Django Version: 4.1.2
Exception Type: KeyError
Exception Value:
'password'
Exception Location: C:\Users\abbas\OneDrive\Desktop\Django\sx_site\generalpage\views.py, line 36, in createaccount
Raised during: generalpage.views.createaccount
Python Executable: C:\Users\abbas\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe
Python Version: 3.10.8
Python Path:
['C:\\Users\\abbas\\OneDrive\\Desktop\\Django\\sx_site',
'C:\\Program '
'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\\python310.zip',
'C:\\Program '
'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\\DLLs',
'C:\\Program '
'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\\lib',
'C:\\Users\\abbas\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0',
'C:\\Users\\abbas\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python310\\site-packages',
'C:\\Program '
'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0',
'C:\\Program '
'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\\lib\\site-packages']
Server time: Sat, 15 Oct 2022 11:57:46 +0000
Try this and check if it works
in
def createaccount(request):
...............
if request.method == "POST":
form = CustomUserRegisterForm(request.POST,instance = request.user)
It is not 100% obvious what you are trying to do. Is UserRegister meant to be a model for your base user?
What is the value of settings.AUTH_USER_MODEL?
If UserRegister is meant to be your base user, then I am not sure why you have a field that is OneToOne with another User model?
class UserRegister(AbstractBaseUser, PermissionsMixin):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
username = models.CharField(_("Användarnamn"), max_length=100, null=True, unique=True)
age = models.IntegerField(_("Ålder"),null=True, blank=False)
email = models.EmailField(_("E-mail"), unique=True, null=False)
...
Can you try removing the user field from your model?:
class UserRegister(AbstractUser, PermissionsMixin):
username = models.CharField(_("Användarnamn"), max_length=100, null=True, unique=True)
age = models.IntegerField(_("Ålder"),null=True, blank=False)
email = models.EmailField(_("E-mail"), unique=True, null=False)
...
The in your settings.py file:
AUTH_USER_MODEL = "<app_name>.UserRegister"
My hunch is that, because of the above, you have a second User model that is being created as well and the error is because of this.
Sorry if I have misunderstood your question.

Django - After Register, Data Should Go To 2 Different Tables (Customer & User)

I am creating an e-commerce website where people can choose to login or not but still the can order and checkout (even if you are an AnonymousUser or Guest user). Now, I am making a login and register form in my website. The login form works and looks good but the register form wasn't working and throwing an error that said "RelatedObjectDoesNotExist at / User has no customer."
I think the reason is that when I register, it only makes a User in database but didn't register anything in the Customer table (which consists Name and Email). How can I register a Customer and User at the same time when I hit the "Submit" button? And how can I make that specific User have "Staff status" only and cannot make changes in the Admin site?
Also, I want to add new fields in the Register form for Name and Email that will go directly to the Customer table. I tried to do this one but it doesn't work and throwed and error that says "django.core.exceptions.FieldError: Unknown field(s) (name) specified for User".
Here's what I did:
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import *
class CustomUserCreationForm(UserCreationForm):
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200)
class Meta:
model = User
fields = ['username', 'name', 'email', 'password1', 'password2']
SUMMARY:
I want to add extra fields in the Register form called Name and Email. Then after clicking the Register form, I want create User and Customer at the same time. But the User should only have "Staff status" and cannot make changes in the Admin site. And the Name and Email field should go to Customer Table with the User I've created.
Here's the screenshot of my Register form:
Here's my forms.py file:
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'password1', 'password2']
def __init__(self, *args, **kwargs):
super(CustomUserCreationForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Enter Username'})
self.fields['password1'].widget.attrs.update({'class':'form-control','placeholder':'Enter Password'})
self.fields['password2'].widget.attrs.update({'class':'form-control','placeholder':'Confirm Password'})
Here's my views.py file:
def loginUser(request):
page = 'login'
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
print('USER:', user)
if user is not None:
login(request, user)
return redirect('/')
return render(request, 'store/login_register.html', {'page': page})
def logoutUser(request):
logout(request)
return redirect('/')
def registerUser(request):
page = 'register'
form = CustomUserCreationForm()
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
user = authenticate(request, username=user.username, password=request.POST['password1'])
if user is not None:
login(request, user)
return redirect('/')
context = {'form': form, 'page': page}
return render(request, 'store/login_register.html', context)
Here's my models.py file:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200)
def __str__(self):
return self.name
Here's my register.html file:
<form class="form" method="POST">
{% csrf_token %}
<h2> REGISTER </h2>
<h4> Create your account now! </h4>
<br />
{% for field in form %}
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">{{field.label}}:</label>
{{field}}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
<br />
<p> Already have an account? Login here </p>
</form>

How to resolve user into the field?

I'm creating a simple To Do app using Django 3.2, and I have stuck in a error which is: FieldError: Cannot resolve keyword 'user' into field. Choices are: content, created, email, id, name, user1, user1_id
This is models.py:
from django.db import models
from django.db.models.deletion import CASCADE
from django.db.models.fields import CharField
from django.contrib.auth.models import User
# Create your models here.
class User(models.Model):
content = models.CharField(max_length=200, null=True)
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
user1 = models.ForeignKey(User, on_delete=CASCADE)
def __str__(self):
return self.content
forms.py
from django import forms
from django.forms import ModelForm, fields
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2']
views.py
from django.shortcuts import render, redirect
from django.http.response import HttpResponse
from django.utils import timezone
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from demo.forms import CreateUserForm
from .models import *
from .models import __str__
# Create your views here.
#login_required(login_url='/login')
def home(request):
user = request.user
all_items = User.objects.filter(user=user).order_by("created")
context = {'all_items': all_items}
return render(request, 'html/home.html', context)
#login_required(login_url='/login')
def add_content(request):
current_date = timezone.now()
newItem = User(content=request.POST.get('content'))
newItem.save()
return redirect('/')
#login_required(login_url='/login')
def login_user(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/')
return render(request, 'html/login.html')
def logoutUser(request):
logout(request)
return redirect('login/')
def register_user(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
user = authenticate(request, username=user.username, password=request.POST.get('password1'))
if user is not None:
login(request, user)
return redirect('/')
context = {'form':form}
return render(request, 'html/register.html', context)
home.html
<div>
<form class="felx" action="add_content/" method="POST">
{% csrf_token %}
<input class="form-control me-2" type="text" name="content" placeholder="Hey">
<button id="add-btn" class="button" type="submit">Add</button>
</form>
<table>
<thead>
{% for all_item in all_items %}
<tr>
<td>{{ all_item.content }}</td>
</tr>
{% endfor %}
</thead>
</table>
Logout
{% if request.user.is_authenticated %}
<p>Hello {{request.user}}</p>
{% endif %}
</div>
By far, any data that is added can be access by every account, but what i'm trying to do is that each user has his own data or tasks in this case.
Would appreciate any idea!
Thanks
i think your problem is here
#login_required(login_url='/login')
def home(request):
user = request.user.pk
all_items = User.objects.filter(user1_id=user).order_by("created") #new
context = {'all_items': all_items}
return render(request, 'html/home.html', context)
#login_required(login_url='/login')
def add_content(request):
current_date = timezone.now()
newItem = User(content=request.POST.get('content'),user1_id=request.user.pk)
newItem.save()
return redirect('/')
Advice:Please try to change the User in models.py to an other name because Django has by default a model called User.

Django 1.9 check if email already exists

My site is set up so there is no username (or rather user.username = user.email). Django has an error message if a user tries to input a username that is already in the database, however since I'm not using a username for registration I can't figure out how to do this.
Just like the default settings already is, I don't want to reload the page to find out if there is an email address already associated with a user. My guess is to use Ajax, but I can't figure out how to do it. Ive looked at other posts, but there doesn't seem to be anything recent.
How can I check to see if an email address already exists, and if so, give an error message for the user to input a new email address?
models.py:
class MyUsers(models.Model):
user = models.OneToOneField(User)
first_name = models.CharField(max_length=100, blank=True)
last_name = models.CharField(max_length=100, blank=True)
email = models.EmailField(max_length=100, blank=True, unique=True)
company = models.CharField(max_length=100, blank=True, null=True)
website = models.URLField(max_length=100, blank=True, null=True)
phone_number = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.user.username
forms.py:
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('email',)
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('first_name', 'last_name', 'company', 'website', 'phone_number')
views.py:
def index(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.password = ""
user.username = user.email
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.email = user.email
profile.save()
user.first_name = profile.first_name
user.last_name = profile.last_name
user.save()
registered = True
return HttpResponseRedirect(reverse('registration'))
else:
print user_form.errors, profile_form.errors
else:
user_form = UserForm()
profile_form = UserProfileForm1()
context = {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}
return render(request, 'mysite/register.html', context)
register.html:
{% extends 'mysite/base.html' %}
{% load staticfiles %}
{% block title_block %}
Register
{% endblock %}
{% block head_block %}
{% endblock %}
{% block body_block %}
<form id="user_form" method="post" action="/mysite/" enctype="multipart/form-data">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<input type="submit" name="submit" value="Register" />
</form>
{% endblock %}
You can override the clean_<INSERT_FIELD_HERE>() method on the UserForm to check against this particular case. It'd look something like this:
forms.py:
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('email',)
def clean_email(self):
# Get the email
email = self.cleaned_data.get('email')
# Check to see if any users already exist with this email as a username.
try:
match = User.objects.get(email=email)
except User.DoesNotExist:
# Unable to find a user, this is fine
return email
# A user was found with this as a username, raise an error.
raise forms.ValidationError('This email address is already in use.')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('first_name', 'last_name', 'company', 'website', 'phone_number')
You can read more about cleaning specific fields in a form in the Django documentation about forms.
That said, I think you should look into creating a custom user model instead of treating your User Profile class as a wrapper for User.

Django how to pass value from template to view

i want this functionality. User enters email address, and somehow it has to be passed to my views.py file, so i could then email the user that he has succesfully registered.
This is my template file:
{% extends "base.html" %}
{% block content %}
<section>
<h2 style="text-align: center">Register</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}
<ul>
{{form.as_ul}}
</ul>
<input type="submit" value="Register" onclick="validateForm()"/>
</form>
</section>
{% endblock %}
this is my forms.py file:
class MyRegistrationForm(UserCreationForm):
#kokie fields bus displayed html form
email = forms.EmailField(required=True)
firstname = forms.CharField(required=True)
lastname = forms.CharField(required=True)
whoinvitedyou = forms.CharField(required=True)
phone = forms.CharField(required=True)
workplace = forms.CharField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2', 'firstname', 'lastname', 'whoinvitedyou', 'phone', 'workplace')
def save(self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.set_password(self.cleaned_data["password1"])
#more fields for name last name
user.firstname = self.cleaned_data['firstname']
user.lastname = self.cleaned_data['lastname']
user.whoinvitedyou = self.cleaned_data['whoinvitedyou']
user.phone = self.cleaned_data['phone']
user.workplace = self.cleaned_data['workplace']
if commit:
user.save()
return user
this is my views.py:
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
return render_to_response('invalid_reg.html')
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
print args
return render_to_response('register.html', args)
how do i pass the value so later i can use it? maybe somebody can help me with this...
In your view, after the form.is_valid() call, the email address will be available in form.cleaned_data['email']. You can use that to send the email after form.save().
Additionally, you might want to look into existing 3rd party libraries like django-registration as it already does the functionality (emailing the just registered user) that you want.
In order to send an e-mail you don't necessarily need to send the value to a view in views.py.
You can use a post_save signal to send an email. You can put the code anywhere, although I usually put it in models.py.
Info on signals: https://docs.djangoproject.com/en/1.7/topics/signals/
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import send_mail
#receiver(post_save, sender=User)
def my_handler(sender, instance, *args, **kwargs):
send_mail('Subject of email', 'Message body.', 'from#example.com', [instance.email], fail_silently=False)
note that instance.email is the email address of the user which you just saved, you can access instance to retreive more information e.g. the name, so that you can put "dear "+instance.name at the beginning of the body for example

Categories