Reputation: 157
I have these 3 models in models.py
class Customer(models.Model):
name = models.CharField(max_length=50)
....
class Agent(django.contrib.auth.models.User):
regions = models.CharField(max_length=50, choices={...})
....
class Payment(models.Model):
added_by = models.ForeignKey(Agent)
customer = models.ForeignKey(Customer)
date = models.DateField(default=datetime.date.today())
amount = models.IntegerField(default=0)
and also in my admin.py, I have these classes:
class PaymentInline(admin.TabularInline):
model = Payment
extra = 0
class CustomerAdmin(admin.ModelAdmin):
inlines = [PaymentInline,]
Question#1: is it possible to have the 'agent' field pre-set to the current logged in Agent in 'PaymentInline' in Customer change page. we can preset the value for the agent field, just like the way that django does for 'Customer' field, which is hidden from the inline already.
Question#2: or is there a way to construct a link, with the customer_id and agent_id "hardcoded" in the url; and in the add payment page, we could have the default and non-editable values for customer field and agent field for example, this url[1] will link us to the normal add page, but with the customer_field and agent_feild set to Agent.objects.get(id=1) and Customer.objects.get(id=1). (Or we can hide these 2 fields since they are non-editable anyway)
[1]http://localhost:8000/admin/my_app/payment/add/?customer_id=1&agent_id=1
Any thoughts?
Thanks
Max
Upvotes: 3
Views: 3229
Reputation: 12968
A TabularInline is an InlineModelAdmin and as such let's you define formfield_for_foreignkey():
class PaymentInline(admin.TabularInline):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'added_by':
kwargs['initial'] = request.user.id
return db_field.formfield(**kwargs)
return super(MyModelAdmin, self).formfield_for_foreignkey(
db_field, request, **kwargs
)
Upvotes: 5
Reputation: 36
Q1: My guess would be to edit the inline template, hide the Agent column and set it by default to the logged in user. Q2: GET arguments are passed to the form by default. If you want to make some fields not non-editable I think you need to alter the template to check for presence of those arguments and then hide the fields (or not). Alternatively you could pass different form to the ModelAdmin view (also after checking for the presence of GET options).
Tomus
Upvotes: 1