I'm attempting to determine if a user on my site is an adult by using his birthday and today's date.
I have a boolean attribute in my user called adult and I attempt to set it in the following way
from datetime import date
...
def set_adult(self):
today = date.today()
age = today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))
if age > 18:
self.adult = True
else:
self.adult = False
When registering a user, I have a field for adding a birthday
class MyRegistrationForm(forms.ModelForm):
"""
Form for registering a new account.
"""
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
email = forms.EmailField(widget=forms.EmailInput,label="Email")
date_of_birth = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y'), label="Date of birth (MM/DD/YYYY)")
gender = forms.ChoiceField(widget=RadioSelect, choices=GENDER_CHOICES)
password1 = forms.CharField(widget=forms.PasswordInput,
label="Password")
password2 = forms.CharField(widget=forms.PasswordInput,
label="Password (again)")
class Meta:
model = MyUser
fields = ['email', 'date_of_birth', 'gender', 'password1', 'password2']
def clean(self):
"""
Verifies that the values entered into the password fields match
NOTE: Errors here will appear in ``non_field_errors()`` because it applies to more than one field.
"""
cleaned_data = super(MyRegistrationForm, 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(MyRegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
user.set_adult # NOT WORKING
if commit:
user.save()
return user
When I check my admin page after adding an "adult birthday", the result is always false.
Am I making a mistake in my form or in my set_adult method?
user.set_adult # NOT WORKING
You are missing () in function call:
user.set_adult()
Related
So, I am a beginner and I'm coding a django application that has a 3 user types in total but to make the code readable and understandable I'm just gonna assume we have 2 user types. One is a doctor and one is a patient.
I've created this custom user so far:
in models.py
class User(AbstractUser):
is_doc = models.BooleanField(default=False)
is_patient = models.BooleanField(default=False)
objects = UserManager()
manager.py
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
if email is None:
raise TypeError('Users must have an email address.')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save()
return user
def create_patient(self, email, password):
if password is None:
raise TypeError('Must have a password')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.is_patient = True
user.save()
def create_superuser(self, email, password):
if password is None:
raise TypeError('Superusers must have a password.')
user = self.create_user(email, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
Patient Model is as follows:
class Patient(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=70)
last_name = models.CharField(max_length=70)
address = models.CharField(max_length=210)
phone = models.CharField(max_length=15)
email = models.EmailField(max_length=110)
password = models.CharField(max_length=65)
def __str__(self):
return self.first_name + " " + self.last_name
My form for Patient:
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ['first_name', 'last_name', 'address', 'phone', 'email', 'password']
widgets = {
'first_name': forms.TextInput(attrs={'placeholder': 'First Name'}),
'last_name': forms.TextInput(attrs={'placeholder': 'Last Name'}),
'address': forms.TextInput(attrs={'placeholder': 'Address'}),
'phone': forms.TextInput(attrs={'placeholder': 'Phone Number'}),
'email': forms.EmailInput(attrs={'placeholder': 'Email'}),
'password': forms.PasswordInput(attrs={'placeholder': 'Password (Minimum Length: 8)'}),
}
Current Views.py:
def RegPatient(request):
if request.method == "POST":
form = PatientForm(request.POST)
if form.is_valid():
FName = form.cleaned_data['first_name']
LName = form.cleaned_data['last_name']
C_Address = form.cleaned_data['address']
C_Phone = form.cleaned_data['phone']
C_Email = form.cleaned_data['email']
C_Password = form.cleaned_data['password']
Reg = Patient(first_name= FName, last_name= LName, address= C_Address, phone= C_Phone, email= C_Email, password= C_Password)
Reg.save()
return HttpResponseRedirect('/Login/')
else:
for field in form.errors:
form[field].field.widget.attrs['class'] += ' is-invalid'
return render(request, 'Home/RegPatient.html', {'form': form})
else:
form = PatientForm()
return render(request, 'Home/RegPatient.html', {'form': form})
I have separate signups for patient and doctor and don't want a user type field in my form so I have all the detail fields in my form except user type.
How should my view look like so that it saves Patient with a user type is_patient? and am I missing something out? Cause I've tried to edit it so many times, tried getting help from Django Docs but I'm still stuck.
First, lets talk about the Manager and Models. The Manager you are using is not really necessary, its possible to just set up the field on User object creation. As for the Model you can use model inheritance to have an extended Patient model based on your User model:
class User(AbstractUser):
is_doctor = models.BooleanField(default=False)
is_patient = models.BooleanField(default=False)
class Patient(User):
address = models.CharField(max_length=210)
phone = models.CharField(max_length=15)
class Meta:
verbose_name_plural = "Patients"
Although, I would say the right approach to your problem is to use Django authentication groups, instead of adding fields to your User model.
As for the signup form, it should contain confirmation and validation of the password and the username field unless you are doing a login with email. To hold the information of is_patient field, use an HiddenInput (I couldn't replicate it with 'ModelForm' will need to dig further into that.):
forms.py
from django.contrib.auth.hashers import make_password
from django.forms import ValidationError
class PatientSignUpForm(forms.Form):
username = forms.CharField(
required=True,
widget=forms.TextInput(attrs={'placeholder': 'username'}))
first_name = forms.CharField(
required=True,
widget=forms.TextInput(attrs={'placeholder': 'first name'}))
last_name = forms.CharField(
required=False,
widget=forms.TextInput(attrs={'placeholder': 'last name'}))
email = forms.EmailField(
required=True,
widget=forms.TextInput(attrs={'placeholder': 'email'}))
address = forms.CharField(
required=True,
widget=forms.TextInput(attrs={'placeholder': 'address'}))
phone = forms.CharField(
required=True,
widget=forms.TextInput(attrs={'placeholder': 'XXX-XXXXXXXXX'}))
password = forms.CharField(required=True, widget=forms.PasswordInput)
password_confirmation = forms.CharField(required=True, widget=forms.PasswordInput)
is_patient = forms.BooleanField(widget=forms.HiddenInput)
def clean(self):
password = self.cleaned_data['password']
password_confirmation = self.cleaned_data['password_confirmation']
if len(password) < 8 or len(password_confirmation) < 8:
raise ValidationError("Passwords must have at least 8 characters")
elif password != password_confirmation:
raise ValidationError("Passwords must be equal")
else:
self.cleaned_data['password'] = make_password(self.cleaned_data['password_confirmation'])
del self.cleaned_data['password_confirmation']
return self.cleaned_data
Lastly, in views.py create an instance of PatientSignUpForm with an initial value for is_patient field.
from app import models, forms
def patient_signup(request):
if request.method == 'POST':
form = forms.PatientSignUpForm(request.POST)
if form.is_valid():
models.Patient.objects.create(**form.cleaned_data)
return redirect('')
else:
form = forms.PatientSignUpForm(initial={'is_patient': True})
return render(request, 'patient_signup.html', {'form': form})
ERROR: repetitive record violates the singular constraint "user_otherinfo_user_id_key"
DETAIL: The key "(user_id) = (52)" already exists.
models.py
class OtherInfo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
phone = models.CharField(max_length=11,verbose_name="phone number")
location = models.CharField(max_length=50,verbose_name="location")
profile_image = models.FileField(blank = True,null = True,verbose_name="image")
class Meta:
verbose_name_plural = 'Other informations'
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
OtherInfo.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.otherinfo.save()
forms.py
class LoginForm(forms.Form):
username = forms.CharField(label = "Username")
password = forms.CharField(label = "Parola",widget = forms.PasswordInput)
class RegisterForm(forms.ModelForm):
password1 = forms.CharField(max_length=100, label='Parola',widget=forms.PasswordInput())
password2 = forms.CharField(max_length=100, label='Parola again', widget=forms.PasswordInput())
phone_number = forms.CharField(required=False, max_length=11, label='Phone Number')
location = forms.CharField(required=False, max_length=50, label='Location')
profile_image = forms.FileField(required=False, label="Image")
class Meta:
model = User
fields = [
'first_name',
'last_name',
'email',
'username',
'password1',
'password2',
'phone_number',
'location',
'profile_image',
]
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords do not match!")
return password2
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class ProfileForm(forms.ModelForm):
class Meta:
model = OtherInfo
fields = ('phone', 'location', 'profile_image')
views.py
#login_required
#transaction.atomic
def updateprofile(request):
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST, instance=request.user.otherinfo)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, _('Your profile has been successfully updated!'))
return redirect('/user/profile/')
else:
messages.error(request, _('Please correct the following error.'))
else:
user_form = UserForm(instance=request.user)
profile_form = ProfileForm(instance=request.user.otherinfo)
return render(request, 'user/update_user.html', {
'user_form': user_form,
'profile_form': profile_form
})
def register(request):
form = RegisterForm(request.POST or None,request.FILES or None )
if form.is_valid():
user = form.save(commit=False)
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
username = form.cleaned_data.get("username")
email = form.cleaned_data.get('email')
password = form.cleaned_data.get('password1')
phone = form.cleaned_data.get('phone_number')
location = form.cleaned_data.get('location')
profile_image = form.cleaned_data.get('profile_image')
user.set_password(password)
user.save()
new_user = authenticate(username=user.username, first_name=first_name, last_name=last_name, email=email, password=password)
OtherInfo.objects.create(user=new_user,phone=phone,location=location,
profile_image=profile_image)
login(request,new_user)
messages.info(request,"Successfully Register ...")
return redirect("/")
context = {
"form" : form
}
return render(request,"user/register.html",context)
In Django, the user can register before updating the profile. When I add the profile update code, now the user is failing to register. How can I solve the problem?
It's simply a matter of not creating twice a OtherInfo for the same User:
in the post_save handler of saving a User, you create a OtherInfo object for the user.
in your view, you first create the User, hence you already create the OtherInfo associated with the user.
then you have OtherInfo.objects.create(user=new_user,phone=phone,location=location,
profile_image=profile_image)
This last instruction will fail, because you're trying to create a second OtherInfo for the same user. So you can do two things:
Remove the post_save signal handler that creates the OtherInfo object
or
Update new_user.otherinfo by setting the various values and saving it instead of creating it.
You need to delete the data entry with id=51.
The error you get is related to database, that the entry with id you are trying to create already exists.
Drop your database and create a new one(If you are not on a production environment)
I have a Django form consisting of a email and name field. I want to validate the name to have more than 8 characters. I have used the following code. But it is not working.
class SignUpForm(forms.ModelForm):
class Meta:
model=SignUp
fields=('email','name')
def emailValidation(self):
name=self.cleaned_data.get('name')
if len(name) <=8:
raise forms.ValidationError("name cannot be less than 8")
models.py
class SignUp(models.Model):
name=models.CharField(max_length=200)
email=models.EmailField()
timestamp=models.DateTimeField(auto_now_add=True, auto_now=False)
updated=models.DateTimeField(auto_now=True,auto_now_add=False)
def __unicode__(self):
return self.name
views.py
def home(request):
form=SignUpForm(request.POST or None)
if form.is_valid():
instance=form.save(commit=False)
instance.save()
print instance.timestamp
return render(request, 'home.html',{'form':form})
In your SignUpForm, in the function emailValidation, you haven't returned 'name'. Also a major mistake is that you have to name the function clean_(field_name) and NOT emailValidation.
This should do it I guess:
class SignUpForm(forms.ModelForm):
class Meta:
model=SignUp
fields=('email','name')
def clean_name(self):
name=self.cleaned_data.get('name')
if len(name) <=8:
raise forms.ValidationError("name cannot be less than 8")
return name
You need to use correct name for your validation method. Django forms will call methods with the format clean_<fieldname>.
Also you seem to be confused about which field you are validating; your email validation method should be called clean_email and should access the email value via form.cleaned_data['email'], and the name one should be called clean_name and access form.cleaned_data['name'].
Something like this may give you some guidance.
class RegistrationForm(forms.ModelForm):
"""
Form for registering a new account.
"""
firstname = forms.CharField(label="First Name")
lastname = forms.CharField(label="Last Name")
phone = forms.CharField(label="Phone")
email = forms.EmailField(label="Email")
password1 = forms.CharField(label="Password")
password2 = forms.CharField(label="Password (again)")
min_password_length = 8
class Meta:
model = User
fields = ['firstname', 'lastname', 'phone', 'email', 'password1', 'password2']
def clean_email(self):
email = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise forms.ValidationError(u'Email "%s" is already in use! Please log in or use another email!' % email)
return email
def clean_password1(self):
" Minimum length "
password1 = self.cleaned_data.get('password1', '')
if len(password1) < self.min_password_length:
raise forms.ValidationError("Password must have at least %i characters" % self.min_password_length)
else:
return password1
def clean(self):
"""
Verifies that the values entered into the password fields match
NOTE: Errors here will appear in ``non_field_errors()`` because it applies to more than one field.
"""
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 didn't match. Please try 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
class CustomAccount(models.Model):
user = models.OneToOneField("auth.User")
role = models.CharField(max_length = 50, default = 'student', choices=APPROVAL_CHOICES)
balance = models.FloatField( default = 0 )
timezone = models.CharField(max_length = 200)
def __str__(self):
return self.user.username +" ["+ self.role + "]"
class CustomAccountForm(forms.ModelForm):
username = forms.CharField(max_length=30 )
email = forms.EmailField(max_length=255 )
password1 = forms.CharField(label= "Password",widget=forms.PasswordInput())
password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput , help_text="Enter the same password as above, for verification.")
def save(self, commit= True):
user = User.objects.create_user(username = self.cleaned_data['username'], email = self.cleaned_data['email'] , password = self.cleaned_data['password1'])
user.save()
self.user = user
return super(CustomAccountForm, self).save(commit=commit)
def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("A user with that username already exists.")
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError("The two password fields didn't match.")
return password2
def clean_email(self):
email = self.cleaned_data["email"]
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError("A user with that emailaddress already exists.")
class Meta:
model = CustomAccount
exclude = ['balance','user']
I want to create Custom account in Django Admin section using single form which has fields of auth.User and CustomAccount Model. I have getting error IntegrityError at /admin/mylogin/customaccount/add/
NOT NULL constraint failed: mylogin_customaccount.user_id
Since you are getting a not null error, I think you need to specify that the field is not required. Here is an example from one of my apps. This says that the form field is not required.
class arunModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
myuser = kwargs.pop('user', None)
super(arunModelForm, self).__init__(*args, **kwargs)
self.fields['nanoadded'].required = False
self.fields['response'].required = False
I also include this in my models so that my model fields can be null, like this:
class arun(models.Model):
auser = models.CharField(max_length=50, null=True)
adate = models.DateField(null=True)
atime = models.TimeField(null=True)
If I still get not null errors after I do both of these things, I fill the field with a place holder value to allow me to further investigate the problem.
You have removed the user from the form and in the save method, you have assigned self.user in save method. So when saving the form, the user attribute is not used for CustomAccountForm and the user field for CustomAccount is None.
Your save method should look like:
def save(self, commit= True):
user = User.objects.create_user(username =self.cleaned_data['username'], email = self.cleaned_data['email'] , password = self.cleaned_data['password1'])
user.save()
obj = super(CustomAccountForm, self).save(commit=False)
obj.user = user
obj.save()
I have a custom registration form for my users to add a profile on my app. However, a bug has recently popped up in that the form is not saving the information that is put into all the fields.
My user model, MyUser has a ManyToMany relationship with another model, Interest, and this is where the issues are arising. I am not sure if it is the RegistrationForm or the register view that is causing it, so I have included both below, as well as the model code.
I also have a view for the users to update their profile, also included, once it is created, and this is working absolutely perfectly. This is the personal view.
As I say, it is only the Interest field that is not being returned, even though it is being filled in on the registration page.
Any help or advice is much appreciated, thanks.
models.py
class Interest(models.Model):
title = models.TextField()
def __unicode__(self):
return self.title
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
date_of_birth = models.DateField()
course = models.ForeignKey(Course, null=True)
location = models.ForeignKey(Location, null=True)
interests = models.ManyToManyField(Interest, null=True)
bio = models.TextField(blank=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['date_of_birth']
views.py
def register(request):
if request.method == 'POST':
form = RegistrationForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('/friends/home/')
else:
form = RegistrationForm()
template = "adduser.html"
data = { 'form': form, }
return render_to_response(template, data, context_instance=RequestContext(request))
#login_required(login_url='/friends/login/')
def personal(request):
"""
Personal data of the user profile
"""
profile = request.user
if request.method == "POST":
form = ProfileForm(request.POST, instance=profile)
if form.is_valid():
form.save()
messages.add_message(request, messages.INFO, _("Your profile information has been updated successfully."))
return redirect('/friends/success/')
else:
form = ProfileForm(instance=profile)
template = "update_profile.html"
data = { 'section': 'personal', 'form': form, }
return render_to_response(template, data, context_instance=RequestContext(request))
forms.py
class RegistrationForm(forms.ModelForm):
"""
Form for registering a new account.
"""
email = forms.EmailField(widget=forms.TextInput, label="Email")
password1 = forms.CharField(widget=forms.PasswordInput,
label="Password")
password2 = forms.CharField(widget=forms.PasswordInput,
label="Password (again)")
course = forms.ModelChoiceField(queryset=Course.objects.order_by('title'))
location = forms.ModelChoiceField(queryset=Location.objects.order_by('location'))
class Meta:
model = MyUser
fields = [
'first_name',
'last_name',
'date_of_birth',
'email',
'password1',
'password2',
'course',
'location',
'interests',
'bio',
]
def __init__(self, *args, **kwargs):#Sort interests alphabetically
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields['interests'].queryset = Interest.objects.order_by('title')
def clean(self):
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 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
Since you use commit=false for the super(RegistrationForm, self).save call, it doesn't save the many-to-many field. You therefore need to add self.save_m2m() after user.save() in your save() method of RegistrationForm.
See https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method
EDIT: save_m2m() is on the Form, not the Model