I am using the method described in this question to load intial users for my django project.
This saves user permissions, where one permission record might look like this:
{
"pk": 56,
"model": "auth.permission",
"fields": {
"codename": "change_somemodel",
"name": "Can change some model",
"content_type": 19
}
And a user record:
{
"pk": 2,
"model": "auth.user",
"fields": {
"username": "some_user",
"first_name": "",
"last_name": "",
"is_active": true,
"is_superuser": false,
"is_staff": true,
"last_login": "2011-09-20 06:36:54",
"groups": [],
"user_permissions": [
10,
11,
19,
20,
21,
1,
2,
56,
...,
],
"password": "sha1$e4f29$fcec7f8bb930d98abdaaa3c0020220f413c4c1f5",
"email": "",
"date_joined": "2011-03-15 06:01:41"
}
Is there any potential for the content type foreign key to change on a future installation? How about if models or apps added? For example, let's say I add a model to my core app, then I have some reusable apps which are listed after that in settings.py, will those have a different content_type_id on a new installation? Can I include the content_type table in my initial data, or is that likely to cause other issues?
If this isn't a reliable method to load multiple initial users into the database, what are the alternatives?
Check Natural Keys
. Use -n w/ dumpdata, like ./manage.py dumpdata -n auth.User
In practice, it may be that you also have to exclude contenttypes to make this work. Additionally, if you have any user or group data, you'll need to dump those as well. See this thread for more info on excluding contenttypes.
For my app, I had to use the following command for loaddata or test to work with the fixtures generated by manage.py dumpdata. Additionally, you should probably use --indent N option to make sure that you get a human readable file (where N is the number of spaces for indentation)
./manage.py dumpdata -n --indent 4 -e contenttypes appName auth.Group auth.User > initial_data.json
Related
I want populate my database with initial data (dummy data). I have DateTimeFields in many models and for the DateTimeFields it would be good to have a variable in my fixtures files (json, yaml, xml). E.g.: now() + 7h, now() + 6d + 8h + 30m
https://docs.djangoproject.com/en/3.2/howto/initial-data/ :
[
{
"model": "myapp.person",
"pk": 1,
"fields": {
"first_name": "John",
"last_name": "Lennon",
"appointment": now(),
}
},
]
Is there a solution for it?
I found a nice solution. I combined the following very nice python packages FactoryBoy + django-dynamic-fixtures + Faker. Works fine for me. I hope it will hep someone
When I run django tests I get the error:
IntegrityError: Problem installing fixture ... ContentType matching
query does not exist.: (auth.group:pk=2) field_value was
'[u'add_corsmodel', u'corsheaders', u'corsmodel']'
I get the fixtures by doing
python manage.py dumpdata --natural-foreign --exclude=contenttypes --exclude=auth.Permission
How can I solve this? should I exclude some other table?
well I tried to do one simple thing to add permissions.
I've created a .json file and put in data.
[
{
"model": "auth.group",
"fields": {
"name": "foo",
"permissions": [
29,45,46,47,48 //permission ID's created in auth.group
]
}
},
{
"model": "auth.group",
"fields": {
"name": "new_grp",
"permissions": [
29,45,46,47,48
]
}
}
]
this is my initial permissions that I want to include and then
manage.py loaddata <myJsonFIle>
i think in your case it is not able to find the rows or columns in the table that's why it shows IntegrityError
Removing Group from your fixture resolves your issue
because Group depends on Permission which depends on ContentType, both of which were stripped from the export.
Judging from your comments on this question it sounds like you already figured that part out. There is another answer to you question though: Don't use fixtures for test data in Django. Django's documentation suggests you use the TestCase.setUpTestData method to setup your test data. Here's the exert from the documentation: "Tests are more readable and it’s more maintainable to create objects using the ORM."
I am using django-jsonify to convert django variable into json in javascript, and it returns such list
[{"pk": 4, "model": "api.post", "fields": {"summary": "Testing", "title": "My Test"}}, {"pk": 5, "model": "api.post", "fields": {"summary": "testing again", "title": "Another test"}}]
But desired list is
[{"pk": 4,"summary": "Testing", "title": "My Test"}, {"pk": 5,"summary": "testing again", "title": "Another test"}]
django-jsonify is just a thin wrapper around Django's builtin JSON model serializer. See:
https://bitbucket.org/marltu/django-jsonify/src/586ff1bbdd9b1c20e450015a093c146e58d40ddb/jsonify/templatetags/jsonify.py?at=default
If you want a different format, you'll have to define your own serializer. To do so, subclass the stdlib's json.JSONEncoder, and override the .default() method:
http://docs.python.org/2/library/json.html#json.JSONEncoder.default
You'll also need to hook up your own template tag (or pass the JSON via the view, etc) - but, as you can see in the django-jsonify source, that part isn't very much code.
I'm on a page which sends a request to server side for a list of comments of current topic.
like this
localhost:8000/getComments/567 , while 567 is the topic id.
then, in my django view, like this:
def getProjectComments(request, pId):
format = 'json'
mimetype = 'application/javascript' #'application/xml' for 'xml' format
comments = PrjComment.objects.filter(prj=pId)
data = serializers.serialize(format, comments)
return HttpResponse(data,mimetype)
Now , the question is ,
when I try to use jQuery.parseJSON(data) at the browser side.
[
{
"pk": 10,
"model": "app.prjcomment",
"fields":
{
"status": 1,
"time_Commented": "2011-12-11 17:23:56",
"prj": 1,
"content": "my comment 1",
"user": 25
}
},
{
"pk": 9,
"model": "app.prjcomment",
"fields": {
"status": 1,
"time_Commented": "2011-12-11 17:23:51",
"prj": 1,
"content": "comment \u4e00\u4e2a",
"user": 33
}
} ..
I need to use some detail information of user object. (user is a Foreign Key in model PrjComment)
such as user.first_name to display on the comment list.
but here it is only an id for user.("user": 33)
How can I do that? Anyone who can kind help?
Thank you very much
the User is the Django auth_user.
The easy solution would be to specify the values you need:
comments = PrjComment.objects.filter(prj=pId) \
.values('status','time_commented','prj','content','user__id',
'user__username','user__first_name')
Update:
To access your userprofile information use the table name as defined in your AUTH_PROFILE_MODULE setting. In my case the table is called userprofile, and I'd access the data like this:
values('user__userprofile__moreinfo')
where moreinfo is the field you're interested in
I have a fixture with multiple models that I'm using for testing. It
works for the basic models, but fails to create the entities for the
models with relationships. Is this a known limitation of app-engine-patch or am I missing
something? I'm using JSON for the fixture file.
I'm creating the fixture file with 'manage.py dumpdata --format=json >> file.json'
Here are the models involved:
class BibleBook(db.Model):
name = db.StringProperty(required=True)
description = db.TextProperty(required=True)
class Task(db.Model):
name = db.StringProperty(required=True)
description = db.TextProperty(required=True)
energy = db.IntegerProperty(default=1)
focus = db.IntegerProperty(default=0)
empathy = db.IntegerProperty(default=0)
denarii = db.IntegerProperty(default=0)
talents = db.IntegerProperty(default=0)
experience = db.IntegerProperty(default=1)
percent_per_task = db.IntegerProperty(default=5)
bibleBook = db.ReferenceProperty(BibleBook)
level = db.StringProperty(required=True, choices=set(["Catachumen", "Laymen", "Elder"]))
drop_percentage = db.IntegerProperty(default=10)
The json in the fixture file looks like this:
[
{"pk": "ag5sYXctYW5kLWdvc3BlbHIcCxIWbGF3YW5kZ29zcGVsX2JpYmxlYm9vaxgDDA",
"model": "lawandgospel.biblebook",
"fields": {"name": "Luke", "description": "Description"}},
{"pk": "ag5sYXctYW5kLWdvc3BlbHIXCxIRbGF3YW5kZ29zcGVsX3Rhc2sYBQw",
"model": "lawandgospel.task",
"fields": {"empathy": 0, "name": "Study Luke", "level": "Catachumen", "energy": 1,
"focus": 0, "experience": 1, "drop_percentage": 10, "talents": 0,
"bibleBook": "ag5sYXctYW5kLWdvc3BlbHIcCxIWbGF3YW5kZ29zcGVsX2JpYmxlYm9vaxgDDA",
"percent_per_task": 5, "denarii": 0, "description": "The Book of Luke"}}
]
The BibleBook model loads properly, but the Task one does not.
I'm checking this by doing:
books = BibleBook.gql('')
self.assertEquals(books.count(), 1)
tasks = Task.gql('')
self.assertEquals(tasks.count(), 1)
The first test passes, but the second does not.
Thanks,
Brian Yamabe
Thanks, celopes, for asking for the additional code. I decided to play with the json file and fixed the problem by using simple numbers for the pk's. Here's the JSON that fixes the problem for the models and tests I posted:
[
{"pk": "1",
"model": "lawandgospel.biblebook",
"fields": {"name": "Luke", "description": "The Gospel According to St. Luke."}},
{"pk": "2",
"model": "lawandgospel.task",
"fields": {"empathy": 0, "name": "Study the Gospel of Luke", "level": "Catachumen",
"energy": 1, "focus": 0, "experience": 1, "drop_percentage": 10, "talents": 0,
"bibleBook": "1", "percent_per_task": 5, "denarii": 0,
"description": "The Book of Luke"}}
]