|as_crispy_field got passed an invalid or inexistent field

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)

It might help if you posted the full traceback message from your runserver console when you encounter this error.

Just curious - why do these functions exist and what do you think you’re accomplishing with them? (I don’t see where they’re doing anything useful, but I do see where each of them is generating an apparently unnecessary database query.)

 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

Finally, it looks like you’ve possibly switched from extending the User object by profile model to replacing the User model completely. Was that something you did after starting the project and performing the initial migration? If so, you might want to drop and recreate the database and redo the initial migration. Changing User models after the initial migration has been performed is filled with all sorts of probable pitfalls.

Hi Ken,

Thanks for your response. As for the functions, I have probably confused myself from the multiple tutorials, examples I have followed. My understanding was I needed them describe what data is to be cleaned from the fields and added to the user object.

As for extending the the standard django User profile. I made the decision to extend after I had started my project because I realised that I needed to create multiple user types for my site to allow for not only user type permissions across the app but each of the user types has specific required profile information for each of the types to fill out for registration. As I have changed the user model after starting the project, as you would know I have encountered errors that have required me to delete the database re-perform migrations.

I basically have generic Class User as a base, which has the standard profile information, then i have Class User Types 1-6 which have different user type specific profile fields some of which will eventually need to be validated before they can have that user type class. Even though I have started the project and realised I needed to change the user models to fit my requirements. I thought its best to get the User model right from the start before continuing on with the rest of the project.

  • Is there a better way to achieve the same or a similar outcome for my user model?

  • Should I also have a User Profile class as well as a user model and user types model, so that the User Profile references the User model and the User Types reference the User Profile…if that makes sense?

I also felt that “User” and “Profile” are the same thing, should I be thinking of them as seperate apps? …or is there a better option or tutorial that you could point me to?

Thanks for your help.

Traceback:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/profile/profileedit/

Django Version: 3.0.5
Python Version: 3.8.2
Installed Applications:
['profiles',
 'web_portal',
 'enquiries',
 'crispy_forms',
 'colorful',
 'desktop',
 'projects',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'social_app',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.google']

Installed 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']



Template error:
In template /Users/neens1981/Desktop/xARx/src/profiles/templates/base2.html, error at line 22
   |as_crispy_field got passed an invalid or inexistent field
   12 :     <meta name="generator" content="Jekyll v3.8.6">
   13 :     <title>Dashboard Template · Bootstrap</title>
   14 : 
   15 :     <link rel="canonical" href="https://getbootstrap.com/docs/4.4/examples/dashboard/">
   16 : 
   17 :     <!-- Bootstrap core CSS -->
   18 : <link href="{% static '/styles/css/bootstrap.min.css' %}" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
   19 : 
   20 :     <!-- Favicons -->
   21 : <link rel="icon" href="{% static '/styles/site/docs/4.4/assets/img/favicons/home.svg' %}" sizes="32x32" type="image/svg">
   22 : <link rel="i con" href="{% static '/styles/site/do cs/4.4/assets/img/favicons/clock.svg' %}" sizes="32x32" type="image/svg">
   23 : <link rel="icon" href="{% static '/styles/site/docs/4.4/assets/img/favicons/hard-drive.svg' %}" sizes="32x32" type="image/svg">
   24 : <link rel="icon" href="{% static '/styles/site/docs/4.4/assets/img/favicons/calendar.svg' %}" sizes="32x32" type="image/svg">
   25 : <link rel="icon" href="{% static '/styles/site/docs/4.4/assets/img/favicons/dollar-sign.svg' %}" sizes="32x32" type="image/svg">
   26 : <link rel="icon" href="{% static '/styles/site/docs/4.4/assets/img/favicons/message-circle.svg' %}" sizes="32x32" type="image/svg">
   27 : 
   28 : <link rel="icon" href="{% static '/styles/site/docs/4.4/assets/img/favicons/favicon-32x32.png' %}" sizes="32x32" type="image/png">
   29 : <link rel="icon" href="{% static '/styles/site/docs/4.4/assets/img/favicons/favicon-16x16.png' %}" sizes="16x16" type="image/png">
   30 : <link rel="manifest" crossorigin="use-credentials" href="{% static '/styles/site/docs/4.4/assets/img/favicons/manifest.json' %}"/>
   31 : <link rel="mask-icon" href="{% static '/styles/site/docs/4.4/assets/img/favicons/safari-pinned-tab.svg' %}" color="#563d7c">
   32 : <link rel="icon" href="{% static '/styles/site/docs/4.4/assets/img/favicons/favicon.ico' %}">


Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/Users/neens1981/Desktop/xARx/src/profiles/views.py", line 155, in user_profile_edit
    return render(request, 'profileedit.html', args)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/base.py", line 986, in render
    output = self.filter_expression.resolve(context)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/base.py", line 697, in resolve
    new_obj = func(obj, *arg_vals)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/crispy_forms/templatetags/crispy_forms_filters.py", line 101, in as_crispy_field
    raise CrispyError("|as_crispy_field got passed an invalid or inexistent field")

Exception Type: CrispyError at /profile/profileedit/
Exception Value: |as_crispy_field got passed an invalid or inexistent field

Not sure what resources you’re working from, but the clean_<fieldname> methods are used to perform additional tests when necessary to validate the content of a field. (For example, you might have a field for “birth year”. You might want to add a test to ensure the entry is between 1900 and 2020, or within some reasonably expected range.) If you don’t have any specific additional validation to be performed, you don’t need the validation function.

Regarding your User model design - I don’t think there’s really a right or wrong answer here. Your solution is workable, and that’s all that really matters.

Nope, User and Profile can appropriately both be the same app.

<opinion>
My preference is to extend the User model using a Profile model when I don’t need to alter the default behavior of the User model. Only when I need to change default behavior do I think about using a custom User model.
Off the cuff, I’d be tempted to adopt something similar to what you’ve identified - but I don’t know just how different those User Types are to know whether or not I would choose a different mechanism for doing it.
</opinion>

Now, back to the original error message, you quoted:

That’s where I’d start looking to see what’s in that neighborhood that might be causing a problem.

Ken

Yes I noticed that it was pointing to my base styling template file. The file is imported over the top of my app template files and holds the bootstrap information and links to my side bar and nav bar html files. It says the error is at line 0. Does that mean it doesn’t like the whole file?

This exception doesn’t seem to match the traceback you posted above.

Can you just post your base2.html file?

base2.html

<!-- BASE 2 Template - Navbar + Sidebar -->

{% load static %}

<!DOCTYPE html>
<html lang="en">
  <head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Jekyll v3.8.6">
<title>Dashboard Template · Bootstrap</title>

<link rel="canonical" href="https://getbootstrap.com/docs/4.4/examples/dashboard/">

<!-- Bootstrap core CSS -->
<link href="{% static '/styles/css/bootstrap.min.css' %}" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="manifest" crossorigin="use-credentials" href="{% static '/styles/site/docs/4.4/assets/img/favicons/manifest.json' %}"/>
<meta name="msapplication-config" content="{% static '/styles/site/docs/4.4/assets/img/favicons/browserconfig.xml' %}">
<meta name="theme-color" content="#563d7c">

<style>
  .h1 {
    color: #007bff !important;
  }

  .bd-placeholder-img {
    font-size: 1.125rem;
    text-anchor: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  @media (min-width: 768px) {
    .bd-placeholder-img-lg {
      font-size: 3.5rem;
    }
  }
</style>
  </head>

  <body>
<!-- Custom styles for this template -->
<link rel="stylesheet" href="{% static '/styles/css/dashboard.css' %}">
<link rel="stylesheet" href= "{% static '/styles/css/main.css' %}">
 
{% include 'navbar.html' %}
{% include 'sidebar.html' %}
{% block content %}
{% endblock %}






<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script>window.jQuery || document.write('<script src="/docs/4.4/assets/js/vendor/jquery.slim.min.js"><\/script>')</script><script src="{% static '/styles/javascript/bootstrap.bundle.min.js' %}" integrity="sha384-6khuMg9gaYr5AxOqhkVIODVIvm9ynTT5J4V1cfthmT+emCG6yVmEZsRHdxlotUnm" crossorigin="anonymous"></script>
    <script src="{% static '/styles/javascript/feather.min.js' %}"></script>
    <script src="{% static '/styles/javascript/Chart.min.js' %}"></script>
    <script src="{% static '/styles/javascript/dashboard.js' %}"></script>
  </body>
</html>

Unfortunately, I’m not seeing anything wrong at the moment with what you’re posting.

Working under the assumption that neither navbar.html nor sidebar.html use crispy at all (doesn’t import crispy tags and doesn’t try to use any of the crispy filters), there’s nothing obviously wrong that I can see.

The only thing I see wrong at all is that you’ve got one <main> tag but two </main> tags - no idea how this would affect the template engine.

If I had to attack this problem, I’d start by backing off - either remove the as_crispy_field tags to verify that they are related to the real issue, or remove all but maybe one or two fields, and work incrementally from there.

Beyond that, I’d be testing regularly, seeing what’s being rendered with making incremental additions. (I’d probably be working on this through the django shell as well - it’s really a helpful tool.) I might also see if the django debug toolbar reveals further information.

In other words, my next step would just be more information gathering - looking at anything and everything that shows any opportunity of revealing more information than what I have now.

(Personal note: We use crispy for our forms too - but we use it as a complete crispy form using the crispy layout helpers. I don’t think I’ve ever used the filter version of the APIs. I know that doesn’t help you any, just consider it a disclaimer that my knowledge of it in that area is very limited.)

1 Like

Thanks Ken for your detailed help. You were right, the errors were being thrown from a double up of when one should of been . Something so simple in the template html file and overlooked and caused an error with rendering the crispy forms. After removing the unnecessary form.py functions the edit user profile form renders with "as_crispy_field"s and submits the data to the profile view. Thanks also for your suggestion of using the crispy layout helpers, it looked a little more complicated to implement than the “as_crispy_field” option, but will consider it in the future. Thanks again for all your help.

2 Likes

Great! Glad to see you’ve gotten it working.

<opinion>
I won’t deny that the helpers aren’t a bit more “fiddly” - but we had some very specific layout requirements for that task, and we found that using those helpers ended up getting us there faster. YMMV.
</opinion>

Ken

1 Like

How did you solve the error?

Please how to I debug this error

Superficially, the error message is quite clear - it’s reporting that form.email is not a valid form field. That’s the first thing to check.

If that’s not the problem, then we’ll need more information. As this is a different error from a different template on a different project, it would probably be more appropriate to open up a new discussion for this.

When you do, we will probably need to see your view and the full template being rendered.

When posting code or templates, please enclose the code (or template) between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This ensures your code will stay properly formatted by the forum software and special characters / html tags won’t be interpreted.

Hi, thanks for the help so far

here is my own error

I’m sorry, I can’t read that image.

I would suggest that you open up a new topic for your issue, and copy/paste the text of the error message into your post. (Surrounded by the lines of three backticks - . A line of \``, then the text of the message, then another line of ```.)

Confirm that you aren’t jumping the gun in your admin page. The users has their privileges, despite having multiple superusers; you might need to grant more privileges to your superuser so as not to mess your query_set as well as database.
For instance if you have a super user who is not necessarily an admin by default; he can’t perform and save the admin functions successfully; and if he does and you reload the page, you will get this error; so you either grant him all privileges on the __is() method then save before reloading the page. It should work.

Hello Ken.
Can you help me to fix this?

Error during template rendering
In template /Users/mac/Desktop/dev/ecommerce/account/templates/account/registration/register.html, error at line 45

|as_crispy_field got passed an invalid or inexistent field
35	
36	            <h5> Purchase your favourite items today! </h5>
37	
38	            <hr>
39	            <br>
40	
41	            <form method="POST" autocomplete="off">
42	
43	                {% csrf_token %}
44	
45	                {{form.username|as_crispy_field}}
46	
47	                <br> <br>
48	
49	
50	                {{form.email|as_crispy_field}}
51	
52	                <br> <br>
53	
54	
55	                {{form.password1|as_crispy_field}}

my.html

{% include "store/base.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}

{{form.username|as_crispy_field}}

settings.py
INSTALLED_APPS = [‘crispy_forms’, # register_page_form]
CRISPY_TEMPLATE_PACK = ‘bootstrap4’

forms.py

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', 'email', 'password1', 'password2']

    def __init__(self, *args, **kwargs):
        super(CreateUserForm).__init__(*args, **kwargs)

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('This email is invalid')
        if len(email) >= 350:
            raise forms.ValidationError('Your email is to long buddy :)')
        return email

views.py

from django.shortcuts import render, redirect
from .forms import CreateUserForm

# Create your views here.

def register(request):
    form = CreateUserForm()
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('')
    context = {'form': form}
    return render(request, 'account/registration/register.html', context=context)

urls.py

from django.urls import path
from . import views

urlpatterns = [

    path('register', views.register, name='register')


]

First, in the future, if you have a question or issue that is not directly part of the current topic, please open a new topic for you question.

From what you’re showing, I’m going to make the initial guess that it’s because in your template fragment that you are showing, you are using the include tag instead of the extends tag on your base template.
However, without seeing the complete "store/base.html" template,this is just a guess.

(It’s also assuming you have all the “normal” apps in your INSTALLED_APPS setting.)