Django AbstractUser Inheritence Error - python

I'm still pretty new to Django, and have been having a problem defining my own user model that inherits from the Abstract User in Django. However, I have users already in the databse (with only usernames and passwords) and when I try to migrate the changes, I get the error that the email field is required and doesn't have a default value.
What confuses me is that I looked it up in the docs, and at https://docs.djangoproject.com/en/1.7/ref/contrib/auth/ the email field is clearly listed as optional. Furthermore, when I try to override the email field I get an error that my field clashes with the existing one.
Why is it giving me this error, and how do I fix it?
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class UserProfile(AbstractUser):
additionalFields = models.IntegerField(default=0)
def __unicode__(self):
return self.username

EmailField is a text field in the database, and 'empty' text fields are saved as an empty string (''). They are not empty (NULL) on a database level, and the column is defined as NOT NULL. What you need to do is set a default of '', then the migration will work.

Related

Django: Field 'object_id' expected a number but got 'fe2b1fd4313c'

I am getting this error while trying to save a model from the admin section using Django admin, this is the error Field 'object_id' expected a number but got 'id_b2cbfe2b1fd4313c'.. I am using django shortuuid package https://pypi.org/project/shortuuid/ to create id field in django, and i choose to use it because the inbuild UUID field keeps giving this error Django UUIDField shows 'badly formed hexadecimal UUID string' error? and the id looks like this id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True). What would be the problem witht the short uuid field.
Based on this, i quote:
If you filter on the ForeignKey, then Django will filter on the primary key of the target object, and that is normally an AutoField, unless you referred to another (unique) column, or defined another primary key as field.
But i dont know what the issue might be now
Models.py
class Channel(models.Model):
id = ShortUUIDField( length=16, max_length=40, prefix="id_", alphabet="abcdefg1234", primary_key=True,)
full_name = models.CharField(max_length=200)
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, related_name="channel")
Views.py
def channel_profile(request, channel_name):
channel = Channel.objects.get(id=channel_name, status="active")
context = {
"channel": channel,
}
return render(request, "channel/channel.html", context)
Your database is not sync with your migrations file, because your problem is easy to solve, Django is expecting an ID (integrer) and you are passing a string.
If you have not push your project into production you can delete the migration folder and migrate again, otherwise you need to update your migrations files to change the type for the UD field

Adding username when submitting form on django

I am trying to store the username of the user currently logged in when they submit information on a form on a django website.
This is what my models.py file looks like so far:
from django.db import models
from django.contrib.auth.models import User
class Transfer(models.Model):
id = models.AutoField(primary_key=True)
username = User._meta.get_field('username')
amount = models.DecimalField(max_digits=10, decimal_places=2)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
however this doesn't seem to work. The migrations etc work fine and the server runs, but when I submit information on the form I get the following error:
Exception Type: IntegrityError
Exception Value: UNIQUE constraint failed: transfer_transfer.username
Any advice on how I could get the username to save would be very helpful.
Thanks in advance
That declaration doesn't make any sense in a model definition. It might "work", in the sense that you get a field with the same properties as User.username, but it isn't doing anything useful; you could just as well define it directly as models.CharField.
Instead you need to define a ForeignKey from Transfer to User, and call it user; there is plenty of documentation on how to do this, and also plenty of questions here on how to fill in the user field automatically on form submission.

Django UUIDField modelfield causes error in Django admin: badly formed hexadecimal UUID string

I have a Django 1.8 project and on one of my models, I am using the new UUIDField like so:
class MyModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
I've also set up my admin.py:
#admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
pass
When I load the admin page to try to create an instance, I get an error:
ValueError at /admin/core/mymodel/add/
badly formed hexadecimal UUID string
I am able to create an instance no problem from the Django shell (./manage.py shell). Once I've done that though, I get the same error as before on the admin site even when viewing the list of object instances.
Any thoughts?
The problem is that I had an existing record in the DB with a default integer autoincrement id, before I had specific that the id field on my model was a UUIDField. The value of this field was just 1, which was not a valid UUID hex string.
Removing this record fixed my issue.

How to add new columns to django userprofile model

I have added one extra custom field phone to Django user authentication. Till then it worked properly. Later I added one more custom field called permissions. After that I am facing an error message when I try to access the admin page. Here is my model.py code
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
class Meta:
permissions = (
("ssc_1","can access ssc locked questions"),
)
# The additional attributes we wish to include.
phone = models.CharField(max_length =20)
permission = models.IntegerField()
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user.username
I have followed this stackoverflow answer, when I issue python manage.py migrate command, I am getting this error message
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: table "users_userprofile" already exists
Note : My Django versions is 1.6.6
Thanks
Migrations were introduced only in django 1.7. Until then south was being used to handle migrations

Error in Inherit BaseUser in Django 1.7b4

I'm trying to add a custom field to already existed django's User model.
I want all fields of default User model(including password hashing functionality) + a custom field has_car, so I did ...
class MyUser(AbstractBaseUser):
has_car = models.BooleanField(default=False)
and register in admin panel admin.site.register(MyUser)
when I try to add open this model in admin panel I get this error.
OperationalError at /admin/myapp/myuser/
(1054, "Unknown column 'myapp_myuser.id' in 'field list'")
I'm not sure if its a mysqldb error or what?
I know I can use OneToOne or ForeignKey field but I simply want to extend User model.
again, It django==1.7b4 + Mysql
If you're just looking to add custom fields to the standard User model, your user model should inherit from AbstractUser instead of from AbstractBaseUser.
Don't forget to set:
AUTH_USER_MODEL = 'myapp.MyUser'
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-django-s-default-user

Categories