`NOT NULL constraint failed:` when try to Create a User - django

I encounter error NOT NULL constraint failed: when intend to create a User account:
The model data code:
class ActivateCode(models.Model):
""" """
user = models.ForeignKey(User, on_delete=models.CASCADE)
code = models.CharField(max_length=100)
date_expired = models.DateTimeField(default=tomorrow)
def __str__(self):
return self.code
the register in views.py
def register(request):
if request.method == "GET":
form = UserForm()
if request.method == "POST":
form = UserForm(request.POST)
print(vars(form))
if form.is_valid():
user = User.objects.create_user(
form.cleaned_data['username'],
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
email=form.cleaned_data['email'],
password=form.cleaned_data['password'])
user.is_active = False
user.save()
#create activate code
uuid_code = str(uuid.uuid4()).replace("-", '')
activate_code = ActivateCode(code=uuid_code)
activate_code.save()
return HttpResponse(f"You have registered successfully with activate_code: {uuid_code}. \n"
"Please activate your account from your registered email.")
The error it throwed
IntegrityError at /user/register
NOT NULL constraint failed: user_activatecode.user_id
Request Method: POST
Request URL: http://127.0.0.1:8001/user/register
Django Version: 1.11.13
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: user_activatecode.user_id
How to solve such a problem?

Seems you are trying to insert null value in a field that don't accept it, in you ActivateCode Model its seems you have a foreign key related to the user, maybe you have to post it also. Try to pass the user to the ActivateCode call:
ActivateCode(code=code, user=user)

Related

I am trying to create user in auth_user in Django but I am getting this error TypeError at /register/ set_password() missing 1 required

Hello I am trying to create user in auth_user in database but it is showing me a error
The method I am using
from django.contrib.auth.models import User
user = Users.objects.get(username='myuser')
user.set_password('mypassword')
user.save()
My views.py
def registerpage(request):
if request.method == 'POST':
myusername = request.POST['name']
email = request.POST['email']
pass1 = request.POST['password1']
pass2 = request.POST['password2']
myuser = User.objects.get(username=myusername)
User.set_password('pass1')
myuser.name = myusername
myuser.email = email
myuser.password = pass1
myuser.save()
return redirect('testlogin')
The error that I am getting
TypeError at /register/
set_password() missing 1 required positional argument: 'raw_password'
I need help !
create user
myuser = User.objects.create_user('username', 'example#gmail.com', 'youPassword')
Update user data
user = User.objects.get(username=myusername)
user.set_password('newpassword')
user.save()
In line 8 you are trying to get a user before creating that user, that's not possible, and in line no. 9, for which user you want to set password?(User is the class). first you have to create a user, after that, write get query.
def registerpage(request):
if request.method == 'POST':
myusername = request.POST['name']
email = request.POST['email']
pass1 = request.POST['password1']
pass2 = request.POST['password2']
if not pass1 == pass2:
messages.warning(request,"please enter both password same")
return render(request,'registerpagetemplate.html')
else:
user = User.objects.create_user(username=myusername,password=pass1,email=email)
return redirect('testlogin')
After creating user, create a separate method for login, then execute query for access user:
myuser = User.objects.get(username=myusername)

Django file upload:Integrity Error

This is what I got
IntegrityError at /malex/upload/
NOT NULL constraint failed: malex_document.uploaded_by_id
Request Method: POST
Request URL: http://127.0.0.1:8000/malex/upload/
Django Version: 2.0.5
Exception Type: IntegrityError
Models
class Profile(models.Model):
username = models.OneToOneField(User, on_delete=models.CASCADE)
password = models.TextField(max_length=80,blank=True)
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
uploaded_by = models.ForeignKey(Profile,on_delete=models.CASCADE)
date_uploaded = models.DateTimeField(auto_now_add=True)
Forms
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file')
views
def upload(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
**newdoc.uploaded_by = request.user.profile**
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('upload'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render(request,'upload.html',{'documents': documents, 'form': form})
If I add the line as neverwalker alone has suggested
'AnonymousUser' object has no attribute 'profile'
What even makes things more strange with this integrity error is that the file is uploaded
~/nup/malex/media/documents/2018/06/22$ ls -lh 262_V01_C06_R000_TEy_BH_131072H.ats
-rw------- 1 milenko milenko 46M јун 22 07:22 262_V01_C06_R000_TEy_BH_131072H.ats
Why do I got this error and how to fix this?
You didn't set uploaded_by attribute. Since it's not nullable this is raise error. To fix this, you need to provide uploaded_by to new Document instance before saving like this:
#login_required
def upload(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.uploaded_by = request.user.profile # if Profile has onetofield with User model
# newdoc.uploaded_by = request.user if Profile is your user_model
newdoc.save()
Note uose login_required decorator to ensure current user is authenticated.
Also you can set uploaded_by as nullable field:
uploaded_by = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
In this case uploaded_by will not required, and will be set as ULL for new records.

Django -> Exception Value: (1048, "Column 'user_id' cannot be null")

I have the following view which works perfectly:
#transaction.atomic
def register(request):
next_url = request.POST.get('next', request.GET.get('next', reverse('profile')))
if request.method == 'POST':
form = RegistrationForm(request.POST)
profileform = ProfileForm(request.POST)
if form.is_valid() and profileform.is_valid():
new_user = form.save()
# Login the newly created user.
authenticated_user = authenticate(username=new_user.username,
password=form.cleaned_data['password1'])
login(request, authenticated_user)
return redirect(next_url)
else:
form = RegistrationForm()
profileform = ProfileForm()
return render(request, 'meta/register.html', {'form': form, 'profileform': profileform, 'next': next_url})
However, when I wish to save the additional profile information using the following line (placed below the line new_user = form.save() ):
new_user_profile = profileform.save()
I get the following error:
Exception Type: IntegrityError
Exception Value: (1048, "Column 'user_id' cannot be null")
My model for the profile is as follows:
class Profile(models.Model):
user = models.OneToOneField(User)
dob = models.DateField(max_length=8)
class Meta:
managed = True
db_table = 'fbf_profile'
Any help would be great, Alan.
When working with foreign keys like this you typically see a save with commit=False and then setting the foreign keys on the model manually. e.g.,
new_user = form.save()
profile = profileform.save(commit=False)
if profile.user_id is None:
profile.user_id = new_user.id
profile.save()
This save() method accepts an optional commit keyword argument, which accepts either True or False. If you call save() with commit=False, then it will return an object that hasn’t yet been saved to the database. In this case, it’s up to you to call save() on the resulting model instance. This is useful if you want to do custom processing on the object before saving it, or if you want to use one of the specialized model saving options. commit is True by default.
Apparently the user field is not set in the ProfileForm. The Profile model needs a user_id for the user OneToOneField.
The ProfileForm will need a user field that you'll have to set, or you'll have to manually set the user field in the save() function of ProfileForm (which you would then have to override).

Error about Django custom authentication and login?

I create a custom Authentication backends for my login system. Surely, the custom backends works when I try it in python shell. However, I got error when I run it in the server. The error says "The following fields do not exist in this model or are m2m fields: last_login". Do I need include the last_login field in customer model or Is there any other solution to solve the problem?
Here is my sample code:
In my models.py
class Customer(models.Model):
yes_or_no = ((True, 'Yes'),(False, 'No'))
male_or_female = ((True,'Male'),(False,'Female'))
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100,blank = False, null = False)
password = models.CharField(max_length=100)
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)
_is_active = models.BooleanField(default = False,db_column="is_active")
#property
def is_active(self):
return self._is_active
# how to call setter method, how to pass value ?
#is_active.setter
def is_active(self,value):
self._is_active = value
def __str__(self):
return self.name
In backends.py
from .models import Customer
from django.conf import settings
class CustomerAuthBackend(object):
def authenticate(self, name=None, password=None):
try:
user = Customer.objects.get(name=name)
if password == getattr(user,'password'):
# Authentication success by returning the user
user.is_active = True
return user
else:
# Authentication fails if None is returned
return None
except Customer.DoesNotExist:
return None
def get_user(self, user_id):
try:
return Customer.objects.get(pk=user_id)
except Customer.DoesNotExist:
return None
In views.py
#login_required(login_url='/dataInfo/login/')
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(name=username,password=password)
if user is not None:
if user.is_active:
login(request,user)
#redirect to user profile
print "suffcessful login!"
return HttpResponseRedirect('/dataInfo/userprofile')
else:
# return a disable account
return HttpResponse("User acount or password is incorrect")
else:
# Return an 'invalid login' error message.
print "Invalid login details: {0}, {1}".format(username, password)
# redirect to login page
return HttpResponseRedirect('/dataInfo/login')
else:
login_form = LoginForm()
return render_to_response('dataInfo/login.html', {'form': login_form}, context_instance=RequestContext(request))
In setting.py
AUTHENTICATION_BACKENDS = ('dataInfo.backends.CustomerAuthBackend', 'django.contrib.auth.backends.ModelBackend',)
This is happening because you are using django's login() function to log the user in.
Django's login function emits a signal named user_logged_in with the user instance you supplied as argument. See login() source.
And this signal is listened in django's contrib.auth.models. It tries to update a field named last_login assuming that the user instance you have supplied is a subclass of django's default AbstractUser model.
In order to fix this, you can do one of the following things:
Stop using the login() function shipped with django and create a custom one.
Disconnect the user_logged_in signal from update_last_login receiver. Read how.
Add a field named last_login to your model
Extend your model from django's base auth models. Read how
Thanks, I defined a custom login method as follows to get through this issue in my automated tests in which I by default keep the signals off.
Here's a working code example.
def login(client: Client, user: User) -> None:
"""
Disconnect the update_last_login signal and force_login as `user`
Ref: https://stackoverflow.com/questions/38156681/error-about-django-custom-authentication-and-login
Args:
client: Django Test client instance to be used to login
user: User object to be used to login
"""
user_logged_in.disconnect(receiver=update_last_login)
client.force_login(user=user)
user_logged_in.connect(receiver=update_last_login)
This in turn is used in tests as follows:
class TestSomething(TestCase):
"""
Scenarios to validate:
....
"""
#classmethod
#factory.django.mute_signals(signals.pre_save, signals.post_save)
def setUpTestData(cls):
"""
Helps keep tests execution time under control
"""
cls.client = Client()
cls.content_type = 'application/json'
def test_a_scenario(self):
"""
Scenario details...
"""
login(client=self.client, user=<User object>)
response = self.client.post(...)
...
Hope it helps.

object is not callable error when creating a form in django

I am using django and trying to create a registration form and below are my codes
forms.py
from django import forms
attrs_dict = { 'class': 'required' }
class RegistrationForm(forms.Form):
username = forms.RegexField(regex=r'^\w+$',
max_length=30,
widget=forms.TextInput(attrs=attrs_dict),
label=_(u'username'))
email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,maxlength=75)),
label=_(u'email address'))
password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_(u'password'))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_(u'password (again)'))
views.py
from authentication.forms import RegistrationForm
def register(request):
regsiter_form = RegistrationForm()
if request.method=='POST':
form = regsiter_form(request.POST)
if form.is_valid():
new_user = User.objects.create_user(username=request.POST['username'],
email=request.POST['email'],
password=request.POST['password1'])
new_user.is_active = False
new_user.save()
return HttpResponseRedirect(reverse('index'))
return render_to_response('registration/registration_form.html'{'form':regsiter_form})
so when we go to the url,a registration form is displaying and when we enter the details and clicked submit i am getting the following error
TypeError at /accounts_register/register/
'RegistrationForm' object is not callable
Request Method: POST
Request URL: http://localhost:8000/accounts_register/register/
Django Version: 1.5.1
Exception Type: TypeError
Exception Value:
'RegistrationForm' object is not callable
Traceback
▶ Local vars
/home/user/package/authentication/views.py in register
form = regsiter_form(request.POST)
So can anyone please let me know why the above form object is complaining as the object is not callable and where we need to make the changes in order to avoid this error.
It should be:
def register(request):
register_form = RegistrationForm()
if request.method=='POST':
form = RegistrationForm(request.POST)
if form.is_valid():
new_user = User.objects.create_user(username=request.POST['username'],
email=request.POST['email'],
password=request.POST['password1'])
new_user.is_active = False
new_user.save()
return HttpResponseRedirect(reverse('index'))
return render_to_response('registration/registration_form.html'{'form':register_form})
So, form = register_form(request.POST) should be form = RegistrationForm(request.POST) inside your POST check.
The point is you first created an object/instance of RegistrationForm using register_form = RegistrationForm(), and then you tried register_form(request.POST), so basically you are trying to again call an object/instance which is not allowed unless there is a __call__ method defined on your class.
Instead of
form = regsiter_form(request.POST)
do
regsiter_form = RegistrationForm(request.POST)
And use register_form object instead of form.
Also, use data from form.cleaned_data to create user object instead of from request.POST
As
new_user = User.objects.create_user(username=form.cleaned_data['username'] ...)