Related
Model.py
class Branch(models.Model): # Branch Master
status_type = (
("a",'Active'),
("d",'Deactive'),
)
name = models.CharField(max_length=100, unique=True)
suffix = models.CharField(max_length=8, unique=True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.name
class Vendor(models.Model):
status_type = (
("a",'Active'),
("d",'Deactive'),
)
branch = models.ManyToManyField(Branch)
company = models.CharField(max_length=200)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=11, unique = True)
email = models.EmailField(max_length=254, unique = True)
gst = models.CharField(max_length=15, unique = True)
pan_no = models.CharField(max_length=10, unique = True)
add_1 = models.CharField(max_length=50, null=True, blank = True)
add_2 = models.CharField(max_length=50, null=True, blank = True)
add_3 = models.CharField(max_length=50, null=True, blank = True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.company
form.py
i want save like created_by field
class VendorForm(ModelForm):
class Meta:
model = Vendor
fields = 'all'
exclude = ['created_by', 'branch']
widgets = {
'company':forms.TextInput(attrs={'class':'form-control'}),
'name':forms.TextInput(attrs={'class':'form-control'}),
'phone':forms.TextInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
'gst':forms.TextInput(attrs={'class':'form-control'}),
'pan_no':forms.TextInput(attrs={'class':'form-control'}),
'add_1':forms.TextInput(attrs={'class':'form-control'}),
'add_2':forms.TextInput(attrs={'class':'form-control'}),
'add_3':forms.TextInput(attrs={'class':'form-control'}),
'Remark':forms.Textarea(attrs={'class':'form-control','rows':'2'}),
'status':forms.Select(attrs={'class':'form-control'}),
}
Views.py
I have pass branch in session.
I want to save with branch which is many to many field
def Add_Vendor(request): # for vendor add
msg = ""
msg_type = ""
branch_id = request.session['branch_id']
branch_data = Branch.objects.get(id = branch_id)
form = ""
if request.method == "POST":
try:
form = VendorForm(request.POST)
if form.is_valid:
vendor_add = form.save(commit=False)
vendor_add.created_by = request.user
vendor_add.instance.branch = branch_data.id
vendor_add.save()
form.save_m2m() # for m to m field save
msg_type = "success"
msg = "Vendor Added."
form = VendorForm(initial={'branch':branch_id})
except:
msg_type = "error"
msg = str(form.errors)
print(msg)
else:
form = VendorForm(initial={'branch':branch_id})
context = {
'form':form,
'branch_data':branch_data,
'msg_type':msg_type,
'msg':msg,
'btn_type':'fa fa-regular fa-plus',
'form_title':'Vendor Form',
'tree_main_title':'Vendor',
'v_url':'vendor_page',
'tree_title':'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html',context)
I would advise not to work with commit=False in the first place:
def Add_Vendor(request): # for vendor add
branch_id = request.session['branch_id']
branch_data = get_object_or_404(Branch, pk=branch_id)
if request.method == 'POST':
form = VendorForm(request.POST, request.FILES)
if form.is_valid():
form.instance.created_by = request.user
form.instance.branch = branch_data.id
vendor_add = form.save()
vendor_add.branch.add(branch_data)
return redirect('name-of-some-view')
else:
form = VendorForm()
context = {
'form': form,
'branch_data': branch_data,
'btn_type': 'fa fa-regular fa-plus',
'form_title': 'Vendor Form',
'tree_main_title': 'Vendor',
'v_url': 'vendor_page',
'tree_title': 'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html', context)
You can simplify your form by automatically adding form-control to each widget:
class VendorForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
attrs = field.widget.attrs
attrs['class'] = attrs.get('class', '') + ' form-control'
class Meta:
model = Vendor
exclude = ['created_by', 'branch']
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Note: You can set a field editable=False [Django-doc]. Then the field does not show up in the ModelForms and ModelAdmins by default. In this case for example with created_by.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Note: Please do not pass messages manually to the template. Django has the messages framework [Django-doc], which allows to add messages to the request, which will then be delivered the next time a template renders these messages. This makes delivering multiple messages convenient, as well as setting different log levels to the messages.
i keep getting this error when i try to register for the second time i have tried multiple possible solutions but i keep getting it anyway any help ?
IntegrityError at /registration/transporteur
this is my code:
here i try to have multi type users
models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length= 15, )
first_name = models.CharField(max_length= 15)
last_name = models.CharField(max_length= 15)
email = models.EmailField(_('email address'),unique= True,)
phone_number = models.CharField(max_length= 15)
address = models.CharField(verbose_name = "Address", max_length= 50, null = True, blank= True)
# profile_picture = models.ImageField(null = True)
# longitude = models.CharField(verbose_name = "Longitude", max_length= 100, null = True, blank= True)
# lagitude = models.CharField(verbose_name = "Lagitude", max_length= 100, null = True, blank= True)
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now=True)
is_transporteur = models.BooleanField(default= False)
is_client = models.BooleanField(default= False)
is_staff = models.BooleanField(default= False)
is_superuser = models.BooleanField(default= False)
is_active = models.BooleanField(default= False)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["first_name", "last_name", "username", "phone_number", "address"]
objects = CustomUserManager()
def __str__(self):
return self.username
def has_perm(self, perm: str, obj: None):
return self.is_admin
def has_module_perms(self, app_label):
return True
class Trasporteur(CustomUser):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="trasporteur_account")
matricule = models.CharField(max_length = 20, blank=True, null=True)
car_type = models.CharField(max_length = 20, choices = CAR_tYPES)
rating = models.IntegerField(blank=True, null = True)
current_location = models.CharField(max_length = 20, blank=True, null=True)
is_on_travail = models.BooleanField(default=False)
bio = models.TextField()
# last_transports = models.ManyToManyField('transport_services.TrasportService', on_delete=models.CASCADE, related_name="trasporteur_transports")
def __str__(self):
return self.user.username
class Client(CustomUser):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="client_account")
current_location = models.CharField(max_length = 20, blank=True, null=True)
# last_transports = models.ManyToManyField('transport_services.TrasportService', on_delete=models.CASCADE, related_name="client_transports")
def __str__(self):
return self.user.username
managers.py
class CustomUserManager(BaseUserManager):
def create_user(self, username, email, password, **extra_fields):
if not username:
raise ValueError(_('The username must be set'))
if not email:
raise ValueError(_('The Email must be set'))
username = username
email = self.normalize_email(email)
user = self.model(username = username, email = email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, username, email, password, **extra_fields):
"""
Create and save a SuperUser with the given 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(_('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(username, email, password, **extra_fields)
serializers.py
there is a separate registration and retrieve serializers for each class and the custom user one is just for test it is also the main one
class CustomUserSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = '__all__'
class TransporteurSerializer(serializers.ModelSerializer):
user = serializers.CharField(read_only=True,)
class Meta:
model = Trasporteur
fields = '__all__'
class ClientSerializer(serializers.ModelSerializer):
user = serializers.CharField(read_only=True,)
class Meta:
model = Client
fields = '__all__'
class TransporteurCustomRegistrationSerializer(RegisterSerializer):
user = serializers.PrimaryKeyRelatedField(read_only=True,)
first_name = serializers.CharField(required=True)
last_name = serializers.CharField(required=True)
phone_number = serializers.CharField(required=True)
address = serializers.CharField(required=True)
matricule = serializers.CharField(required=True)
car_type = serializers.ChoiceField(choices= CAR_tYPES)
def get_cleaned_data(self):
data = super(TransporteurCustomRegistrationSerializer, self).get_cleaned_data()
extra_data = {
'first_name' : self.validated_data.get('first_name', ''),
'last_name' : self.validated_data.get('last_name', ''),
'phone_number' : self.validated_data.get('phone_number', ''),
'address' : self.validated_data.get('address', ''),
'matricule' : self.validated_data.get('matricule', ''),
'car_type' : self.validated_data.get('car_type', ''),
}
data.update(extra_data)
return data
def save(self, request):
user = super(TransporteurCustomRegistrationSerializer, self).save(request)
user.is_transporteur = True
user.username = self.data.get('username')
user.email = self.data.get('email')
user.first_name = self.data.get('first_name')
user.last_name = self.data.get('last_name')
user.phone_number = self.data.get('phone_number')
user.address = self.data.get('address')
user.matricule = self.data.get('matricule')
user.car_type = self.data.get('car_type')
user.save()
transporteur = Trasporteur(
user=user,
email=self.cleaned_data.get('email'),
first_name=self.cleaned_data.get('first_name'),
last_name=self.cleaned_data.get('last_name'),
phone_number = self.cleaned_data.get('phone_number'),
address = self.cleaned_data.get('address'),
matricule=self.cleaned_data.get('matricule'),
car_type=self.cleaned_data.get('car_type'),
)
transporteur.save()
return user
class ClientCustomRegistrationSerializer(RegisterSerializer):
user = serializers.PrimaryKeyRelatedField(read_only=True,)
first_name = serializers.CharField(required=True)
last_name = serializers.CharField(required=True)
phone_number = serializers.CharField(required=True)
address = serializers.CharField(required=True)
def get_cleaned_data(self):
data = super(ClientCustomRegistrationSerializer, self).get_cleaned_data()
extra_data = {
'first_name' : self.validated_data.get('first_name', ''),
'last_name' : self.validated_data.get('last_name', ''),
'phone_number' : self.validated_data.get('phone_number', ''),
'address' : self.validated_data.get('address', ''),
}
data.update(extra_data)
return data
def save(self, request):
user = super(ClientCustomRegistrationSerializer, self).save(request)
user.is_client = True
user.email = self.data.get('email')
user.first_name = self.data.get('first_name')
user.last_name = self.data.get('last_name')
user.phone_number = self.data.get('phone_number')
user.address = self.data.get('address')
user.save()
client = Client(
user=user,
email=self.cleaned_data.get('email'),
first_name=self.cleaned_data.get('first_name'),
last_name=self.cleaned_data.get('last_name'),
phone_number = self.cleaned_data.get('phone_number'),
address = self.cleaned_data.get('address'),
)
client.save()
return user
settings related to django rest auth
AUTH_USER_MODEL = 'users.CustomUser'
ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username'
ACCOUNT_UNIQUE_USERNAME = True
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = False
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = '/?verification=1'
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/?verification=1'
SITE_ID = 1
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
thanks for your help
Solved by removing the inheritance from custom user. You wouldn't inherit from the abstract class.
Trasporteur(CustomUser) => Trasporteur(models.Model):
I am trying to build a project management system and have to add client to my database. For this I have created a form as below
forms.py
class AddClientForm(forms.Form):
email = forms.EmailField(label="Email", max_length=50, widget=forms.EmailInput(attrs={"class":"form-control"}))
password = forms.CharField(label="Password", max_length=50, widget=forms.PasswordInput(attrs={"class":"form-control"}))
first_name = forms.CharField(label="First Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
last_name = forms.CharField(label="Last Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
username = forms.CharField(label="Username", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
phone = forms.CharField(label="Phone", max_length=15, widget=forms.TextInput(attrs={"class":"form-control"}))
#For Displaying Projects
try:
projects = Projects.objects.all()
project_list = []
for project in projects:
single_project = (project.id, project.project_name)
project_list.append(single_project)
except:
project_list = []
#For Displaying Contracts
try:
contracts = Contracts.objects.all()
contract_list = []
for contract in contracts:
single_contract = (contract.id, contract.contract_name)
contract_list.append(single_contract)
except:
contract_list = []
project_name = forms.ChoiceField(label="Project", choices=project_list, widget=forms.Select(attrs={"class":"form-control"}))
contract_id = forms.ChoiceField(label="Contract", choices=contract_list, widget=forms.Select(attrs={"class":"form-control"}))
location = forms.ChoiceField(label="Location", choices=States, widget=forms.Select(attrs={"class":"form-control"}))
Then i have created the following views.py
def add_client(request):
form = AddClientForm()
context = {
"form": form
}
return render(request, 'admintemplate/add_client_template.html', context)
def add_client_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect('add_client')
else:
form = AddClientForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
phone = form.cleaned_data['phone']
location = form.cleaned_data['location']
project_id = form.cleaned_data['project_name']
contract_id = form.cleaned_data['contract_id']
try:
user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3)
user.clients.location = location
user.client.primaryphone = phone
project_obj = Projects.objects.get(id=project_id)
user.clients.project_id = project_obj
contract_obj = Contracts.objects.get(id=contract_id)
user.clients.contract_id = contract_obj
user.clients.save()
messages.success(request, "Client Added Successfully!")
return redirect('add_client')
except:
messages.error(request, "Failed to Add Client!")
return redirect('add_client')
else:
return redirect('add_client')
And my models.py is as follows
class Clients(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE)
primaryphone = models.CharField(max_length=15, unique=True)
location = models.CharField(max_length=30, choices=States)
project_id = models.ForeignKey(Projects, on_delete=models.DO_NOTHING, default=1)
contract_id = models.ForeignKey(Contracts, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
I am not sure why the data is not being saved in the clients model. ANy help would be appreciated.
I have a form that users can fill to leave a review. On the same page, the reviews are displayed with a button to edit the review. When the edit button is clicked, I would like for the form to be pre-filled with the appropriate review data, so that it can be edited and updated in the database.
models
class Clinic(models.Model):
practitioner = models.OneToOneField(User, on_delete=models.CASCADE)
lat = models.FloatField(null=True, blank=True)
lng = models.FloatField(null=True, blank=True)
web = models.CharField(null=True, blank=True, max_length=128)
name = models.CharField(max_length=128, )
phone = PhoneNumberField()
description = models.TextField(max_length=5000)
street = models.CharField(max_length=128, )
city = models.CharField(max_length=128, )
def __str__(self):
return self.name
def save(self):
super().save()
class Reviews(models.Model):
title = models.CharField(max_length=128)
body = models.TextField(max_length=500)
author = models.ForeignKey(User, on_delete=models.CASCADE)
clinic = models.ForeignKey(Clinic,
null=True,
blank=True,
on_delete=models.CASCADE)
Form
class ReviewForm(forms.ModelForm):
class Meta:
model = Reviews
fields = (
'title',
'body',
)
View
def clinic_profile(request, clinic_id):
clinic = Clinic.objects.filter(pk=clinic_id)
form = ReviewForm(request.POST)
if request.method == 'POST':
if form.is_valid():
r_clinic = Clinic.objects.get(pk=clinic_id)
title = form.cleaned_data.get("title")
body = form.cleaned_data.get("body")
review = Reviews(title=title,
body=body,
author=request.user,
clinic=r_clinic)
review.save()
messages.success(request, f'Thank you for leaving a review!')
clinic_reviews = Reviews.objects.filter(clinic=clinic_id)
latlng = {
"lat": clinic[0].lat,
"lng": clinic[0].lng,
"name": clinic[0].name
}
def get_mods():
profile = Profile.objects.filter(user=Clinic.objects.get(
pk=clinic_id).practitioner)
mods = profile[0].mods.all().values('name') if profile else []
mods = [(q['name']) for q in mods]
return mods
return render(
request, 'clinic_profile.html', {
'clinic': clinic,
'mods': get_mods,
'latlng': latlng,
'api_key': api_key,
'reviews': clinic_reviews,
'form': form,
})
Screenshot
When requesting a blank RegisterForm, I get a KeyError. I believe that when I click the link on the site, I submit a GET request to the register method and the form1 = RegisterForm() line fires. I believe there is something wrong with my RegisterForm class but I can't figure out what it is. I'm using the User model and UserCreationForm. Any help is greatly appreciated.
KeyError at /profile/pm/register u'username'
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vagrant/project/tmp/user_profile/views.py" in register
77. form1 = RegisterForm()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/forms.py" in __init__
97. self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': ''})
Exception Type: KeyError at /profile/pm/register
Exception Value: u'username'
views.py
def register(request, user_type):
if user_type not in ["pm", "hm"]:
raise Http404
if request.user.is_authenticated():
return redirect(reverse('index'))
if user_type == 'hm':
userTypeChoices = [Profile.RecruiterAgency, Profile.RecruiterInternal, Profile.HiringManager]
else:
userTypeChoices = [Profile.PMEmployee, Profile.PMContractConsultant, Profile.PMBoth]
if request.method =="POST":
# accept tos
if 'accepted_tos' in request.POST:
return acceptedTOS(request)
form1 = RegisterForm(request.POST)
form2 = ProfileForm(request.POST)
if form1.is_valid() and form2.is_valid():
user = form1.save()
profile = Profile()
profile.user_id = user.id
profile.company = form2.cleaned_data["company"]
profile.phone = form2.cleaned_data["phone"]
profile.user_type = form2.cleaned_data["user_type"]
profile.save()
if profile.user_type in [Profile.PMEmployee, Profile.PMContractConsultant, Profile.PMBoth]:
prospect = Prospect(profile=profile)
prospect.save()
else:
employer = Employer(profile=profile)
employer.save()
return JsonResponse({'message':'success'})
else:
return JsonResponse({'message':form2.errors})
else:
form1 = RegisterForm()
form2 = ProfileForm()
return render(request, 'profile/register.html', {'form1':form1, 'form2':form2, 'userType':user_type, 'userTypeChoices':userTypeChoices})
forms.py
class RegisterForm(UserCreationForm):
email = forms.EmailField(label = "Email")
first_name = forms.CharField(label = "First name")
last_name = forms.CharField(label = "Last name")
class Meta:
model = User
fields = ("email", "first_name", "last_name")
def clean_email(self):
email = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise forms.ValidationError('Email already in use.')
return email
def save(self, commit=True):
user = super(RegisterForm, self).save(commit=False)
user.username = self.cleaned_data["email"]
if commit:
user.save()
return user
models.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
phone = models.CharField(max_length=200, null=True, blank=True)
RecruiterAgency = 'ra'
RecruiterInternal = 'ri'
HiringManager = 'hm'
PMEmployee = 'pe'
PMContractConsultant = 'pc'
PMBoth = 'pm'
USER_TYPE_CHOICES = (
(RecruiterAgency, 'Recruiter - Agency'),
(RecruiterInternal, 'Recruiter - Internal'),
(HiringManager, 'Hiring Manager'),
(PMEmployee, 'PM - Employee'),
(PMContractConsultant, 'PM - Contract / Consultant'),
(PMBoth, 'PM - Both'),
)
user_type = models.CharField(max_length=2, choices=USER_TYPE_CHOICES, default=RecruiterAgency)
company = models.CharField(max_length=200, null=True, blank=True)
bio = models.TextField(null=True, blank=True)
accepted_tos = models.BooleanField(default=False)
profile_photo = models.ImageField(null=True, blank=True, upload_to="avatar")
def __str__(self):
return "%s's profile" % self.user.email
class Prospect(models.Model):
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True, blank=True, related_name="profile_prospects")
RestrictedCompany = models.ForeignKey(RestrictedCompany, on_delete=models.CASCADE, null=True, blank=True, related_name="company_prospects")
badge = models.ManyToManyField(Badge, blank=True, related_name="badge_prospects")
certification = models.ManyToManyField(Certification, blank=True, related_name="certification_prospects")
LargestProject1 = 'lp1'
LargestProject2 = 'lp2'
LargestProject3 = 'lp3'
LargestProject4 = 'lp4'
LargestProject5 = 'lp5'
LARGEST_PROJECT_CHOICES = (
(LargestProject1, '$1-100,000'),
(LargestProject2, '$100,001-$500,000'),
(LargestProject3, '$500,001-$1,000,000'),
(LargestProject4, '$1,000,001-$5,000,000'),
(LargestProject5, '$5,000,001+'),
)
largest_project = models.CharField(max_length=3, choices=LARGEST_PROJECT_CHOICES, default=LargestProject1)
add_to_pool = models.BooleanField(default=False)
LargestTeam1 = 'lt1'
LargestTeam2 = 'lt2'
LargestTeam3 = 'lt3'
LargestTeam4 = 'lt4'
LargestTeam5 = 'lt5'
LargestTeam6 = 'lt6'
LARGEST_TEAM_CHOICES = (
(LargestTeam1, '0-5'),
(LargestTeam2, '6-10'),
(LargestTeam3, '11-20'),
(LargestTeam4, '21-50'),
(LargestTeam5, '51-100'),
(LargestTeam6, '100+'),
)
largest_team = models.CharField(max_length=3, choices=LARGEST_TEAM_CHOICES, default=LargestTeam1)
Contract = 'ct'
FullTimeEmployee = 'fe'
Both = 'bo'
Position_Type_CHOICES = (
(Contract, 'Contract'),
(FullTimeEmployee, 'Full-Time Employee'),
(Both, 'Both'),
)
position_type = models.CharField(max_length=2, choices=Position_Type_CHOICES, default=Contract)
resume = models.FileField(null=True, blank=True, upload_to="resume")
EntryLevel = 'el'
Junior = 'jn'
Professional = 'pr'
TIER_CHOICES = (
(EntryLevel, 'Entry-Level'),
(Junior, 'Junior'),
(Professional, 'Professional'),
)
tier = models.CharField(max_length=2, choices=TIER_CHOICES, default=EntryLevel)
billable_rate = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
annual_salary = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
total_years_exp = models.DecimalField(max_digits=4, decimal_places=2, null=True, blank=True)
def __str__(self):
return "%s" % self.profile.user.email
class Employer(models.Model):
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True, blank=True, related_name="profile_employers")
title = models.CharField(max_length=200, null=True, blank=True)
street = models.CharField(max_length=200, null=True, blank=True)
city = models.CharField(max_length=200, null=True, blank=True)
zip = models.CharField(max_length=200, null=True, blank=True)
state = models.CharField(max_length=200, null=True, blank=True)
country = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return "%s" % self.profile.user.email
The comments were correct and very helpful! I needed to rename the "email" field on the RegisterForm to "username":
class RegisterForm(UserCreationForm):
username = forms.EmailField(label = "Email")
first_name = forms.CharField(label = "First name")
last_name = forms.CharField(label = "Last name")
class Meta:
model = User
fields = ("username", "first_name", "last_name")
def clean_email(self):
username = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise forms.ValidationError('Email already in use.')
return username
def save(self, commit=True):
user = super(RegisterForm, self).save(commit=False)
user.username = self.cleaned_data["email"]
if commit:
user.save()
return user
You have come across this issue where the UserCreationForm crashes if USERNAME_FIELD (in your case username) is not a form field.
The issue only affects Django 1.10, it doesn't affect earlier versions of Django. It will be fixed in the upcoming Django 1.10.1 release.