Skip to content

Instantly share code, notes, and snippets.

@frutik
Created October 10, 2012 21:04
Show Gist options
  • Save frutik/3868392 to your computer and use it in GitHub Desktop.
Save frutik/3868392 to your computer and use it in GitHub Desktop.
from restoran.models import *
from django.contrib import admin
class DishIngredientInline(admin.StackedInline):
model = Dish.ingredients.through
extra = 1
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
field = super(DishIngredientInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
if db_field.name == 'dishingredient':
if request._obj_ is not None:
field.queryset = field.queryset.filter(group=request._obj_.group)
else:
field.queryset = field.queryset.none()
return field
class DishAdmin(admin.ModelAdmin):
exclude = ['ingredients']
def change_view(self, request, obj_id):
self.inlines=[DishIngredientInline,]
self.inline_instances = []
for inline_class in self.inlines:
inline_instance = inline_class(self.model, self.admin_site)
self.inline_instances.append(inline_instance)
return super(DishAdmin, self).change_view(request, obj_id)
def add_view(self, request):
self.inlines=[]
self.inline_instances = []
return super(DishAdmin, self).add_view(request)
def get_form(self, request, obj=None, **kwargs):
request._obj_ = obj
return super(DishAdmin, self).get_form(request, obj, **kwargs)
class DishGroupAdmin(admin.ModelAdmin):
pass
class DishIngredientAdmin(admin.ModelAdmin):
pass
admin.site.register(Dish, DishAdmin)
admin.site.register(DishGroup, DishGroupAdmin)
admin.site.register(DishIngredient, DishIngredientAdmin)
from django.db import models
class DishGroup(models.Model):
name=models.CharField(max_length=32)
def __unicode__(self):
return self.name
class DishIngredient(models.Model):
name = models.CharField(max_length=32)
group = models.ForeignKey(DishGroup)
def __unicode__(self):
return self.name
class Dish(models.Model):
name = models.CharField(max_length=32)
group = models.ForeignKey(DishGroup)
ingredients = models.ManyToManyField(DishIngredient, related_name='dish')
def __unicode__(self):
return self.name
@nfx
Copy link

nfx commented Oct 11, 2012

i to peton?

@gsvster
Copy link

gsvster commented Oct 11, 2012

nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment