I copied the full example code from: [customizing admin user][1] (part of the django documentation), but when I run it the django will not came out error,but when i add a user ,the django will the came out following error .
I have not changed any code for the example,and setting follow up the document.
follow up link is example:
https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#a-full-example
Error:
IntegrityError at /admin/app01/myuser/add/
NOT NULL constraint failed: app01_myuser.last_login
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/app01/myuser/add/
Django Version: 1.8.5
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: app01_myuser.last_login
Exception Location: /Library/Python/2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 318
There is clearly a discrepancy between the custom user model you are using from the Django sample code and the definition of the table it represents in database. The error is from the database saying the last_login column of the app01_myuser table has a NOT NULL constraint on it and you are trying to create a user with that field NULL.
Your MyUser model contains the last_login field inherited from AbstractBaseUser. Here is the definition of last_login from the AbstractBaseUser class:
last_login = models.DateTimeField(_('last login'), blank=True, null=True)
Based on that definition of last_login, the NOT NULL constraint should not exist in your database.
Make sure your database is up to date by running migrations. Watch for any errors that occur when running the migrations.
You can also check the app01 migrations code to try to see when and why app01_myuser was created with the NOT NULL constraint in the first place.
Related
I am developing a custom usermodel for my application in django, by using AbstractUser.
But I am getting a UNIQUE constraint failed error while using add user + from django admin.
I have also tried to add unique = False in the EmailField
class User(AbstractUser):
id = models.BigAutoField(primary_key=True)
rollno = models.CharField(null=True,unique=True,max_length=15)
email = models.EmailField(blank=True,null=True,unique=False)
Error :
....
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: Accounts_user.email
[28/Jun/2022 05:54:58] "POST /admin/Accounts/user/add/ HTTP/1.1" 500 233697
The add form does not have a email field, submits a blank email.
(PS : I can add user by signup form of my application, change user of django admin is also working.)\
in the above code, there should not be any problem with migrations. i think your old migrations are creating problem here. check your old migrations and delete them.
I have a Payment Django model that has a CheckNumber attribute that I seem to be facing issues with, at least whilst mentioning the attribute in the str method. It works just fine on the admin page when creating a Payment instance, but as soon as I called it in the method it gave me the following error message:
Request URL: http://127.0.0.1:8000/admin/Vendor/payment/
Django Version: 3.0.7
Exception Type: AttributeError
Exception Value:
'Payment' object has no attribute 'CheckNumber'
Exception Location: /Users/beepboop/PycharmProjects/novatory/Vendor/models.py in __str__, line 72
Python Executable: /Users/beepboop/Environments/novatory/bin/python3.7
Python Version: 3.7.2
this is my code:
class Payment(models.Model):
Vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
Amount = models.DecimalField(decimal_places=2, blank=True, max_digits=8)
PaymentDate = models.DateField(name="Payment date", help_text="Day of payment")
CheckNumber = models.IntegerField(name="Check number", help_text="If payment wasn't made with check, leave blank", blank=True)
def __str__(self):
return f"Vendor: {self.Vendor.Name} | Amount: {prettyPrintCurrency(self.Amount)} | Checknumber: {self.CheckNumber}"
I would absolutely love any comments/suggestions about the cause of the error
In my opinion, you have introduced CheckNumber field in the Payment models recently with no migration. make sure you run the migration then you can do that using the following command.
python manage.py migrate
This will create a new field in the Payment table. Hopefully, this will resolve your issue.
please clean the database and then run the migration command.
To clean the database you need to write the following command(Don't run this command in production):
python manage.py flush
After the cleaning, you can make an initial migration using the following command:
python manage.py makemigrations
and then migrate those changes to the database table:
python manage.py migrate
So it turns out that when you pass a name value in a model field, it changes the name of the field with it, I personally thought that it would change the name when displayed in the Django admin. My fix was to just remove the name value and migrate, that fixed it for me.
I started using Django REST this week, and I am running into something I do not understand.
I building a POST that takes in the following payload:
{
"requestor":"naughtron",
"test_name":"testName",
"workers":"2"
}
The value for requestor in our data model is set to CurrentUserField()
When the payload comes into the serializer
class TestSuiteRequestSerializer(serializers.Serializer):
requestor = what_do_use_here?
test_name = serializers.CharField(required=True, allow_blank=False, max_length=100)
workers = serializers.CharField(required=True, allow_blank=True, max_length=3)
the following error is thrown
database_1 | ERROR: null value in column "requestor" violates not-null constraint
because I am believe it is not being serialized properly therefore the model has no idea what to do.
I looked through the documentation and the current list of Serializer fields. Nothing seems to be helping.
I tried using a basic serializers.CharField but that threw an error stating must be a "User" instance.
I'm working on a Django app that will contain sensitive User data, so I'm taking a number of steps to anonymise User objects and their data.
I created custom 'User' object that subclassses the AbstractBaseUser model like so:
class User(AbstractBaseUser, PermissionsMixin):
(...)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
(...)
It has the following linked ModelAdmin object:
from django.contrib.auth.forms import UserChangeForm
#admin.register(User)
class UserAdmin(admin.ModelAdmin):
form = UserChangeForm
I'm using UUID fields for primary keys to ensure maximum anonymity, yet I would like to be able to reset User passwords in the Django Admin (like you can do with the default User object)
However, when I open a User in the admin and press the link to change the password I get the following error message:
User with ID "21362aca-6918-47ea-9b29-275350a89c54/password" doesn't exist. Perhaps it was deleted?
The admin url is still expecting a url with the an integer as its pk value.
So it seems that I have to override the admin url configuration in the ModelAdmin definition, but I was wondering if there was a simpler way to achieve the desired result - as I imagine that replacing the User.pk with an UUID field is a fairly regular occurrence and I image many developers have ran into this problem. I tried to find some kind of settings / toggle to achieve this but to no avail, am I missing something?
Your 'UserAdmin' inherits from ModelAdmin, which provides the urls via the get_urls method for the add, change, delete, etc. views but also a 'fallback' url:
urlpatterns = [
#...
url(r'^(.+)/change/$', wrap(self.change_view), name='%s_%s_change' % info),
# For backwards compatibility (was the change url before 1.9)
path('<path:object_id>/', wrap(RedirectView.as_view(
pattern_name='%s:%s_%s_change' % ((self.admin_site.name,) + info)
))),
]
The url you are following looks like /user/<UUID>/password/ which only fits the regex of the fallback pattern - which redirects you to the change page in such a way that it uses <UUID>/password as the object_id.
Try inheriting from django.contrib.auth.admin.UserAdmin instead as its get_urls method provides the url pattern you need.
Some more poking around...
If your primary key field was an AutoField, the whole process would raise a ValueError('invalid literal for int') when trying to cast int('some_integer/password') in django.db.models.fields.AutoField.get_prep_value in order to prepare the value for a query. Understandable!
HOWEVER: UUIDField uses the get_prep_value method of the base class Field. Field.get_prep_value just simply returns the value without even checking (after all, validating the value should be the job of UUIDField). So you end up with a query that looks for the bogus uuid '<uuid>/password', which obviously doesn't exist.
I am using PasswordResetView (the class-based view in Django 2.0) to implement Forgot Password functionality into my app. I am new to class based views and by default it looks for is_active in my user model. However, I overrode the default user model and my model instead contains the field with the name active. How do I change this behavior?
FieldError at /account/reset-Password/
Cannot resolve keyword 'is_active' into field. Choices are: active, admin, confirm, email, full_name, id, last_login, logentry, password, social_auth, staff, timestamp, userlogin, username
Request Method: POST
Request URL: http://127.0.0.1:8000/account/reset-Password/
Django Version: 2.0.5
Exception Type: FieldError
Exception Value:
Cannot resolve keyword 'is_active' into field. Choices are: active, admin, confirm, email, full_name, id, last_login, logentry, password, social_auth, staff, timestamp, userlogin, username
Exception Location: /home/yash/Desktop/ltigo/lib/python3.6/site-packages/django/db/models/sql/query.py in names_to_path, line 1379
Python Executable: /home/yash/Desktop/ltigo/bin/python
Python Version: 3.6.5
Python Path:
['/home/yash/Desktop/ltigo/src',
'/home/yash/Desktop/ltigo',
'/home/yash/Desktop/ltigo/lib/python36.zip',
'/home/yash/Desktop/ltigo/lib/python3.6',
'/home/yash/Desktop/ltigo/lib/python3.6/lib-dynload',
'/usr/lib/python3.6',
'/home/yash/Desktop/ltigo/lib/python3.6/site-packages',
'/snap/pycharm-professional/68/helpers/pycharm_matplotlib_backend']
Server time: Mon, 16 Jul 2018 15:18:07 +0000
To fix that particular error, it looks as if you have to subclass PasswordResetForm so that it doesn't use is_active. Then use your form in your password reset view.
However, I would recommend against renaming the field to active - it is likely to cause problems in other places as well.