# Error Field Required While Login

**URL:** <https://forum.djangoproject.com/t/error-field-required-while-login/7462>\
**Category:** Using Django\
**Created:** [April 10, 2021, 8:46am UTC](https://forum.djangoproject.com/t/error-field-required-while-login/7462 "2021-04-10T08:46:25Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![AhmdMWddh](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ahmdmwddh/32/21707_2.png) [@AhmdMWddh](https://forum.djangoproject.com/u/AhmdMWddh)\
**Post date:** [April 10, 2021, 8:46am UTC](https://forum.djangoproject.com/t/error-field-required-while-login/7462/1 "2021-04-10T08:46:26Z")

</div>

- created account custom model
- register is working
- login always get error message

> Field is required

will be attached Github link for Code and Pythonanywhere live link for whom wanna try live.  
Live Demo: [http://ahmdmwddh.pythonanywhere.com](http://ahmdmwddh.pythonanywhere.com)  
github Source Code: [GitHub - AhmadMWaddah/project\_amw](https://github.com/AhmadMWaddah/project_amw.git)  
Hope the data is clear.  
Great Thanks For Any Response.

Models:

```
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class MyAccountManager(BaseUserManager):
	def create_user(self, email, username, password=None):
		if not email:
			raise ValueError('E-Mail Address Required.')
		if not username:
			raise ValueError('Username Required.')

		account = self.model(
			email=self.normalize_email(email),
			username=username,
		)
		account.set_password(password)
		account.save(using=self._db)
		return account

	def create_superuser(self, email, username, password):
		account = self.create_user(
			email=self.normalize_email(email),
			username=username,
			password=password
		)
		account.is_admin = True
		account.is_staff = True
		account.is_superuser = True
		account.save(using=self._db)
		return account

def account_image_path(self):
	return f'accounts/{self.account_id}/{"account_image.png"}'

def default_account_image():
	return 'default/default_account_image.png'

class Account(AbstractBaseUser):
	account_id = models.AutoField(verbose_name='ID', primary_key=True)
	email = models.EmailField(verbose_name='E-Mail', max_length=60, unique=True)
	username = models.CharField(verbose_name='Username', max_length=60, unique=True)
	first_name = models.CharField(verbose_name='First Name', max_length=30, blank=True, null=True)
	last_name = models.CharField(verbose_name='Last Name', max_length=30, blank=True, null=True)
	age = models.IntegerField(verbose_name='Age', blank=True, null=True)
	mobile = models.CharField(verbose_name='Mobile', max_length=15, blank=True, null=True)
	location = models.CharField(verbose_name='Location', max_length=300, blank=True, null=True)
	date_joined = models.DateTimeField(verbose_name='Date Joined', auto_now_add=True)
	last_login = models.DateTimeField(verbose_name='Last Login', auto_now=True)
	is_active = models.BooleanField(verbose_name='Is Active', default=True)
	is_superuser = models.BooleanField(verbose_name='Is Superuser', default=False)
	is_staff = models.BooleanField(verbose_name='Is Staff', default=False)
	is_admin = models.BooleanField(verbose_name='Is Admin', default=False)
	image = models.ImageField(verbose_name='Image', null=True, blank=True, upload_to=account_image_path, default=default_account_image)

	USERNAME_FIELD = 'email'
	REQUIRED_FIELDS = ['username']

	objects = MyAccountManager()

	def __str__ (self):
		return self.username

	def has_perm(self, perm, obj=None):
		return self.is_admin

	def has_module_perms(self, app_label):
		return True

```

Forms:  
from django import forms  
from django.contrib.auth.forms import UserCreationForm  
from django.contrib.auth import authenticate, login  
from .models import Account

```
class RegisterForm(UserCreationForm):
	email = forms.EmailField(max_length=250, help_text='Must Be Valid E-Mail.')

	class Meta:
		model = Account
		fields = ('email', 'username', 'password1', 'password2')

	def clean_email(self):
		email = self.cleaned_data['email'].lower()
		try:
			account = Account.objects.get(email=email)
		except Exception as e:
			return email
		raise forms.ValidationError(f'E-Mail {email} Is Already Exists.')

	def clean_username(self):
		username = self.cleaned_data['username']
		try:
			account = Account.objects.get(username=username)
		except Exception as e:
			return username
		raise forms.ValidationError(f'Username {username} Is Already Exists.')

class LoginForm(forms.ModelForm):
	password = forms.CharField(label='password', widget=forms.PasswordInput)

	class Meta:
		model = Account
		fields = ('email', 'password')

	def save(self):
		email = self.cleaned_data['email']
		password = self.cleaned_data['password']
		account = authenticate(email=email, password=password)
		if account:
			login(request, account)

```

Views:  
from django.shortcuts import render, redirect  
from django.http import HttpResponse  
from django.contrib.auth import login, authenticate, logout  
from .forms import RegisterForm, LoginForm

```
def account_register(request, *args, **kwargs):
	account = request.user
	if account.is_authenticated:
		return redirect('index')
	context = {
		'page': 'register',
		'form_title': 'A.M.W Store User Register'
	}
	if request.POST:
		register_form = RegisterForm(request.POST)
		if register_form.is_valid():
			register_form.save()
			return redirect('login')
		else:
			context['register_form'] = register_form
	return render(request, 'account/register.html', context)

def account_login(request, *args, **kwargs):
	context = {
		'page': 'login',
		'form_title': 'A.M.W Store User Login'
	}
	account = request.user
	if account.is_authenticated:
		return redirect('index')

	if request.POST:
		login_form = LoginForm(request.POST)
		if login_form.is_valid():
			login_form.save()
			destination = get_redirect_if_exist(request)
			if destination:
				return redirect(destination)
			return redirect('index')
		else:
			context['login_form'] = login_form
	return render(request, 'account/login.html', context)

def get_redirect_if_exist(request):
	redirect = None
	if request.GET:
		if request.GET.get('next'):
			destination_string = request.GET.get('next')
			redirect = str(destination_string)
	return redirect

def account_logout(request):
	logout(request)
	return redirect('index')

```

Urls:  
from django.urls import path  
from account import views

```
urlpatterns = [
	path('register', views.account_register, name='register'),
	path('login', views.account_login, name='login'),
	path('logout', views.account_logout, name='logout'),
]

```

Login Page HTML:  
{% extends ‘base.html’ %}

```
{% load static %}

{% block content %}
<div class="sign-form-wrap">
	<img src="{% static 'imgs/logos/AMWLogo.png' %}" alt="A.M.W Store Logo" class="logo-img"/>
	<form class="sign-form" action="{% url 'login' %}" method="POST">
		{% csrf_token %}
		<h3>{{ form_title }}</h3>
		<div class="sign-form-inputs">
			<input type="email" placeholder="E-Mail.. " required/>
			<input type="password" placeholder="Password.. " required/>
		</div>
		{% for field in login_form %}
		<p>
			{% for error in field.errors %}
			<span style="color: red;">{{ error }}</span>
			{% endfor %}
		</p>
		{% endfor %}
		{% if login_form.non_field_errors %}
		<p>{{ login_form.non_field_errors }}</p>
		{% endif %}
		<input type="submit" value="Sign In"/>
	</form>
</div>
{% endblock %}

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [April 10, 2021, 11:54am UTC](https://forum.djangoproject.com/t/error-field-required-while-login/7462/2 "2021-04-10T11:54:49Z")

</div>

You are not rendering your form fields in your login form. You’ve manually added the input fields, but they’re not the form fields as referenced in your login form.

See [Working with form templates](https://docs.djangoproject.com/en/3.1/topics/forms/#working-with-form-templates), particularly the section on [Rendering fields manually](https://docs.djangoproject.com/en/3.1/topics/forms/#rendering-fields-manually).

---

<div class="post-metadata">

**Author:** ![AhmdMWddh](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ahmdmwddh/32/21707_2.png) [@AhmdMWddh](https://forum.djangoproject.com/u/AhmdMWddh)\
**Post date:** [April 10, 2021, 5:22pm UTC](https://forum.djangoproject.com/t/error-field-required-while-login/7462/3 "2021-04-10T17:22:20Z")

</div>

thanks for support Ken,  
may i ask why its different for Register form i am using the same logic for it too. register form also made with html and working,

---

<div class="post-metadata">

**Author:** ![AhmdMWddh](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ahmdmwddh/32/21707_2.png) [@AhmdMWddh](https://forum.djangoproject.com/u/AhmdMWddh)\
**Post date:** [April 10, 2021, 8:09pm UTC](https://forum.djangoproject.com/t/error-field-required-while-login/7462/4 "2021-04-10T20:09:30Z")

</div>

## Update:

i found i didnt add name attribute into login form inputs in login.html  
and still looking for this issue solution.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [April 11, 2021, 12:30am UTC](https://forum.djangoproject.com/t/error-field-required-while-login/7462/5 "2021-04-11T00:30:36Z")

</div>

My recommended solution would be to create your form and views in the manner intended by Django. I frequently use the phrase “don’t fight the framework” - Django is opinionated with how things are supposed to be done, and working with Django is easiest overall if you adapt to how Django does things rather than trying to make it fit a different mindset.

---

<div class="post-metadata">

**Author:** ![AhmdMWddh](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ahmdmwddh/32/21707_2.png) [@AhmdMWddh](https://forum.djangoproject.com/u/AhmdMWddh)\
**Post date:** [April 11, 2021, 4:37am UTC](https://forum.djangoproject.com/t/error-field-required-while-login/7462/6 "2021-04-11T04:37:28Z")

</div>

nice,  
about forms i guess its ModelForm,  
but about views, what do you advice me, is there any note about for my views, or its working,  
i still in the beginning in Django and Programming and looking for easiest way to make things work now,

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [April 11, 2021, 1:10pm UTC](https://forum.djangoproject.com/t/error-field-required-while-login/7462/7 "2021-04-11T13:10:18Z")

</div>

You mention being a beginner, have you worked your way through either (or both) of the [Official Django Tutorial](https://docs.djangoproject.com/en/3.1/intro/tutorial01/) and the [Django Girls Tutorial](https://tutorial.djangogirls.org/en/)? I always recommend these to people who are just getting started, They do a really good job of showing how the different pieces work together.

One particularly important concept in Django is that these different components are designed to work closely together. You’d be missing out on a lot of what makes Django so useful by looking at views separately from templates. All of views, templates, and urls are designed to work with each other - you don’t want to build templates without considering the views that are going to use them, and the reverse - you don’t want to build views without an eye toward the templates that will be rendering the data.

So to get back around to your view, a LoginForm isn’t something you typically “save”. You might use a form to get input, but you don’t want to save what has been entered.  
See [How to log a user in](https://docs.djangoproject.com/en/3.1/topics/auth/default/#how-to-log-a-user-in) if you really want to do it manually, otherwise look at the [Authentication views](https://docs.djangoproject.com/en/3.1/topics/auth/default/#module-django.contrib.auth.views) to take advantage of the facilities already provided by Django.

---

<div class="post-metadata">

**Author:** ![AhmdMWddh](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ahmdmwddh/32/21707_2.png) [@AhmdMWddh](https://forum.djangoproject.com/u/AhmdMWddh)\
**Post date:** [April 11, 2021, 2:46pm UTC](https://forum.djangoproject.com/t/error-field-required-while-login/7462/8 "2021-04-11T14:46:55Z")

</div>

yes, ken i am a beginner, i use Django Documentation sometimes but i depend on Youtube about 90%, i don’t know its good or bad, but it words fine,

Did not hear about Django Girls Tutorials will definitely check it,

Also found many ways to do things in Django and my goal is to make my website work nicely and will continue after that for modifying it and adding features.

i guess i will build the account app from scratch again if i could not make login work, lol.  
Thanks Again So Much For Support.
