NOT NULL constraint failed: store_customer.first_name - django

NOT NULL constraint failed: store_customer.first_name
Request Method: GET
Request URL: http://127.0.0.1:8000/signup/
Django Version: 4.1.4
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: store_customer.first_name
models.py
class Customer(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=500)
def register(self):
self.save()
def __str__(self):
return self.first_name
views.py
def signup(request):
if request == 'GET':
return render(request, 'signup.html')
else:
first_name = request.POST.get('firstname')
last_name = request.POST.get('lastname')
phone = request.POST.get('phone')
email = request.POST.get('email')
password = request.POST.get('password')
customer = Customer(first_name=first_name, last_name=last_name,phone=phone,email=email,password=password)
customer.register()
# return HttpResponse( 'signup successful' )
return render(request, 'signup.html')

No need to handle GET requests it's automatically handled by Django Just handle POST requests like this...
models.py
class Customer(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=500)
def __str__(self):
return self.first_name
views.py
def signup(request):
if request == 'POST': #<------- handled POST request
first_name = request.POST.get('firstname')
last_name = request.POST.get('lastname')
phone = request.POST.get('phone')
email = request.POST.get('email')
password = request.POST.get('password')
customer = Customer(first_name=first_name, last_name=last_name,phone=phone,email=email,password=password)
customer.save()
return redirect('/signup/')
return render(request, 'signup.html') #<------- handled GET request

Are you sending first name in the form? By default 'models.CharField' has a null and 'blank' option set to false Django ref. - this means that the it need to be set to something different that null when saving.
Your error suggests that the first_name was not sent in POST request (from form).

Related

Error in Django Model and Serializer - (1048, "Column 'dso_id' cannot be null")

I am trying to create a user profile, I feel i have everything correct but still it doesn't register.
You see my codebase below, please help
What i did:
Models.py:
class UserManager(BaseUserManager):
def create_user(self, username, email, name, address,roleId,customerId,dso password=None,):
if username is None:
raise TypeError('User should have a userame')
if email is None:
raise TypeError('Users should have a Email')
user = self.model(username=username , email = self.normalize_email(email))
user.set_password(password)
user.save()
return user
def create_superuser(self, username, email, password=None):
if password is None:
raise TypeError('User should have a password')
user=self.create_user(username,email,password,)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(models.Model):
dso = models.ForeignKey(Dso,related_name='dso',default=NULL,blank=False,on_delete=models.CASCADE)
name = models.CharField(max_length=70, blank=False, default='')
email = models.EmailField(max_length=70, blank=False, default='')
password = models.CharField(max_length=70, blank=False, default='')
address = models.CharField(max_length=70, blank=False, default='')
roleId = models.IntegerField(blank=False, default='1')
isActive = models.BooleanField(blank=False, default=True)
customerId = models.CharField(max_length=70, blank=False, default='')
dateJoined = models.DateTimeField(auto_now_add=False, blank=False, default=NULL)
#property
def energy_data(self):
energydata = EnergyData.objects.filter(customerId=self.customerId).first()
return energydata
Serializers.py:
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(max_length = 68, min_length=6, write_only = True)
class Meta:
model=User
fields=['email','username','password','name','address','customerId',
'dso', 'roleId']
def validate(self, attrs):
email = attrs.get('email', '')
username = attrs.get('username', '')
if not len(username) >= 4:
raise serializers.ValidationError('Username must be morethan 4 letters or characters')
return attrs
def create(self, validated_data):
return User.objects.create_user(**validated_data)
Views.py:
class RegisterView(generics.GenericAPIView):
serializer_class= RegisterSerializer
def post(self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
user= User.objects.get(email=user_data['email'])
token = RefreshToken.for_user(user).access_token
current_site = get_current_site(request).domain
relativeLink = reverse('email-verify')
absolute_url = 'http://'+current_site+relativeLink+"?token="+str(token)
email_body= 'Hi '+ user.username + ' Use this link below to verify your email \n'+ absolute_url
data = {'email_subject': 'Verify Your Email', 'email_body': email_body , 'to_email': user.email}
Util.send_email(data)
return Response(user_data, status = status.HTTP_201_CREATED)
URL Path:
path('register/', RegisterView.as_view(), name="register" )
When i do this and try to test i get the error, '(1048, "Column 'dso_id' cannot be null")'
Please kindly help as i am new to django rest framework.
error thrown from this line in User Model
dso = models.ForeignKey(Dso,related_name='dso',default=NULL,blank=False,on_delete=models.CASCADE)
you set default NULL while don't set null and blank fields True
so change to this or remove default=NULL(None)
dso = models.ForeignKey(Dso,related_name='dso',default=NULL, blank=True, null=True, on_delete=models.CASCADE)
also you should not useNULL in python, use None replace that

Extract and save data from another model

In my app users create a project then create a team and invite team members by sending them a mail to sign up to the app.
I am trying to figure out how to add the invited user to the team that was created just before.
I tried using : TeamMember.user = user but obviously it does not work ;)
Could you help me to make it work ?
Registration/views.py:
def TeamRegister(request):
if request.method == 'POST':
form = TeamMembersForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
password = MyUser.objects.make_random_password()
user.set_password(password)
user.is_active = False
user.is_employee = True
TeamMember.user = user
user.save()
u1 = user.id
a1 = MyUser.objects.get(email = request.user.email)
a2 = Project.objects.filter(project_hr_admin = a1)
a3 = a2.latest('id')
a4 = a3.team_id
a4.members.add(u1)
current_site = get_current_site(request)
message = render_to_string('acc_active_email.html', {
'user':user,
'domain':current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app'
to_email = form.cleaned_data.get('email')
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
return HttpResponse('An email have been sent to your user asking him to sign in')
else:
form = TeamMembersForm()
return render(request, 'team_register.html', {'form': form})
app/models.py
class Team(models.Model):
team_name = models.CharField(max_length=100, default = '')
team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
members = models.ManyToManyField(MyUser, related_name="members")
def __str__(self):
return self.team_name
class Project(models.Model):
name = models.CharField(max_length=250)
team_id = models.ForeignKey(Team, blank=True, null=True)
project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
def get_absolute_url(self):
return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk})
def __str__(self):
return self.name
You need to somehow identify the Team as well. If you have the team in the view, then you can just create the TeamMember object as such:
# Just one suggestion of how this could be done, but this shouldn't work out of the box
TeamMember.objects.create(user_id=user.id,
team_id=Team.objects.get(id=form.cleaned_data['team_id']))
And as for your models, please consult Django documentation on M2M relationships in Django: https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_many/
Create a ManyToManyField and use the TeamMember as the through model or delete it at all, because Django generates that automatically as well.

Key Error with form - DJANGO

I have a project in django and I am creating a simple form that will allow a user to create a simple profile that asks for name and date of birth and location. I am getting a key error with the date of birth section and I dont know exactly why.
I am trying to collect data and store it to then later added it to a database record.
Here is the views file:
cd = form.cleaned_data
first_name = cd['first_name']
last_name = cd['last_name']
dob_month = cd['dob_month']
dob_day = ['dob_day']
dob_year = ['dob_year']
city = cd['city']
state = cd['state']
phone = cd['phone']
privacy = cd['privacy']
Here is the models file:
user = models.ForeignKey(User, on_delete=models.CASCADE) # server
first_name = models.CharField(max_length=25, default='first')
last_name = models.CharField(max_length=25, default='last')
dob_month = models.IntegerField(default=0)
dob_day = models.IntegerField(default=0)
dob_year = models.IntegerField(default=0)
city = models.CharField(max_length=45) # user
state = models.CharField(max_length=25, default='state')
phone = models.BigIntegerField(default=0) # user
privacy = models.SmallIntegerField(default=1) # user
created = models.DateTimeField(auto_now_add=True) # server
here is the forms file:
class ProfileForm(forms.ModelForm):
split_choices = (('1', 'public'),
('2', 'private'))
privacy = forms.TypedChoiceField(
choices=split_choices, widget=forms.RadioSelect, coerce=int
)
dob = forms.DateField(widget=extras.SelectDateWidget)
class Meta:
model = Profile
fields = ['first_name', 'last_name', 'dob', 'city', 'state', 'phone', 'privacy']
and finally, here is the error that I am getting:
KeyError at /setup_profile/
'dob_month'
Request Method: POST
Request URL: http://127.0.0.1:8000/setup_profile/
Django Version: 1.8.6
Exception Type: KeyError
Exception Value:
'dob_month'
Exception Location: C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in profile_setup, line 292
first_name 'omar'
last_name 'jandali'
dob_month '1'
dob_day '23'
dob_year '2024'
city 'riverside'
state 'ca'
phone '9515343666'
privacy '1'
submit 'submit'
UPDATED:
here is the views.py file but the issue is with the cd['dobv_month'], but i have no idea why the error is coming from there.
def profile_setup(request):
if 'username' not in request.session:
return redirect('login')
else:
# the following is just going to grab the currently logged in user and
# save the profile information to the appropriate user
username = request.session['username']
currentUser = User.objects.get(username = username)
# the following is the provessing for the form where the user entered
# the profile informaiton
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
first_name = cd['first_name']
last_name = cd['last_name']
dob_month = cd['dob_month']
dob_day = ['dob_day']
dob_year = ['dob_year']
city = cd['city']
state = cd['state']
phone = cd['phone']
privacy = cd['privacy']
# this is the new record that is going to be created and saved
new_profile = Profile.objects.create(
user = currentUser,
first_name = first_name,
last_name = last_name,
dob_month = dob_month,
dob_day = dob_day,
dob_year = dob_year,
city = city,
state = state,
phone = phone,
privacy = privacy,
)
return redirect('home_page')
else:
# this is what is going to be saved into the html file and used to
# render the file
form = ProfileForm()
message = 'fill out form below'
parameters = {
'form':form,
'currentUser':currentUser,
'message':message,
}
return render(request, 'tabs/profile_setup.html', parameters)
Let's say your model name is User.
forms.py:
from .models import User
class UserForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
class Meta:
model = User
fields = '__all__'
and views.py:
def user_create(request):
form = UserForm(request.POST or None)
if request.method == 'POST':
form = UserForm(request.POST or None)
if not form.is_valid():
print form.errors
return render(request, 'user_create.html', {'form': form})
else:
first_name = form.cleaned_data.get("first_name")
last_name = form.cleaned_data.get("last_name")
# pass your extra fields here
new_user = User.objects.create_user(
user=user,
first_name=first_name,
last_name=last_name,
)
new_user.save()
return redirect('where you want to redirect',)
return TemplateResponse(request, 'user_create.html')
finally user will be save.
Read docs:https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/

what causes the weird "UNIQUE constraint failed: auth_user.username" error?

I try to insert data in user model into other model by one to one relationship. In specific, I want insert username,email and password attributes of User into other models.In Addtional, I intend to create both User model and other model in one form. So, I override the save method in modelform. It works partially and be able to insert data in both models and databases, except throw a UNIQUE constraint failed: auth_user.username error.
In models.py
class Staff(models.Model):
yes_or_no = ((True, 'Yes'),(False, 'No'))
male_or_female = ((True,'Male'),(False,'Female'))
user = models.OneToOneField(User, unique=True)
gender = models.BooleanField(default = True, choices = male_or_female)
birthday = models.DateField(default =None,blank = False, null = False)
created = models.DateTimeField(default=datetime.now, blank=True)
authorized = models.BooleanField(default=False,choices = yes_or_no)
store_id = models.ForeignKey(Store,default=1)
#property
def name(self):
return self.user.username
#property
def email(self):
return self.user.email
#property
def password(self):
return self.user.password
#property
def first_name(self):
return self.user.first_name
#property
def last_name(self):
return self.user.last_name
def __str__(self):
return self.user.username
In forms.py
class StaffForm(forms.ModelForm):
name = forms.CharField(max_length=100)
email= forms.EmailField(max_length=100, required=True)
password = forms.CharField(max_length=50)
store_id = forms.ModelChoiceField(queryset = Store.objects.all(),empty_label="--------") # select values ?
first_name = forms.CharField(required = True,max_length=100)
last_name = forms.CharField(required = True,max_length=100)
class Meta:
model = Staff
fields = ('gender','birthday','authorized','store_id')
widgets = {'authorized':forms.RadioSelect,
'gender':forms.RadioSelect,
'birthday':SelectDateWidget(years=range(date.today().year-50,date.today().year))
}
def save(self,*args,**kwargs):
Staff = super(StaffForm,self).save(commit=False)
user = User.objects.create(
username=self.cleaned_data['name'],
first_name=self.cleaned_data['first_name'],
last_name = self.cleaned_data['last_name'],
email= self.cleaned_data['email'])
user.set_password(self.cleaned_data['password'])
if self.cleaned_data['authorized']:
user.is_staff = True
Staff.user = user
Staff.save()
In views.py
#login_required(login_url='/dataInfo/login/')
def createstaff(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = StaffForm(request.POST or None)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
form.save()
return HttpResponseRedirect('/dataInfo/staff_view/')
# if a GET (or any other method) we'll create a blank form
else:
form = StaffForm()
return render(request, 'dataInfo/create_staff.html', {'form': form})

Form validation error message is not shown in ModelForm

I have a Model like this:
class Client(models.Model):
user = models.OneToOneField(User)
# True if the signed up user is client
is_client = models.BooleanField(default=True)
# Which company the client represents
company = models.CharField(max_length=200, null=True)
# Address of the company
address = models.CharField(max_length=200, null=True)
company_size = models.ForeignKey(CompanySize, null=True)
account_type = models.ForeignKey(AccountType)
billing_address = models.CharField(max_length=254, null=True)
ModelForm of the above model looks like this:
class ProfileForm(ModelForm):
class Meta:
model = Client
exclude = ['user', 'is_client']
def clean(self):
cleaned_data = super(ProfileForm, self).clean()
if not cleaned_data:
raise forms.ValidationError("Fields are required.")
return cleaned_data
In my views, I am doing like this:
def post(self, request, user_id):
# Get the profile information from form, validate the data and update the profile
form = ProfileForm(request.POST)
if form.is_valid():
account_type = form.cleaned_data['account_type']
company = form.cleaned_data['company']
company_size = form.cleaned_data['company_size']
address = form.cleaned_data['address']
billing_address = form.cleaned_data['billing_address']
# Update the client information
client = Client.objects.filter(user_id=user_id).update(account_type=account_type, company=company,
company_size=company_size, address=address, billing_address=billing_address)
# Use the message framework to pass the message profile successfully updated
#messages.success(request, 'Profile details updated.')
return HttpResponseRedirect('/')
else:
profile_form = ProfileForm()
return render(request, 'website/profile.html', {'form': profile_form})
If all the forms data are filled, it successfully redirects to / but if data are not filled it redirects to website/profile.html with the form. But error messages All fields are required are not shown. What's wrong?
Your error is that you are creating a new form when you want to send the error to template, you need send your object "form" and not "profile_form" for include the error information.
Regards.