I've been trying to make the GenericTabularInline class work in a two-admin two-databases setup by inheriting from it and overriding some methods in the BaseModelAdmin class, as is done in the Django docs (https://docs.djangoproject.com/en/dev/topics/db/multi-db/), but if a child model is edited in the inline form, it always writes to the default database (I want the second admin to deal exclusively with a secondary database, models are the same for both), so I must not be overriding some method(s) or doing something wrong. Here's the class I have so far:
class MultiDBGenericTabularInline(generic.GenericTabularInline):
using = settings.SECONDARY_DATABASE
def save_model(self, request, obj, form, change):
# Tell Django to save objects to the 'other' database.
obj.save(using=self.using)
def delete_model(self, request, obj):
# Tell Django to delete objects from the 'other' database
obj.delete(using=self.using)
def queryset(self, request):
# Tell Django to look for objects on the 'other' database.
return super(MultiDBGenericTabularInline, self).queryset(request).using(self.using)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
# Tell Django to populate ForeignKey widgets using a query
# on the 'other' database.
return super(MultiDBGenericTabularInline, self).formfield_for_foreignkey(db_field, request=request, using=self.using, **kwargs)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
# Tell Django to populate ManyToMany widgets using a query
# on the 'other' database.
return super(MultiDBGenericTabularInline, self).formfield_for_manytomany(db_field, request=request, using=self.using, **kwargs)
#Override these three methods; otherwise the log manager attempts
#to write to the main db and raises an exception.
def log_addition(self, request, object):
pass
def log_change(self, request, object, message):
pass
def log_deletion(self, request, object, object_repr):
pass
Any help or hints are appreciated.
I realize this is an old question, but I've stumbled across a very similar thing recently. The trick is to override the parent Model Admin's save_formset method. In my case, the solution is to do something like this:
class SomeTabularInline(admin.TabularInline):
# stuff
class MyModelAdmin(admin.ModelAdmin):
using = 'something'
inlines = (SomeTabularInline,)
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for obj in formset.deleted_objects:
obj.delete(using=self.using)
for instance in instances:
instance.save(using=self.using)
formset.save_m2m()
Note: I'm using a TabularInline instance, and not a GenericTabularInline but they both descend from InlineModelAdmin; so I'm hopeful that this would work in your case.
Source: https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_formset
Related
According to the 1.4 documentation on using Admin with multiple databases, you only need to implement 5 methods in your ModelAdmin subclass. I've overridden all 5 in the recommended way. Browsing the database works with no problems.
However, attempt to save an existing record and I get an error claiming that the table doesn't exist in the database - the default database for the project, not the one I've specified in the method implementations. In fact, save_model() doesn't get called before the error is thrown, so somewhere before it gets that far there's a reference somewhere that isn't successfully getting the "using" for the right database.
Anyone know what's missing? Here's my ModelAdmin class:
class TransactionAdmin(admin.ModelAdmin):
using = "salesdb"
def save_model(self, request, obj, form, change):
# Tell Django to save objects to the 'other' database.
obj.save(using=self.using)
def delete_model(self, request, obj):
# Tell Django to delete objects from the 'other' database
obj.delete(using=self.using)
def queryset(self, request):
# Tell Django to look for objects on the 'other' database.
return super(TransactionAdmin, self).queryset(request).using(self.using)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
# Tell Django to populate ForeignKey widgets using a query
# on the 'other' database.
return super(TransactionAdmin, self).formfield_for_foreignkey(db_field, request=request, using=self.using, **kwargs)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
# Tell Django to populate ManyToMany widgets using a query
# on the 'other' database.
return super(TransactionAdmin, self).formfield_for_manytomany(db_field, request=request, using=self.using, **kwargs)
And the error I'm getting is:
(1146, "Table 'django_dev._Transactions' doesn't exist")
django_dev is the default database, not the sales database.
It is apparently a bug.
https://code.djangoproject.com/ticket/19747
The bug has been accepted so I guess that means they confirmed it.
In other words, I would like to disallow users from editing or viewing anything but their own inputted data, throughout all applications.
I read here that this may be impossible with the built in admin application. If so is there an extension available?
Thanks
It can be done.
You need to create the appropriate modelAdmin in your admin.py first.
For list "display" filtering modify the queryset method:
class MyModelAdmin(admin.ModelAdmin):
def queryset(self, request):
return Entry.objects.filter(owner=request.user)
For field filtering, depending on the field type you want to limit you override the appropriate method.
Related django documentation is here:
https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey
To limit foreignkey field output you can do something like this:
(from the django documentation)
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car": # The name of the field you want to limit
kwargs["queryset"] = Car.objects.filter(owner=request.user)
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
I've looked at several questions here that looked similar, but none of them discussed the problem from the perspective of admin panel.
I need to check if user has permission to leave a field empty. I wanted to use request.user but I don't knot how to pass request from EntryAdmin to ModelForm. I wanted to do something like this:
class EntryAdminForm(ModelForm):
class Meta:
model = Entry
def clean_category(self):
if not self.request.user.has_perm('blog.can_leave_empty_category') and not bool(self.category):
raise ValidationError(u'You need to choose a Category!')
else:
return self.cleaned_data['category']
You could override the ModelAdmin.get_form, by adding the request as an attribute of the newly created form class (should be thread-safe).
Something along these lines:
class EntryAdmin(admin.ModelAdmin):
form = EntryAdminForm
def get_form(self, request, *args, **kwargs):
form = super(EntryAdmin, self).get_form(request, *args, **kwargs)
form.request = request
return form
Then the code in your question should work.
Let's say I have a site where Users can add Entries through admin panel. Each User has his own Category he is responsible for (each Category has an Editor assigned through ForeingKey/ManyToManyField).
When User adds Entry, I limit the choices by using EntryAdmin like this:
class EntryAdmin(admin.ModelAdmin):
(...)
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'category':
if request.user.is_superuser:
kwargs['queryset'] = Category.objects.all()
else:
kwargs['queryset'] = Category.objects.filter(editors=request.user)
return db_field.formfield(**kwargs)
return super(EntryAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
This way I can limit the categories to which a User can add Entry and it works perfect.
Now the tricky part: On the Entry changelist/action page I want to show only those Entries which belong to current User's Category. I tried to do this using this method:
def changelist_view(self, request, extra_context=None):
if not request.user.is_superuser:
self.queryset = self.queryset.filter(editors=request.user)
But I get this error:
AttributeError: 'function' object has no attribute 'filter'
This is strange, because I thought it should be a typical QuerySet. Basically such methods are not well documented and digging through tons of Django code is not my favourite sport.
Any ideas how can I achieve my goal?
Warning: This answer is from 2010, and is not useful for Django >= 1.8.
queryset is a method on ModelAdmin which returns a queryset. You need to override it on your EntryAdmin class.
def queryset(self, request):
qs = super(EntryAdmin, self).queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(editors=request.user)
Changing the queryset will limit the Entries shown in the list view. You also need to override has_change_permission to ensure that the user has permission to edit the object on the individual object editing page. See the following blog post by James Bennett for further details:
http://www.b-list.org/weblog/2008/dec/24/admin/
My question is very similar to this one: How do I access the request object or any other variable in a form's clean() method?
Except, I have the same problem with admin form. So I can't see a way to init the form myself, therefore - to pass a request to it.
Thanks beforehand.
Indeed, there is a way to solve your issue!
You will need to subclass form provided by ModelAdmin.get_form() and override it:
class BusinessDocumentCommentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
# Voila, now you can access request anywhere in your form methods by using self.request!
super(BusinessDocumentCommentForm, self).__init__(*args, **kwargs)
if self.request.GET.get('document_pk', False):
#Do something
def clean(self):
# Do something with self.request
# etc.
class Meta:
model = BusinessDocumentComment
class BusinessDocumentCommentAdmin(admin.ModelAdmin):
form = BusinessDocumentCommentForm
def get_form(self, request, obj=None, **kwargs):
AdminForm = super(BusinessDocumentCommentAdmin, self).get_form(request, obj, **kwargs)
class AdminFormWithRequest(AdminForm):
def __new__(cls, *args, **kwargs):
kwargs['request'] = request
return AdminForm(*args, **kwargs)
return AdminFormWithRequest
There are a number of hooks in the ModelAdmin class to allow you to do things this - look at the code in django.contrib.admin.options.
Two methods that might help you are ModelAdmin.save_form and ModelAdmin.save_model, both of which are passed the request object. So you can override these methods in your Admin subclass and do any extra processing you need.
Edited after comment
You're quite right that this won't let you validate the form dependent on the user's privileges. Unfortunately the form instantiation is buried deep within the add_view and change_view methods of ModelAdmin.
There aren't many possibilities without duplicating a lot of existing code. You could override the *_view methods; or you could try and override the modelform_factory function to return a new class with the request object baked in already; or you could try fiddling with the form class __new__ method to do the same thing, but that's tricky because of the form metaclass.
This solution works for me. You can use self.request anywhere in the form to use it, including def clean(self)
class MyModelAdmin(admin.ModelAdmin):
form = MyForm
def get_form(self, request, *args, **kwargs):
form = super(MyModelAdmin, self).get_form(request, *args, **kwargs)
form.request = request
return form