Hi,
I am having trouble saving the form data to the database after submitting. The page on some occassions redirects to the profile page, but doesnt update the data inputted from profileedit.html
but now more recently I have been getting a Exception Value: |as_crispy_field got passed an invalid or inexistent field. Not sure why this has occured as I havent changed any of the fields and crispy form fields were rendering earlier today… any help would be greatly appreciated.
html:
{% extends 'base2.html' %}
{% load crispy_forms_tags %}
{% load i18n %}
{% block content %}
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h1"> {{ profile_title }} </h1>
</div>
<h3 class="h3">User ID Information:</h3>
<form class="EditProfileForm" action= "" method="POST">{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-12 mb-0">
{{ form.email|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12 mb-0">
{{ form.password|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12 mb-0">
{{ form.password_2|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.first_name|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.last_name|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.date_of_birth|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.user_type|as_crispy_field }}
</div>
</div>
<div class="form-row">
DATE CREATED:
</div>
<div class="form-row">
<input type='submit' value='Save Profile' class="btn btn-default" role="button" style="background-color: #007bff; color: #ffffff;" />
</div>
</form>
</main>
</main>
{% endblock %}
models.py
class User(AbstractBaseUser):
USER_TYPE_CHOICES = (
('user_type_1', 'USER_TYPE_1'),
('user_type_2', 'USER_TYPE_2'),
('user_type_3', 'USER_TYPE_3'),
('user_type_4', 'USER_TYPE_4'),
('user_type_5', 'USER_TYPE_5'),
('user_type_6', 'USER_TYPE_6'),
('Superuser', 'SUPERUSER'),
)
email = models.EmailField(verbose_name='email',max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(_('date joined'), auto_now_add=True, blank=False)
last_login = models.DateTimeField(_('last login'), auto_now_add=True, blank=False)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
password = models.CharField(_('password'), max_length=128)
password_2 = models.CharField(_('password_2'), max_length=128)
first_name = models.CharField(max_length=200, default='please enter your first name', null=True)
last_name = models.CharField(max_length=200, default='please enter your last name', null=True)
date_of_birth = models.DateField(null=True)
user_type = models.CharField(max_length=20, default='Client',choices=USER_TYPE_CHOICES)
professional_title = models.CharField(max_length=120, default='please enter your professional title', null=True)
bio = models.CharField(max_length=200, default='description default text', blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username',]
objects = UserManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"""
Return True if the user has the specified permission. Query all
available auth backends, but return immediately if any backend returns
True. Thus, a user who has permission from a single auth backend is
assumed to have permission in general. If an object is provided, check
permissions for that object.
"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
def has_perms(self, perm_list, obj=None):
"""
Return True if the user has each of the specified permissions. If
object is passed, check if the user has all required perms for it.
"""
return all(self.has_perm(perm, obj) for perm in perm_list)
def has_module_perms(self, app_label):
"""
Return True if the user has any permissions in the given app label.
Use similar logic as has_perm(), above.
"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
return _user_has_module_perms(self, app_label)
def update_last_login(sender, user, **kwargs):
"""
A signal receiver which updates the last_login date for
the user logging in.
"""
user.last_login = timezone.now()
user.save(update_fields=['last_login'])
forms.py
class EditProfileForm(UserChangeForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
password_2 = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = (
'email',
'password',
'password_2',
'first_name',
'last_name',
'date_of_birth',
'user_type',
)
def clean_email(self, request, user):
email = self.cleaned_data.get('email')
qs = User.objects.filter(email=email)
if qs.exists():
raise forms.ValidationError("email is taken")
return email
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
def clean_password_2(self, request, user):
# Check that the two password entries match
password = self.cleaned_data.get("password")
password_2 = self.cleaned_data.get("password_2")
if password and password_2 and password != password_2:
raise forms.ValidationError("Passwords don't match")
return password_2
def clean_first_name(self, request, user):
first_name = self.cleaned_data.get('first_name')
fname = User.objects.filter(first_name=first_name)
return first_name
def clean_last_name(self, request, user):
last_name = self.cleaned_data.get('last_name')
lname = User.objects.filter(last_name=last_name)
return last_name
def clean_date_of_birth(self, request, user):
date_of_birth = self.cleaned_data.get('date_of_birth')
dob = User.objects.filter(date_of_birth=date_of_birth)
return date_of_birth
def clean_user_type(self, request, user):
user_type = self.cleaned_data.get('user_type')
ut = User.objects.filter(user_type=user_type)
return user_type
def save(self, commit=True):
# Save the provided password in hashed format
user = super(EditProfileForm, self).save(commit=False)
user.set_password(self.cleaned_data["password"])
user.active = False # send confirmation email.
if commit:
user.save()
return user
views.py
@login_required(login_url = 'account_login')
def user_profile_edit(request):
title = 'Edit Profile'
context = {
'profile_title': title,
}
if request.method == 'POST':
form = EditProfileForm(request.POST or None, instance=request.user)
if form.is_valid():
email = (form.cleaned_data['email'])
password = (form.cleaned_data['password'])
password_2 = (form.cleaned_data['password_2'])
first_name = (form.cleaned_data['first_name'])
last_name = (form.cleaned_data['last_name'])
date_of_birth = (form.cleaned_data['date_of_birth'])
user_type = (form.cleaned_data['user_type'])
# update_info = form.save(commit=False)
# update_info.user = request.user
# update_info.save()
form.save()
return HttpResponseRedirect('profileview')
else:
print (form.errors)
else:
form = EditProfileForm(instance=request.user)
args = {
'form':form,
'profile_title': title,
}
return render(request, 'profileedit.html', args)