Custom user creation form always invalid in Django - python

I am working on building a new Django Website and am trying to make an abstract base class and using forms to fill it out. I thought I was doing it correctly, but whenever I try to fill out the form it is always invalid. I am wondering if anyone can help me with this problem. All of the other help I find online does not help me. Here is my code. Thanks
My forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Profile
class CustomUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = Profile
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
def __init__(self, regLinkModel):
super(CustomUserCreationForm, self).__init__()
self.linkInfo = regLinkModel
def save(self, commit=True):
user = super(CustomUserCreationForm, self).save(commit=False)
user.username = self.cleaned_data['username']
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['fname']
user.last_name = self.cleaned_data['lname']
user.password1 = self.cleaned_data['password1']
user.password2 = self.cleaned_data['password2']
if commit:
user.save()
return user
My Models.py
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, first_name, last_name, password):
if not email:
raise ValueError("User needs email address")
if not username:
raise ValueError("User needs username")
if not first_name:
raise ValueError("User needs first name")
if not last_name:
raise ValueError("User needs last name")
user = self.model(
email=self.normalize_email(email),
password = password,
username =username,
first_name = first_name,
last_name = last_name,
)
user.set_password(password1)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password, first_name, last_name):
user = self.create_user(
email=self.normalize_email(email),
password = password,
username =username,
first_name = first_name,
last_name = last_name,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
def count_total_profiles(self):
return Profile.objects.filter(license_id= self.id).count()
def count_active_profiles(self):
return Profile.objects.filter(license_id= self.id).filter(is_active=True).count()
def is_expired(self):
return timezone.now() > self.expire_date
def __repr__(self):
return self.name
class Profile(AbstractBaseUser):
email =models.EmailField(verbose_name='email', max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True, default=" ")
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
first_name = models.CharField(max_length=30, default=" ")
last_name = models.CharField(max_length=30, default=" ")
password1 = models.CharField(max_length=20,default= " ")
password2 = models.CharField(max_length=20,default= " ")
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'password1', 'password2']
objects = MyAccountManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
My view.py
def regUser(request):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
print(form)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("/")
else:
return redirect("/youdiditwrong")
My HTML code
<HTML>
<head>
<title>Create a User</title>
</head>
<body>
<h1>User: </h1>
<form action="" method="POST">
{% csrf_token %}
First Name: <input type="text" name="fname"/><br/>
Last Name: <input type="text" name="lname"/><br/>
Username: <input type="text" name ="username"/><br/>
Email:<input type="text" name="email"/><br/>
Password:<input type="text" name="password1"/><br/>
Confirm Password:<input type="text" name="password2"/><br/>
<input type="submit" value="Post"/>
</form>
</body>
</html>

I think your code should look something like this, you have to add the jinja2 in the html, so that you can use the form you created
<HTML>
<head>
<title>Create a User</title>
</head>
<body>
<h1>User: </h1>
<form action="" method="POST">
{% csrf_token %}
<!-- This is the first option
{{ form.first_name }}
{{ form.last_name }}
{{ form.username }}
{{ form.email }}
{{ form.password }}
{{ form.password2 }}
-->
<!-- This is second option
{{ form.as_ul }}
-->
<input type="submit" value="Post"/>
</form>
</body>
</html>
views.py
def regUser(request):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
print(form)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("/")
else:
return redirect("/youdiditwrong")
else: # if the method is not POST
return render(request, "page with the html",
{"form": CustomUserCreationForm()}

Related

customer registration not showing in django admin

Trying to create customer registration form for ecommerce website . No errors while submitting the form, but details are not shown in django admin . Here are required codes :
models.py
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
full_name = models.CharField(max_length=200)
address = models.CharField(max_length=200, null=True, blank=True)
joined_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.full_name
urls.py
urlpatterns = [path("register",views.register, name="register")]
forms.py
class CustomerRegistrationForm(forms.ModelForm):
username = forms.CharField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
email = forms.CharField(widget=forms.EmailInput())
class Meta:
model = Customer
fields = ["username", "password", "email", "full_name", "address"]
def clean_username(self):
uname = self.cleaned_data.get("username")
if User.objects.filter(username=uname).exists():
raise forms.ValidationError(
"Customer with this username already exists.")
return uname
views.py
def register(request):
form = CustomerRegistrationForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
email = form.cleaned_data.get("email")
user = User.objects.create_user(username, email, password)
form.instance.user = user
return redirect("/")
return render(request,"register.html",{'form':form})
register.html
{% load crispy_forms_tags %}
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto">
<h3>Customer Registration Form</h3><hr>
<form action="" method="POST">
{% csrf_token %}
{{form|crispy}}
<button class="btn btn-primary" >Register as a Customer</button>
</form>
<p> Already have an account? Login here</p>
</div>
</div>
</div>
Thank you in advance:)
In your view, you're creating Users, not Customers.
If you're starting a new project, I would suggest using a custom user model.
If that's not possible, you need to save the form first to generate a Customer instance and then connect it with the appropriate User model:
def register(request):
form = CustomerRegistrationForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
email = form.cleaned_data.get("email")
customer = form.save(commit=False)
user = User.objects.create_user(username, email, password)
customer.user = user
customer.save()
form.instance.user = user
return redirect("/")
return render(request,"register.html",{'form':form})

I don't know why my django signup form can't create the new user

I made a signup form and a signup view in the Django project. But it seems that 'create_user' does not work. There is no error. Signup view just sends the browser to Home without creating a new user object
The user model is using email as a username.
I tried to do this with ModelForms but it was the same.
I don't know why happens this.
users/forms.py
class StudentSignUpForm(forms.Form):
first_name = forms.CharField()
last_name = forms.CharField()
email = forms.EmailField(
widget=forms.EmailInput(attrs={"placeholder": "Enter your emaill adress"})
)
password = forms.CharField(
widget=forms.PasswordInput(attrs={"placeholder": "Enter the Password"})
)
password_confirm = forms.CharField(
widget=forms.PasswordInput(attrs={"placeholder": "Confirm the Password"})
)
def clean_email(self):
email = self.cleaned_data.get("email")
try:
models.User.objects.get(email=email)
raise forms.ValidationError("This email already exists.")
except models.User.DoesNotExist:
return email
def clean_password_confirm(self):
password = self.cleaned_data.get("password")
password_confirm = self.cleaned_data.get("password_confirm")
if password != password_confirm:
raise forms.ValidationError("Password confirmation does not match.")
else:
return password
def save(self):
first_name = self.cleaned_data.get("first_name")
last_name = self.cleaned_data.get("last_name")
email = self.cleaned_data.get("email")
password = self.cleaned_data.get("password")
user = models.User.objects.create_user(email, password)
user.first_name = first_name
user.last_name = last_name
user.save()
users/views.py
class StudentSignupView(FormView):
template_name = "users/student_signup.html"
form_class = forms.StudentSignUpForm
success_url = reverse_lazy("core:home")
def form_vaild(self, form):
form.save()
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
user = authenticate(self.request, username=email, password=password)
if user is not None:
login(self.request, user)
return super().form_valid(form)
templates/users/student_signup.html
{% extends "base.html" %}
{% block page_title %}
Student Sign up
{% endblock page_title %}
{% block movie_search_bar %}
{% endblock movie_search_bar %}
{% block people_search_bar %}
{% endblock people_search_bar %}
{% block content %}
<form method="post" action="{% url 'users:student_signup' %}">
{% csrf_token %}
{{form.as_p}}
<button>Sign up</button>
</form>
{% endblock content%}
users/urls.py
from django.urls import path
from users import views as user_views
app_name = "users"
urlpatterns = [
path("students/", user_views.StudentList.as_view(), name="list"),
path(
"students/<int:pk>", user_views.StudentProfile.as_view(), name="student_profile"
),
path("students/search/", user_views.SearchView.as_view(), name="search"),
path("users/login/", user_views.LoginView.as_view(), name="login"),
path("users/logout/", user_views.log_out, name="logout"),
path("users/signup/", user_views.sign_up, name="signup"),
path(
"users/signup/student",
user_views.StudentSignupView.as_view(),
name="student_signup",
),
]
users/models.py
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.db import models
class CustomUserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError("Users require an email field")
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault("is_staff", False)
extra_fields.setdefault("is_superuser", False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")
return self._create_user(email, password, **extra_fields)
class User(AbstractUser):
"""User Model Definition"""
SCHOOL_ACCA_ROMA = "acccademia_belle_arti_di_roma"
SCHOOL_CHOICES = ((SCHOOL_ACCA_ROMA, "Accademia Belle Arti di Roma"),)
ACCOUNT_TYPE_STUDENT = "student"
ACCOUNT_TYPE_PUBLIC = "public"
ACCOUNT_TYPE_CHOICES = (
(ACCOUNT_TYPE_STUDENT, "Studente"),
(ACCOUNT_TYPE_PUBLIC, "Publico"),
)
username = None # email을 username으로 사용하기 위해 Abspython manage.py migratetractUser의 username을 none으로 override.
email = models.EmailField(
_("email address"), unique=True
) # _ 는 ugettext_lazy()의 별칭. 언어설정에 따라 출력되는 문자열을 변환해주는 함수다.
USERNAME_FIELD = "email" # email을 username처럼 사용하기.
REQUIRED_FIELDS = (
[]
) # AbsractUser에는 email이 Required로 잡혀있으나 USERNAME_FIELD로 사용되는 필드는 REQUIRED에 있으면 안된다.
school = models.CharField(
_("accademia"), choices=SCHOOL_CHOICES, max_length=50, null=True, blank=True
)
avatar = models.ImageField(upload_to="user_avatars", null=True, blank=True)
biography = models.TextField(_("biography"), null=True, blank=True)
account_type = models.CharField(
_("tipo d'account"),
choices=ACCOUNT_TYPE_CHOICES,
max_length=50,
null=True,
blank=True,
)
objects = CustomUserManager()
def __str__(self):
return self.email

Django - Form not showing up on template only the button

I've been trying everything, but I can't figure out why it's not showing-up. I searched everywhere on this site with no luck. The button shows up but when I click than it give me a TypeError at get_profile, saying:
Exception Value:
get_profile() got an unexpected keyword argument 'username'
Here's my code:
models.py
class CustomUser(AbstractBaseUser):
email = models.EmailField('email address', unique=True, db_index=True)
username = models.CharField('username', max_length=50, unique=True, db_index=True)
first_name = models.CharField(max_length=50, blank=False)
last_name = models.CharField(max_length=50, blank=False)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __unicode__(self):
return self.username
forms.py
from django import forms
from apps.accounts.models import CustomUser
class RegistrationForm(forms.ModelForm):
email = forms.EmailField(widget=forms.TextInput, label='email')
username = forms.CharField(widget=forms.TextInput, label='username')
password1 = forms.CharField(widget=forms.PasswordInput, label='Enter your password')
password2 = forms.CharField(widget=forms.PasswordInput, label='Re-type your password')
first_name = forms.CharField(widget=forms.TextInput, label='First Name')
last_name = forms.CharField(widget=forms.TextInput, label='Last Name')
class Meta:
model = CustomUser
fields = ['email', 'username', 'password1', 'password2', 'first_name', 'last_name']
def clean(self, password1, password2):
cleaned_data = super(RegistrationForm, self).clean()
if password1 in self.cleaned_data and password2 in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("Passwords don't match. Please enter both fields again")
return self.cleaned_data
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
views.py
def register(request):
"""
User Registration View
"""
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
CustomUser = form.save()
CustomUser.save()
return redirect('home.html')
else:
form = RegistrationForm()
return render_to_response('register.html', {
'form': form,
}, context_instance=RequestContext(request))
def get_profile(request):
username = CustomUser.username
return render_to_response(request, 'profile.html', {'username': username})
urls.py
urlpatterns = patterns ('',
url(r'register$', 'apps.accounts.views.register', name='register'),)
register.html
{% load staticfiles %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<body>
{% block body %}
<form method='POST' action="register" enctype= 'multipart/form-data'>{% csrf_token %}
<table>{{ form.ast_table}}</table>
<input type='submit' class="btn btn-default" value="Register" />
</form>
{% endblock %}
</body>
</html>
It seems that you don't have the right signature for the get_profile view function.
You should check your urls, you probably have something like
url(r'^profile/(?P<username>\w+/$', get_profile),
If so, your view should be
def get_profile(request, username):
#you can get the user
user = CustomUser.objects.get(username=username)
return render_to_response(request, 'profile.html', {'username': username, 'user': user})
CustomUser is the class. You need to fetch an instance before you can actually fetch its username.
Eg:
CustomUser.objects.get(pk=1).username
Gives you the username of the first user.
Also, its supposed to be {{form.as_table}} not ast_table

form.is_valid() always returns false

I have tried all the solutions given on SO but was not able to slve this
view.py
def signup(request):
form = SignupForm(request.GET)
print("%s"%request.GET['hobby'])
form.errors
#h=SignupForm(request.POST)
if form.is_valid():
email = request.GET['email']
location = request.GET['location'] users=User(username=username,email=email,password=request.GET['password'],location=location)
user_profile = request.user.profile
user_profile.location = location
user_profile.save()
form.save()
return HttpResponseRedirect('mtweet/')
return render(request,'mtweet/signup.html',{'SignupForm':form})
form.py
class SignupForm(UserCreationForm):
username=forms.CharField(label = " Username",required=True)
email = forms.EmailField(label = "Email",required=True)
password = forms.CharField(widget = forms.PasswordInput,required=True)
location=forms.CharField(label="Location",required=False)
class Meta:
model = User
fields = ("username", "email","location")
signup.html
<div id="register">
<form method="post" action="{% url 'mtweet.views.signup' %}">
{% csrf_token %}
<table>
{{ SignupForm.as_p}}
</table>
<input type="submit" value="Submit" />
</form>
</div>
There are a few problems with your code; let me try and re-write it:
class SignupForm(forms.Form):
username=forms.CharField(label = " Username",required=True)
email = forms.EmailField(label = "Email",required=True)
password = forms.CharField(widget=forms.PasswordInput,required=True)
location=forms.CharField(label="Location",required=False)
def signup(request):
form = SignupForm(request.POST, request.FILES)
if form.is_valid():
email = form.cleaned_data['email']
location = form.cleaned_data['location']
password = form.cleaned_data['password']
username = form.cleaned_data['username']
user = User.objects.create_user(username, email, password)
user.save()
user_profile = user.profile
user_profile.location = location
user_profile.save()
return HttpResponseRedirect('mtweet/')
else:
return render(request,'mtweet/signup.html',{'SignupForm':form})
return render(request,'mtweet/signup.html',{'SignupForm':SignupForm()})

Login in Django 1.5

I use MyUser model in Django 1.5 with e-mail login:
model:
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
db_index=True,
)
last_name=models.CharField(max_length=30)
first_name=models.CharField(max_length=30)
second_name=models.CharField(max_length=30, blank=True)
post=models.CharField(max_length=30, blank=True)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['last_name','first_name','second_name','post', ....]
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def __unicode__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.is_admin
I tried method with from django.contrib.auth.views import login:
urls:
(r'^login/$', login, {'template_name': 'enter.html'}),
view: nothing.
It works for superuser from classic User model, not for MyUser.
Then I tried:
view:
def login_view(request):
username = request.POST['email']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return HttpResponseRedirect("/n1.html")# Redirect to a success page.
else:
return HttpResponseRedirect("/account/invalid/")# Return a 'disabled account' error message
template:
{% if form.errors %}
<p>Something is wrong</p>
{% endif %}
<form action="" method="post">
{% csrf_token %}
<label for="email">Login:</label>
<input type="text" name="email" value="" id="email"/>
<label for="password">Password:</label>
<input type="password" name="password" value="" id="username">
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{next|escape}}" />
</form>
urls:
(r'^login/$', login_view, {'template_name': 'enter.html'}),
But I got error login_view() got an unexpected keyword argument 'template_name'
What am I doing wrong?
login_view() got an unexpected keyword argument 'template_name' means that your view function should have template_name parameter:
def login_view(request, template_name):
'your code'
If you don't need it, don't pass it in urls.py:
(r'^login/$', login_view),
Upd.
Your login_view handles your POST method. You can re-write it this way to render form on GET
def login_view(request):
if request.method == 'POST':
username = request.POST['email']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return HttpResponseRedirect("/n1.html")
return HttpResponseRedirect("/account/invalid/")
form = LoginForm()
return render(request, 'enter.html', {'login_form': LoginForm})

Categories