How to add superuser in Django from fixture - django

How to add SUPERuser(not just user) through Django fixtures?
Let's say I wanna have login:admin, password:admin.

solution 1
On empty database:
python manage.py createsuperuser
python manage.py dumpdata auth.User --indent 4 > users.json
and in users.json You have needed fixtures.
solution 2
./manage.py shell
>>> from django.contrib.auth.hashers import make_password
>>> make_password('test')
'pbkdf2_sha256$10000$vkRy7QauoLLj$ry+3xm3YX+YrSXbri8s3EcXDIrx5ceM+xQjtpLdw2oE='
and create fixtures file:
[
{ "model": "auth.user",
"pk": 1,
"fields": {
"username": "admin",
"password": "pbkdf2_sha256$10000$vkRy7QauoLLj$ry+3xm3YX+YrSXbri8s3EcXDIrx5ceM+xQjtpLdw2oE="
"is_superuser": true,
"is_staff": true,
"is_active": true
}
}
]

If you are using pytest-django you can use the existing fixture admin_user.
From RTD:
An instance of a superuser, with username “admin” and password “password” (in case there is no “admin” user yet).

Related

django dumpdata command throws doesnot exist error

I am trying to add some default/fixed values to postgres database and came across fixtures.
My model is like this
app/models.py
class Category(models.Model):
category = models.CharField(max_length=255)
def __str__(self):
return self.category
app/fixtures/category.json
[
{
"model": "core.category",
"pk": 1,
"fields": {
"category": "foo"
}
]
However, I am getting the following error when I run manage.py dumpdata
[CommandError: Unable to serialize database: cursor "_django_curs_139823939079496_sync_1" does not exist
It looks like you have json file already (serialize, means that your django models data has been translated already to json format) you just need to to migrate your data into a new database(you say postgres), try to run these few lines of codes NOTE: I used python3 because I am using macbook pro:-
python3 manage.py migrate
OR
python3 manage.py migrate --run -syncdb
Then, enter your django shell and delete all contenttypes:
>>> from django.contrib.contenttypes.models import ContentType
>>> c = ContentType.objects.all()
>>> c.delete()
(55, {'auth.Permission': 44, 'contenttypes.ContentType': 11})
>>> exit()
python3 manage.py loaddata datadump.json
After being notified that all contenttypes has been deleted, You need to ensure that those data will be displayed in your templates. Simply by loading them from from your json file as shown above.*

Mezzanine 4.0.1 - python manage.py createdb always create sqlite

This is happening with Mezzanine 4.0.1 on Ubuntu, in venv. Python 3.4.3
After creating a Mezzanine project, I changed the database connection settings in settings.py as:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "mezzaninedb",
"USER": "mezzanine",
"PASSWORD": "mezzaninepwd",
"HOST": "localhost",
"PORT": "5432",
}
}
I have created (in Postgresql) a Mezzanine user with password mezzaninepwd and database mezzaninedb, and I "GRANT ALL PRIVILEGES ON DATABASE mezzaninedb TO mezzanine;"
Than, I run:
python manage.py createdb
It displays in terminal everything that it should display, asks me to create user, email, password...
After it finished, i "psql" into postgresql and connect to mezzaninedb, but no tables are created in that (PostgreSQL) database.
However, dev.db is created in "local dir" and when I run
python manage.py runserver
I can see mezzanine UI, but mezzanine is using Sqlite.
This happens even if I completely remove this from settings.py
#DATABASES = {
#"default": {
# "ENGINE": "django.db.backends.postgresql_psycopg2",
# "NAME": "mezzaninedb",
# "USER": "mezzanine",
# "PASSWORD": "mezzaninepwd",
# "HOST": "localhost",
# "PORT": "5432",
#}
#}
I even tried to completely "literally remove" this section from settings.py and run
python manage.py createdb
it created all tables, but in sqlite - dev.db.
So, It never creates postgresql tables, but always creates sqlite db and tables, even if DATABASES {...} is not present.
I suspected that this might be DJANGO problem, so I created django project and django app, and some models.
After using the same DATABASE {...} in settings.py, and run
python manage.py syncdb
Tables were created in POSTGRESQL !!!
Just to mention, I tried the same
python manage.py syncdb
in mezzanine, and it behaved the same as createdb - did not create anything in PostgreSQL.
Is this known mezzanine problem or I am doing something very very wrong ?

Django - populate table on startup with known values

I have a Dog Model that have a "dog_type" field. i want the dog_type to be chosen from a list of pre-defined dog types, i DO NOT want to use a textfield with choices but a ForeignKey to a "DogType" Model. How could I populate the DogType Model with types on server startup? is this a good practice or a hack?
thanks.
code:
class Dog(Model):
name = CharField(...)
dog_type = ForeignKey(DogType)
class DogType(Model):
type_name = CharField(...)
type_max_hight = IntegerField(...)
etc....
You'll probably want to write a data migration that will add your choices in database.
Advantages of using this approach is that the data will be loaded in all your databases (production, dev, etc.)
(If you're not using migrations yet, you should consider it, it's a clean and well-supported way to manage your database)
In your django project, just run python manage.py shell makemigrations myapp --empty. This will create an empty migration file under myapp/migrations.
You can then edit it:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
DEFAULT_DOG_TYPES = (
('Labrador', 90),
('Berger Allemand', 66),
('Chihuaha', -2),
)
def add_dog_types(apps, schema_editor):
DogType = apps.get_model('myapp', 'DogType')
for name, max_height in DEFAULT_DOG_TYPES:
dog_type = DogType(name=name, max_height=max_height)
dog_type.save()
def remove_dog_types(apps, schema_editor):
# This is used to migrate backward
# You can remove your dog types, or just pass
# pass
for name, max_height in DEFAULT_DOG_TYPES:
dog_type = DogType.objects.get(name=name, max_height=max_height)
dog_type.delete()
class Migration(migrations.Migration):
dependencies = [
# if you're already using migrations, this line will be different
('myapp', '0001_initial'),
]
operations = [
migrations.RunPython(add_dog_types, remove_dog_types),
]
After that, all you need to do is to run python manage.py syncdb.
not so far after, i found this it's called "fixtures"...
basically what you need to do is to place a "fixture" file in a format of your choice (JSON\YAML...) "myapp/fixtures/" for example, a JSON file would look like this:
[
{
"model": "myapp.person",
"pk": 1,
"fields": {
"first_name": "John",
"last_name": "Lennon"
}
},
{
"model": "myapp.person",
"pk": 2,
"fields": {
"first_name": "Paul",
"last_name": "McCartney"
}
}
]
then simply run from the command line:
python manage.py loaddata <filename> # file with no path!

IntegrityError when loading Django fixtures with OneToOneField using SQLite

When attempting to load initial data via the syncdb command, Django throws the following error:
django.db.utils.IntegrityError: Problem installing fixtures: The row in table 'user_profile_userprofile' with primary key '1' has an invalid foreign key: user_profile_userprofile.user_id contains a value '1' that does not have a corresponding value in user_customuser.id.
There is a OneToOne relationship between the UserProfile model and CustomUser:
class UserProfile(TimeStampedModel):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
Running ./manage.py dumpdata user --format=json --indent=4 --natural-foreign produces the following:
CustomUser Model Data
[
{
"fields": {
"first_name": "Test",
"last_name": "Test",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2014-10-21T11:33:42Z",
"groups": [],
"user_permissions": [],
"password": "pbkdf2_sha256$12000$Wqd4ekGdmySy$Vzd/tIFIoSABP9J0GyDRwCgVh5+Zafn9lOiTGin9/+8=",
"email": "test#test.com",
"date_joined": "2014-10-21T11:22:58Z"
},
"model": "user.customuser",
"pk": 1
}
]
Running ./manage.py dumpdata user_profile --format=json --indent=4 --natural-foreign produces the following:
Profile Model
[
{
"fields": {
"weight": 75.0,
"created": "2014-10-21T11:23:35.536Z",
"modified": "2014-10-21T11:23:35.560Z",
"height": 175,
"user": 1,
},
"model": "user_profile.userprofile",
"pk": 1
}
]
Loading just the CustomUser model's initial data and then following up with UserProfile via load data works great, which suggests to me syncdb is attempting to load UserProfile before CustomUser has been loaded.
If the simplest solution would be to force the load order, what would the simplest way be to do this?
I guess you should use Migrations https://docs.djangoproject.com/en/1.7/topics/migrations/ , they are ordered. But if you using older Django version then 1.7, install south https://south.readthedocs.org/en/latest/

Querying with mongoengine and django

I have a database "tumblelog" (using mongoengine) in which I added some data in the "user" collection with a "User" model:
db.user.find()
...
{ "_id" : ObjectId("4fb0c9494ca88402dd000000"), "_types" : [ "User" ], "first_name" : "John", "last_name" : "Doe", "_cls" : "User", "email" : "jdoe#example.com" }
{ "_id" : ObjectId("4fb0cb9d4ca88402ec000000"), "_types" : [ "User" ], "first_name" : "Joe30", "last_name" : "Foe", "_cls" : "User", "email" : "hu#huu.com" }
When I try User.objects in a django shell, I get the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File ".../mongoengine/queryset.py", line 1127, in __getitem__
return self._document._from_son(self._cursor[key])
File ".../mongoengine/base.py", line 1018, in _from_son
obj = cls(**data)
TypeError: __init__() keywords must be strings
Same thing when I try
for user in User.objects:
print user.first_name
---- Edit ----
I tried this
>>> users = User.objects
>>> users.count()
7
>>> users.first()
...
TypeError: __init__() keywords must be strings
---- Edit 2 ----
I installed my project this way :
> virtualenv Test
> source Test/bin/activate
> pip install Django
> pip install mongoengine
> cd Test/
> django-admin.py startproject db
Then I added the lines
from mongoengine import *
connect('tumblelog')
in settings.py
then I created this simple model
from mongoengine import *
class User(Document):
email = StringField(required=True)
name = StringField(max_length=50)
then I run the server
> python manage.py runserver
And in the shell (python manage.py shell) I can save data if I import my model class but I can't read it, I always have the same TypeError: init() keywords must be strings !
-----Switching to django-mongodb engine----
I didn't find any solution so I will use django-mongodb-engine. I did not find any comparison, but I tried both and it's very similar.
I just regret django-mongodb-engine doesn't handle inheritance principle.
What am I doing wrong ?
Thanks in advance!
we had the exact same issue using mongoengine 0.6.9. I am not suggesting this as an ideal solution but downgrading to 0.6.5 resolved this issue for us.
use the all() method
for user in User.objects.all():
print user.first_name