Snippet List
I don't know if you noticed but GenericForeignKey behaves badly in some situations. Particularly if you assign a not yet saved object (without pk) to this field then you save this object the fk_field does not get updated (even upon saving the model)- it's updated only upon assigning object to the field. So you have to save the related object prior to even **assigning** it to this field. It's get even more apparent when you have null=True on the fk/ct_fields, because then the null constrains won't stop you from saving an invalid object. By invalid I mean an object (based on a model with GFK field) which has ct_field set but fk_field=None.
Maybe this problem is irrelevant in most use case scenarios but this behaviour certainly isn't logical and can introduce silent bugs to your code.
- genericforeignkey
- contenttypes
You can use `UrlModel` to provide URL functionality to any instance of any model and any language (language support can be removed from this). Each model must have own view method, that returns HttpResponse. I was inspired by Flatpages. It is useful for small sites and static pages.
`class Page(UrlModel):
text = models.TextField()
def view(self, request)
# do something here
return HttpResponse(...)`
- middleware
- urls
- models
- foreignkey
- model
- generic
- url
- foreign-key
- genericforeignkey
- contenttypes
- 404
- contenttype
- content-type
Generic Relations with django.contrib.contenttypes.generic.GenericForeignKey work well for models but the admin interface just shows the object id as an integer with no easy way to lookup the id of a new object. This jquery javascript adds a "Lookup <ContentType Name>" link next to the object id field in the admin interface.
This is done by reusing the showRelatedObjectLookupPopup() function provided with django which is used when the field is included in raw_id_fields (a little magnifying glass linked to popup object selector shows up). This essentially works the same way but changes which model's objects are shown and selected in the popup based on the ContentType selected for object_type
- javascript
- admin
- jquery
- genericforeignkey
- lookup
- contenttype
- object_id
- raw_id
- popup
Use this function to merge model objects (i.e. Users, Organizations, Polls, Etc.) and migrate all of the related fields from the alias objects the primary object.
Usage:
from django.contrib.auth.models import User
primary_user = User.objects.get(email='[email protected]')
duplicate_user = User.objects.get(email='[email protected]')
merge_model_objects(primary_user, duplicate_user)
- django
- fields
- model
- generic
- related
- merge
- duplicates
- genericforeignkey
4 snippets posted so far.