Django and sqlite email authentication - django

I wanted to create an email authenticated django user model, and I basically followed the steps in this website:
http://www.micahcarrick.com/django-email-authentication.html
And also included the table alteration code in a post_syncdb function in a managmenet module, to make the email a unique identifier. This should work ok with MySql. BUT, it wont work for sqlite. This is because sqlite's table alteration is limited and wont allow you to change that attribute OR even add a column with a unique identifier.
If there is no elegant way of doing this, then I might have to switch to MySql.

http://www.sqlite.org/faq.html#q26
So, it UNIQUE is fully supported, but you cannot alter a table using UNIQUE. So dump the table to a new table that has the UNIQUE constraint then alter and rename the tables. Or just dump it, modify the dump and reimport it.

I think, in your post_syncdb hook, you can add:
cursor.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS auth_user_email_unique "
"ON auth_user (email COLLATE NOCASE);"
)
you may have to break out different blocks based on settings.DATABASES['default']['ENGINE']

Related

django ignores on_delete=Cascade when creating Postgresql-DBs

I use django 1.7 to create a postgresql 9.3 db with several tables that contain foreign-key constraints. The DB is used for a warehouse in which objects have a physical location. If an object (in table Stored_objects) is deleted, I'd also would like to delete it's position, so that my model for the location looks like:
class object_positions(models.Model):
obj_id = models.ForeignKey(Stored_objects, db_column='obj_id',on_delete=models.CASCADE)
(...)
The constraint in the db (after syncdb) however looks like this:
ALTER TABLE object_positions
ADD CONSTRAINT stored_obj_fkey FOREIGN KEY (obj_id)
REFERENCES "Stored_objects" (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION;
Is there something else I have to do to get this constraint right in the db?
Django uses it's own code to handle cascades, they're not implemented on a database level. The main reason is to maintain consistent behaviour across backends, and to allow model signals to fire for cascaded deletions. If for some reason you want the constraint on a database level, you'll have to edit the table yourself. I wouldn't recommend that unless you have a compelling reason (such as another app accessing the database, bypassing Django).

postgres - load from sql file (skip errors), leave existing ones and create non existing

I have an sql file(we can generate this in whatever way we want).
I want to load it fully initially, then want to update(delete, create) db based using logic.
Later, if I want to delete more, we can simply delete.
But, if we want to add more, then we need to import sql again. Before importing, I cant drop those tables because they are already foreign keys to others. So, I can only do this:
Run sql file somehow to add only non-available entries to database skipping available entries so I can skip errors ( duplicate key value violates unique ).
Import your data to a temporary table and then just use something like:
insert into real_table_name
select * from temporary_table_name
where id not in (select id from real_table_name);

Real difference between 'reference' and 'db.table_name'

I am having a probelm with web2py foreign keys, as this is lack of documentation on this its pretty fustrating. I define tables in different files most tables are related. I used to use db.table_name to denote foreign keys, but I was told to use 'reference tbl_name'. This however makes no difference whatsoever, I still get errors compalaining about models defined in later files as per alphabetical order rules for web2py. It seems it actually matters having tables in order, rendering the use of reference key word useless at best. Or am I missing somethng here.
I would assume you are using mysql. In such case, it is a mysql error. mysql raises error no 150 (foreign key error). So, it is a database backend issue rather than a web2py problem. Please do check the documentation for your database server. How I solved the issue is in the db.py file declare (db.define_table) all the primary tables that require no foreign keys first and then continue declaring the tables that require the foreign keys (Just ensure that the foreign table exists before referencing it). In case you are using individual files for different tables in the models folder, then try finding out which tables are primary and make sure that they are created first by prepending the filenames with numbers so that before referencing a foreign key in a table, the 'foreign' table will already be existing in the database.
However, there should be no issues with sqlite.

How to create a foreign key for a non-key table field?

Simply put, i want to create a structure that has a component MAKTX, and to have a foreign key relation with MAKT-MAKTX.
More generally i want to have a foreign key check for a field that's not part of a primary key.
I see the button "Non-key-fields/candidates", but i don't really know how to use it.
Also, i don't want to use the "key fields of a text table" relation... but i don't know if that's relevant.
Is this even a good thing that i'm trying to do? I don't see any reason why it shouldn't be possible, but you might object.
[EDIT]: I have to mention that I don't really know what I'm doing. I really just want to fill a table i created with values from another, and to make sure that those values (namely MAKTX - kind ofvalues) in my table are always values from MAKT. Suppose i do the initial filling with a SELECT statement, i want the consistency to work even if i later insert new entries manually.
So I don't know whether this makes sense or not, it just sounds to me like a good idea to have the system perform this check automatically, if possible.
Main condition for creating foreign key relation is that the field should be a primary key in your reference table. While in the table you are creating foreign key its not necessary that the field is a primary key or not. The main reason for this is that foreign key cant be null.
Refer to below link for step by step process for creating foreign key relation in abap.
http://learnabaponline.blogspot.in/2013/04/how-to-create-table-in-abap.html
First off, I agree with vwegerts's comments, what you're trying to do doesn't seem to make any sense.
Perhaps this would make more sense: create your own table without the MAKTX field. Then create a database view, joining your table and the MAKT table (and set a default language in the selection conditions if you want to). This way you'll have the descriptions joined with your data, without duplicating the actual data (which is what it looks like you're trying to do).

Primary key and unique key in django

I had a custom primary key that need to be set up on a particular data in a model.
This was not enough, as an attempt to insert a duplicate number succeeded. So now when i replace primary_key=True to unique=True it works properly and rejects duplicate numbers!!. But according this document (which uses fields).
primary_key=True implies null=False
and unique=True.
Which makes me confused as in why does
it accept the value in the first place
with having an inbuilt unique=True ?
Thank you.
Updated statement:
personName = models.CharField(primary_key=True,max_length=20)
Use an AutoField with primary_key instead.
Edit:
If you don't use an AutoField, you'll have to manually calculate/set the value for the primary key field. This is rather cumbersome. Is there a reason you need ReportNumber to the primary key? You could still have a unique report number on which you can query for reports, as well as an auto-incrementing integer primary key.
Edit 2:
When you say duplicate primary key values are allowed, you indicate that what's happening is that an existing record with the same primary key is updated -- there aren't actually two objects with the same primary key in the database (which can't happen). The issue is in the way Django's ORM layer chooses to do an UPDATE (modify an existing DB record) vs. an INSERT INTO (create a new DB record). Check out this line from django.db.models.base.Model.save_base():
if (force_update or (not force_insert and
manager.using(using).filter(pk=pk_val).exists())):
# It does already exist, so do an UPDATE.
Particularly, this snippet of code:
manager.using(using).filter(pk=pk_val).exists()
This says: "If a record with the same primary key as this Model exists in the database, then do an update." So if you re-use a primary key, Django assumes you are doing an update, and thus doesn't raise an exception or error.
I think the best idea is to let Django generate a primary key for you, and then have a separate field (CharField or whatever) that has the unique constraint.