Manually Select Database With Django's `clear()` command - django

I have a ManyToMany relationship between "dashboards" and "modules" in some code that I am trying to upgrade from Django 1.2 to 1.6. I have a section in a view that was working in 1.2, but does not work in 1.6, where I am deleting a "module", but first trying to clear() its relationship to the "dashboards".
module = PortalAnalyticsTimeCountsModule.objects.using( DASHBOARD_DATABASE ).get( id = module_id )
module.dashboards.clear()
PortalAnalyticsTimeCountsModule.objects.using( DASHBOARD_DATABASE ).get( id = module_id ).delete( using = DASHBOARD_DATABASE )
where DASHBOARD_DATABASE is just a string that I set as a global value at the beginning of the file that is the name of the database the lines are supposed to use in these lines. Note that DASHBOARD_DATABASE is not the default database for this django project set in the settings.py file, which is why I am manually setting the database using using.
In django 1.2, this worked fine. In django 1.6, it is the clear() command that is giving me an error because it is using the default database instead of the database it is supposed to be using. I cannot find a way to manually force that middle clear() line to use the correct database.
Does anybody know how (without referencing use of ROUTERS)?

Well, apparently the solution is to just remove
module.dashboards.clear()
entirely. It doesn't seem to be necessary anymore to remove the connections.

Related

How to use objects.create to add a file field from dataframe.to_csv?

I have used this code to try to add a dataframe.to_csv to a django db FileField, but it only works when I dont specify its path, so anyone know how to overcome this, I must specify its path and name it.
Thats my code
df = pd.DataFrame(profile_names,
columns=['username', 'followers', 'tweets', 'hashtags', 'MostRecent'])
Scrape.objects.create(
user=request.user.profile,
name=keyword,
csvfile=df.to_csv(f'./static/assets_new/CSV/{request.user} - {keyword}.csv')
)
Im trying to add a csv file to django db filefield, but nothing gets added instead

unique_together does not replace primary key

In my Django app, I want to insert a record with a composite primary key. Apparently this should be possible by making use of "unique_together". I'm quite sure this code was working in the past, but for some reason it does not seem to be working now. This code used to run on a Linux VM, and now I'm hosting it in Google App Engine. However I don't see how this can be the cause for this error.
class TermsAndConditionsDocument(models.Model):
organization = models.ForeignKey(Organization, on_delete=models.CASCADE, verbose_name=_("Organization"))
language = models.CharField(_('Language'),choices=LANGUAGE_CHOICES, max_length=5, help_text=_("The language of the content."))
content = models.TextField()
class Meta:
unique_together = ('organization', 'language')
The error:
IntegrityError at /transactions/settings/terms_and_conditions
null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, nl-BE, <p>B</p>, 10).
According to what I've read, using "unique_together" should cause Django to not need or include an ID as primary key. I checked the database, and the ID field DOES exist. I do not understand where the database constraint and the ID field are still coming from?
Apparently, as pointed out in the comments, a primary key "id" field is always added, even if you don't need it. It's supposed to get out of your way, so you don't even notice its existence. In my case, it required me to give it a value when I created a new record, which is not how things are supposed to work.
A while back I migrated this database from one Postgres database to another Postgres database. I used an SQL dump and load method for this. Some sequences seem to have been lost during that migration.
Because there are no sequences, some fields now lacked autoincrement capabilities, explaining the IntegrityError on insertion.
In order to fix this, I did the following:
1) Export the current data:
manage.py dumpdata > data.json
2) Drop your database and create a new empty one.
3) Run database migrations:
manage.py migrate
4) Load the data again, excluding some default data already recreated by Django.
manage.py loaddata --exclude auth.permission --exclude contenttypes data.json
This procedure seems to have recreated the sequences while also keeping the data.
The unique_together only creates a DB constraint (https://docs.djangoproject.com/en/2.2/ref/models/options/#unique-together).
You could create a custom primary key with the option primary_key https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.Field.primary_key but you could only do that for one field.
But I suggest to just keep the auto increment id field, this works better with Django.
For the error are you saving a model? or doing a raw import?

Django: How to insert sql statements into sqlite3 database and configure with models

I'm using Django for a project. I have a .sql file containing insert statements. How can I get them into my sqlite3 database and have them work with my models?
The project "fortune" has a models.py file that looks like the following:
class fortune(models.Model):
id = models.IntegerField(primary_key=True)
category = models.CharField(max_length=50)
length = models.IntegerField()
aphorism = models.CharField(max_length=5000)
I have a .sql file with a list of Insert statements like the follwing:
INSERT INTO "fortune_fortune" VALUES(1,'fortunes',127,'Arbitrary Text');
When I run .schema on my db.sqlite3 file which is configured with my project I see:
CREATE TABLE fortune_fortune(id integer, category varchar(50), length integer, aphorism varchar(5000));
I've tried using .read in my sqlite shell with no luck. I've tried typing "sqlite3 file.sqlite3 < file.sql" in bash as well. There is something I'm missing here, but I can't seem to ID the problem.
Thanks for your help.
ok, wait.. normally you dont use sql statements to insert data into db, if you work with django.
to insert data into db, you work with django ORM which is way much fun than these ugly sql statements.
fortune = fortune(category='new cat', length=19, aphorism='i love life')
fortune.save()
then as a result, you will have one new row in fortune table in your db. just read django docs and you feel happy!
and one more thing, class names are always in capital.
to your issue:
Django provides a hook for passing the database arbitrary SQL that’s executed just after the CREATE TABLE statements when you run migrate. You can use this hook to populate default records, or you could also create SQL functions, views, triggers, etc.
The hook is simple: Django just looks for a file called sql/<modelname>.sql, in your app directory, where <modelname> is the model’s name in lowercase.
more in docs

Getting django-facebook to work

I an trying to get django-facebook to work as per instructions given in the readme on
https://github.com/tschellenbach/Django-facebook. I am new to django.
It looks simple but I am facing the following problems. I am not able to get it to work.
In the readme it says AUTH_USER_MODEL = 'member.FacebookUser'. I am guessing the right option is
AUTH_USER_MODEL = 'django_facebook.FacebookUser'
after importing the models - this took me some t even after making that change, syncdb throws an error stating that:
FacebookUser does not have a USERNAME_FIELD.
Not able to solve that I decided to use the default user model - auth.user. That works and I was able to load facebook/example. However after authentication from facebook, I get an error
You need to set AUTH_PROFILE_MODULE in your project settings
So I added AUTH_PROFILE_MODULE = 'django_facebook.FacebookProfile'
Now it returns a new error -
FacebookProfile matching query does not exist. Lookup parameters were {'user_id_exact': 2L}
What should I do now?
Do python manage.py syncdb or whatever it needs to be done to update your database schema with the new table (facebook_profile).
Also, you don't mention it but I have and app that uses django_facebook and I have my settings.py file like this:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django_facebook.context_processors.facebook',
...
)
AUTHENTICATION_BACKENDS = (
...
'django_facebook.auth_backends.FacebookBackend',
)
I hope it helps

Django queryset filter on boolean not working

I have a model:
class mymodel(models.Model):
order_closed = models.BooleanField(default=False)
I added this field to my development mysqllite db manually since its a new field for a model/table that already existed. I then tried:
mymodel.objects.filter(order_closed=False) #and with True
and its producing incorrect or unpredictable results. I saw some mention that is could be a sqllite thing but I'm not sure? The templates seem to understand whether its a true or false value but python code doesn't. To clarify with some examples:
{{mymodel.order_closed}} will print 0 after I set the default to 0 in sqllite. but using .filter(order_closed=value) will still return every record.
I think you make some mistake in wrirting SQL . If you have db which have some important informations use
south
http://south.aeracode.org/
When you will have it you can easly upgrate/edit your database .
If you dont wanna install new 'plugins' try that .
1. Delete this field from DB manualy .
2. write : python manage.py sql 'name of app'
It will return the CREATE TABLE SQL statements for the app.
Then you can upr your database manualy with some of CReate command.