Django PostgreSQL ArrayField does not work - python

I have just switched to PostegreSQL. Now whenever I add the following code to my Custom User Model, the database is broken, no new values are added to the database, for example during registration
from django.contrib.postgres.fields import ArrayField
class NewUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('Email'), unique=True)
username = models.CharField(max_length=150, unique=True)
start_date = models.DateTimeField(default=timezone.now)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(default=timezone.now)
code = models.ImageField(blank=True, upload_to='code',)
#part that breaks the databse:
ip_addresses = ArrayField(
models.CharField(blank=True), default=list)
From the moment also no more migrations are recognized.
Or I get something like this
django.db.utils.ProgrammingError: column "ip_addresses" does not exist
LINE 1: ...ER COLUMN "ip_addresses" TYPE varchar(15)[] USING "ip_addres...
What error I get is 50 50 chance but atleast the first error is always here.
I also tried this which did not work either
ip_addresses = ArrayField(
models.CharField(max_length=15), default=list)

Related

"no such column: id" Django AbstractUser model

I am trying to migrate, and view the admin page. both makemigrations and migrate passed, yet when i go to the admin url it reads this: "django.db.utils.OperationalError: no such column: social_app_user.id"
And once i create an id field, it changes to "django.db.utils.OperationalError: no such column: social_app_user.password"
I was under the impression that the AbstractUser model included all the default user fields, not sure about the primary key, but regardless.
Please help, thanks!
Note: the 'id' field in this models.py file was added after i got the error.
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
class User(AbstractUser):
is_verified = models.BooleanField(default=True)
id= models.AutoField(primary_key=True, null=False)
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
f"{self.username} {self.email}"
return
class main_feed(models.Model):
content= models.CharField(unique=True, max_length=255, default='', null=False)
poster = models.ForeignKey('User', related_name='author', on_delete=models.CASCADE, to_field='username')
likes = models.IntegerField(default=0, null=False)
favorites = models.IntegerField(default=0, null=False)
date_posted = models.DateTimeField(auto_now=True)
def __str__(self):
f"{self.content} {self.likes} {self.poster} {self.date_posted}"
return
It turns out I had to restart my entire application and run startapp again.
This time i added the user model and set up the settings and admin file BEFORE the very first migration. then everything works dandy. But I have no idea why this is the case, shouldnt the migration update and override the default user model?
anyways the question is answered now.

data passing by one to one field in Django

I have two models Employee and myCustomeUser in my Django project.
My models.py:
class myCustomeUser(AbstractUser):
username = models.CharField(default="abcdef", max_length=150, unique="True")
password = models.CharField(default="12345", max_length=150)
is_Employee = models.BooleanField(default=False)
is_Inspector = models.BooleanField(default=False)
is_IndustryOwner = models.BooleanField(default=False)
is_Admin = models.BooleanField(default=False)
class Employee(models.Model):
user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='releted_user')
extraField = models.TextField(blank=True)
Now I am trying to entry an Employee's data with views.py like this:
Employee_obj = Employee.objects.create(releted_user.username=this_username, releted_user.password=this_password, releted_user.is_Employee=True)
Employee_obj.save()
But It shows error like this:
Employee_obj = Employee.objects.create(releted_user.username=this_username, releted_user.password=this_password, releted_user.is_Employee=True)
^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
How can I solve this problem? Mainly I need to save any employee's data by Employee.objects.create()
You can not work with .create(foo.bar=…) that is just illegal Python syntax. If you need to create an object that is referenced throug a OneToOneField, you first create that object, like:
u = myCustomeUser.objects.create(
username=this_username,
password=this_password,
is_Employee=True
)
Employee_obj = Employee.objects.create(user=u)
Please do not store raw passwords. Django normally hashes passwords. See the how does Django stores passwords section of the documentation.

Migrations being applied according to User in models.py instead of being applied according to migrations in the database

I have written a custom django migrations command as shown below
User = get_user_model()
def populate_asset_assignee(apps, schema_editor):
for user in User.objects.all():
user.save()
# Some more code
The user model looks as follows
class User(AbstractUser):
username = None
email = models.EmailField(max_length=50, unique=True)
cohort = models.IntegerField(blank=True, null=True)
slack_handle = models.CharField(max_length=50,
blank=True, null=True)
picture = models.CharField(max_length=255, blank=True, null=True)
phone_number = models.CharField(max_length=50, blank=True, null=True)
last_modified = models.DateTimeField(auto_now=True, editable=False)
password = models.CharField(max_length=128, blank=True, null=True)
location = models.ForeignKey('SomeCentre',
blank=False,
null=True,
on_delete=models.PROTECT)
# Some more fields
I added the location field recently and have the migrations for it which is applied after this custom migration has been applied. The problem I am having is that whenever I try to make the migrations on the test db or a new database, I get the error django.db.utils.ProgrammingError: column core_user.location_id does not exist which is being raised inside the populate_asset_assignee method when I try to do the user in User.objects.all()
Any ideas why location_id is beeing checked yet I haven't applied the migrations for the location field yet.

Django-registration-redux restrict registration to edu emails

Hello I'm trying to restrict my users to have edu emails. I'm using django 1.10 on python 2.7 and Django-registration-redux. I've seen answers like this one but it requires editing the package directly. This seems like a bad idea? I'm using django-custom-user to use the email as a username, and i have extended the user model like so:
models.py
class CustomEmailUser(AbstractEmailUser):
'''
These are inherited from AbstractEmailUser:
id = models.AutoField(primary_key=True) #this is always present, its a django default
email = models.CharField(unique=True, max_length=255)
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_superuser = models.BooleanField()
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
'''
first_name = models.CharField(max_length=50, default='')
last_name = models.CharField(max_length=50, default='')
All the forms are taken care of by these two packages (which is great!) but i'd like to restrict the email domains to .edu and I'm unsure of how to do this without editing the packages directly. Any suggestions? Thanks!

Django ForeignKey to AbstractBaseUser

I'm trying to set up an app that will handle reviews about registered users. So in my Review model, I want to have a ForeignKey to my User model.
I'm using a custom user profile that looks like this:
#In /profiles/models.py
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
company = models.CharField(default="", max_length=200)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['company']
I have included it with settings.py AUTH_USER_MODEL = "profiles.MyUser". It works fine with registration, creating users etc. So I know its working.
In my review model I write the following:
class Review(models.Model):
company = models.ForeignKey(settings.AUTH_USER_MODEL)
reviewer = models.ForeignKey(Reviewer)
rating = models.IntegerField(default=0)
review = models.TextField()
pub_date = models.DateTimeField('date published')
Instead of settings.AUTH_USER_MODEL I have also tried writing profiles.MyUser, 'profiles.MyUser' and MyUser.
I can successfully use the python manage.py makemigrations reviews command. But when I do python manage.py migrate I get errors no matter what version I use above.
The error I get is the following:
ValueError: Lookup failed for model referenced by field reviews.Review.company: profiles.MyUser
nejc92 comment was correct. I had migrated my database earlier before I set AUTH_USER_MODEL for the first time.
I removed my whole database and created new migrations for all apps and migrated everything again from scratch. It then worked.
Sounds like a bug(?) to me.

Categories

Resources