django appuser give duplicate key error while creating new superuser - django

im getting this error while creating new superuser
Heres the error:
django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_auth_appuser_phone_key"
DETAIL: Key (phone)=() already exists.
I know it is checking for unique phone number while also considering empty phone value and hence giving this error.
my question is how to resolve this
Models.py:
class AppUser(AbstractUser):
user_type = models.PositiveSmallIntegerField(default=1)
class Gender(models.IntegerChoices):
Male = 1, 'MALE'
Female = 2, 'FEMALE'
Other = 3, 'OTHER'
email = models.EmailField(null=True, blank=True)
phone = models.CharField(max_length=15, unique=True)
gender = models.PositiveSmallIntegerField(choices=Gender.choices, null=True, blank=True)
dob = models.DateField(null=True, blank=True)
doa = models.DateField(null=True, blank=True)
#property
def info(self):
from user_auth.serializers import UserSerializer
return UserSerializer(self).data
#property
def token(self):
return RefreshToken.for_user(self)

since I don't have enough reputation to comment, I post my thoughts as an answer.
As seen here Django unique nullable CharField
if you want the phone field to be unique and be empty, you could use phone = models.CharField(max_length=15, unique=True, null=True) so that when it's not provided it results to null instead of '' (empty string).
Since null != null, this might fix it.

Related

Django addField ForeignKey during migrations create unusable constraint name

Env: Django 1.8.11 + Postgis
I'm adding some ForeignKeys on a MyModel.
The models pointed are in another schema ("cartography").
makemigrations
no errors
migrate
One error. Can't create the constraint because the generated name.
But I'm adding 10 fields, really similar between them. Only one is giving that stupid error.
I can't specify the constraint name anywhere.
class myModel(models.Model)
zps_calculated = models.ForeignKey( Cartography_zps, verbose_name="zps_calcolato", null=True, blank=True, on_delete=models.SET_NULL)
zsc_sic_sir_calculated = models.ForeignKey( Cartography_zsc_sic_sir, verbose_name="zsc_sic_sir_calcolato", null=True, blank=True, on_delete=models.SET_NULL)
manyothersdata = "xxx"
That is the slice of code generated from sqlmigrate (to inspect the code the migration generate).
As you see the name of the constraint is the error.
1 on 10 fields is giving the error
CREATE INDEX "segnalazioni_f38ba181" ON "segnalazioni" ("zps_calculated_id");
ALTER TABLE "segnalazioni" ADD CONSTRAINT "se_zps_calculated_id_6844dce0603174b2_fk_"cartography"."zps"_id" FOREIGN KEY ("zps_calculated_id") REFERENCES "cartography"."zps" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "segnalazioni_eb52e53f" ON "segnalazioni" ("zsc_sic_sir_calculated_id");
ALTER TABLE "segnalazioni" ADD CONSTRAINT "cc6ce48808e3a5292779a9787d21e5ad" FOREIGN KEY ("zsc_sic_sir_calculated_id") REFERENCES "cartography"."zsc_sic_sir" ("id") DEFERRABLE INITIALLY DEFERRED;
That is the name giving the error: "se_zps_calculated_id_6844dce0603174b2_fk_"cartography"."zps"_id"
I think should be something like:
"6844dce0603174b2..."
the model NOT giving the error:
class Cartography_zsc_sic_sir(models.Model):
id = models.AutoField(primary_key=True)
slug = models.CharField(max_length=40, blank=True, null=True)
nome = models.CharField(max_length=60, blank=True, null=True)
the_geom = models.MultiPolygonField(srid=23032, blank=True, null=True )
objects = models.GeoManager()
class Meta:
managed = False
db_table = '"cartography"."zsc_sic_sir"'
verbose_name = 'Cartography - zsc_sic_sir'
verbose_name_plural = 'Cartography - zsc_sic_sir'
ordering = ["id","slug"]
def __unicode__(self):
return self.nome
that is the model giving the error:
class Cartography_zps(models.Model):
id = models.AutoField(primary_key=True)
slug = models.CharField(max_length=40, blank=True, null=True)
the_geom = models.MultiPolygonField(srid=23032, blank=True, null=True )
objects = models.GeoManager()
class Meta:
managed = False
db_table = '"cartography"."zps"'
verbose_name = 'Cartography - ZPS'
verbose_name_plural = 'Cartography - ZPS'
ordering = ["id","slug"]
def __unicode__(self):
return self.slug
Going further I'm investigating in Django code, backwards.
The
' %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)%s;' %
is in
/django/db/backends/base/creation.py row 180
using that
qn = self.connection.ops.quote_name
that SHOULD be the %s constraint name value:
qn(truncate_name(r_name, self.connection.ops.max_name_length()))
Anyone have an hint to help me?
I'm gonna look what qn does.
https://github.com/django/django/releases/tag/1.8.11
The problem was the attribute name (but I still dunno why):
zps_calculated = models.ForeignKey( Carto...
I renamed it to
zpsasd_calculated = models.ForeignKey( Carto
and the generated constraint name changed to (sqlmigrate):
a326518e5e22b0c2c1251e5bbb331adb
Wow!
Renamed the attribute zpsasd_calculated to zps_calculated, with another migration.
Worked.
Next time I will migrate with custom SQL
https://www.ralphlepore.net/custom-foreign-key-constraints-with-django/

Django get_or_create trying to create row, throwing IntegrityError?

I'm working in Django 1.7 and Postgres, and using the ORM to create some new rows. I am using get_or_create as follows:
p, created = Practice.objects.get_or_create(
code=row[1],
name=row[2],
address1=row[3],
address2=row[4],
address3=row[5],
address4=row[6],
postcode=row[7]
)
But when I try to run this I get:
django.db.utils.IntegrityError: duplicate key value violates unique constraint
DETAIL: Key (code)=(A82057) already exists
What's this about? I thought the point of get_or_create was to only try to create new rows if they didn't already exist.
My model looks like this:
class Practice(TimeStampedModel):
code = models.CharField(max_length=6, primary_key=True, db_index=True)
name = models.CharField(max_length=200)
address1 = models.CharField(max_length=200, null=True, blank=True)
address2 = models.CharField(max_length=200, null=True, blank=True)
address3 = models.CharField(max_length=200, null=True, blank=True)
address4 = models.CharField(max_length=200, null=True, blank=True)
postcode = models.CharField(max_length=9, null=True, blank=True)
def __str__(self):
return self.name
class Meta:
app_label = 'frontend'
ordering = ['name']
Is it something to do with the fact that I've set a manual primary key? I can't see anything in the Django docs about this restriction.
get_or_create attempts to do a get with all of the parameters you pass, not just the PK. So if there is an object with a matching PK but a different postcode, for example, the get will fail so a create will be attempted - but, since you have a manual PK, it will try to create a duplicate one using the data you have passed.
Generally speaking using a non-autoincrementing PK is a bad idea. But if you are just trying to look up against the PK only, use the defaults argument:
p, created = Practice.objects.get_or_create(
code=row[1],
defaults={
'name': row[2],
'address1': row[3],
'address2': row[4],
'address3': row[5],
'address4': row[6],
'postcode': row[7]
})

Django query to filter username in correct format

There is model OraganisationUser :
class OrganisationUser(CommonInfo):
active = models.BooleanField(default=True)
user = models.OneToOneField(User, related_name='organisation_user')
managers = models.ManyToManyField('self', related_name='employees_managed', null=True, default=None, blank=True, symmetrical=False)
approvers = models.ManyToManyField('self', related_name='approvees', null=True, default=None, blank=True, symmetrical=False)
organisation = models.ForeignKey(Organisation, related_name='employees')
user_details = models.OneToOneField('OrganisationUserDetails', null=True, blank=True)
super_admin = models.ForeignKey('self', related_name='organisation_employees', null=True, blank=True)
objects = OrganisationUserManager()
gems = models.PositiveIntegerField(default=0, null=True, blank=True)
rank = models.PositiveIntegerField(default=0, null=True, blank=True)
I have written a query to filter user name in views.py :
username = OrganisationUser.objects.filter(user = id)
print username
Its printing : [<OrganisationUser: nirmal>]
I want to fetch nirmal from above result.
filter returns a list of objects. Use get to get a single object and navigate to the username:
username = OrganisationUser.objects.get(user=id).user.username
Better yet, look up the user directly
username = User.objects.get(pk=id).username
Is there a possibility of not finding the user with that id?
Where are you getting the id? Is this the logged in user? Then he is available in request.user, and his username in request.user.username.
The problem in your code is that 'username' has the organisationuser object. With that object (in your code username), you can access any atribute like active,user,managers,organisation,userdetails.... just adding a dot between object and atribute.
You can do it like this:
orguser = OrganisationUser.objects.filter(user = id)
print orguser #This print the object OrganisationUser
print orguser.user #This print the object User, wich the onetoonefield is pointing to
print orguser.user.username #This print the username, of the user pointed by the one to one field
Example managing django object. Get attribute value:
object = OrganisationUser.objects.filter(user = 1) #Get the object with id=1
print object.active #This will print the value for this attribute (active)

Haystack searching multiple fields

I am currently building a page in django, where there are 4 form fields, 2 text, 2 select fields, and when submitted it takes those fields and searches several models for matchinng items.
the model looks like this:
class Person(models.Model):
user = models.ForeignKey(User, blank=True, null=True, verbose_name="the user associated with this profile")
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
about = models.TextField(max_length=255, blank=True, null=True)
birthdate = models.DateField(blank=True, null=True, verbose_name="Birthdate (yyyy-mm-dd)")
GENDER_CHOICES = (
(u'M', u'Male'),
(u'F', u'Female'),
)
gender = models.CharField(max_length=1, choices = GENDER_CHOICES, default = 'M')
picture = models.ImageField(upload_to='profile', blank=True, null=True)
nationality = CountryField(blank=True, null=True)
location = models.CharField(max_length=255, blank=True, null=True)
command_cert = models.BooleanField(verbose_name="COMMAND certification")
experience = models.ManyToManyField('userProfile.MartialArt', blank=True, null=True)
and I am trying to search the first_name field, the last_name field, the nationality field, and the experience field, but say if the first_name field is blank, I need to pass an empty value so it returns all rows, then filter from there with last name the same way, for some reason it is not working at all for me. this is my sqs:
results = SearchQuerySet().models(Person).filter(first_name=sname, last_name=slastname, nationality=scountry, experience__pk=sexperience)
any ideas?
Without seeing specific errors or a stack trace, it's hard to determine what "is not working at all".
Edit: Looking at your provided view code, I would remove the filter and return all of the objects for your Fighter, Referee, Insider, and Judge models. This is to ensure that the issue here lies in the filter, and not something else.
Then, once I'd verified that objects are being placed into results, I'd put in the filters one at a time to determine what the problematic filter is. Give this a try and reply back with your results.

Django ForeignKey TemplateSyntaxError and ProgrammingError

This is are my models i want to relate. i want for collection to appear in the form of occurrence.
class Collection(models.Model):
id = models.AutoField(primary_key=True, null=True)
code = models.CharField(max_length=100, null=True, blank=True)
address = models.CharField(max_length=100, null=True, blank=True)
collection_name = models.CharField(max_length=100)
def __unicode__(self):
return self.collection_name
class Meta:
db_table = u'collection'
ordering = ('collection_name',)
class Occurrence(models.Model):
id = models.AutoField(primary_key=True, null=True)
reference = models.IntegerField(null=True, blank=True, editable=False)
collection = models.ForeignKey(Collection, null=True, blank=True, unique=True),
modified = models.DateTimeField(null=True, blank=True, auto_now=True)
class Meta:
db_table = u'occurrence'
Every time i go to check the Occurrence object i get this error
TemplateSyntaxError at /admin/hotiapp/occurrence/
Caught an exception while rendering: column occurrence.collection_id does not exist
LINE 1: ...LECT "occurrence"."id", "occurrence"."reference", "occurrenc..
And every time i try to add a new occurrence object i get this error
ProgrammingError at /admin/hotiapp/occurrence/add/
column occurrence.collection_id does not exist
LINE 1: SELECT (1) AS "a" FROM "occurrence" WHERE "occurrence"."coll...
What am i doing wrong? or how does ForeignKey works?
The problem is that you have not updated your database table definition since adding the ForeignKey. syncdb doesn't do this for you, as the documentation clearly states. You need to update the SQL manually, or use a tool like South.
Are you sure you mean
collection = models.ForeignKey(Collection, null=True, blank=True, unique=True),
Nullable and Unique? This may not be possible in some databases.
Generally, the unique constraint doesn't seem to make much sense here.
Are you trying to force a 1-to-1 relationship? Use the OneToOneField. http://docs.djangoproject.com/en/1.1/ref/models/fields/#django.db.models.OneToOneField