Hello,

I'm interested what's the proper/best way to restrict foreign keys when
adding a new object through the admin interface.

For example, let's say I have models like this:

class Project(models.Model):
    name = models.CharField(max_length = 100)

class Entity(models.Model):
    name = models.CharField(max_length = 100)

class Connection(models.Model):
    name = models.CharField(max_length = 100)
    first = models.ForeignKey(Entity, related_name = "first_set")
    second = models.ForeignKey(Entity, related_name = "second_set")

And let's say I have an admin class like this:

class ConnectionAdmin(admin.ModelAdmin):
    list_display = ('name', 'first', 'second')
    list_filter = ['first__entity__project']

What I need to be able to do is when I select a particular project in
the admin interface, and proceed to then add a new object, get the
filter applied to my foreign key fields.

Right now, what I'm doing is overriding the formfield_for_foreignkey in
the above ConnectionAdmin class to get this behaviour, but the tricky
part was actually getting this project filter information available to
my overridden method. The way I did it was by overriding the
chante_list.html admin template. Inside of it I've done this:

{% extends "admin/change_list.html" %}
{% load i18n admin_static admin_list %}
{% load url from future %}
{% load admin_urls %}

{% block object-tools-items %}
            <li>
              {# Add the GET parameters from the admin's filter to 'Add entity' 
button #}
              {# so we can perform some filtering on first/second. #}
              <a href="{% url cl.opts|admin_urlname:'add' %}?{% if is_popup 
%}_popup=1{% endif %}{% if 'first__entity__project__id__exact' in cl.params 
%}&first__entity__project__id__exact={{ 
cl.params.first__entity__project__id__exact }}{% endif %}" class="addlink">
                {% blocktrans with cl.opts.verbose_name as name %}Add {{ name 
}}{% endblocktrans %}
              </a>
            </li>
{% endblock %}

I.e. I'm overriding the link for adding the new object to include get
parameters that are the same as the ones used for filtering in list
view.

So, is this the right way (or did I fail to find the information in the
documentation on this)?

Best regards

P.S.
The actual application code I'm working on can be found at (the above
example is a bit simplified to what I have):

http://hg.majic.rs/conntrackt/

-- 
Branko Majic
Jabber: bra...@majic.rs
Please use only Free formats when sending attachments to me.

Бранко Мајић
Џабер: bra...@majic.rs
Молим вас да додатке шаљете искључиво у слободним форматима.

Attachment: signature.asc
Description: PGP signature

Reply via email to