Django Admin Custom Widget for ForeignKey

3.8k views Asked by At

It sounds like a trivial question, but it seems not so easy to answer:

How would you display a ForeignKey field as a Checkbox in Django Admin and save the currently logged in user whenever this user checks the checkbox in Admin?

Example:

class MyModel(models.Model):
    ...
    approved = models.ForeignKey(User)
    ...

admin.site.register(MyModel)

How would I be able to display the approved field as a checkbox?

Thanks alot in advance for your help!

3

There are 3 answers

2
Alvin Lindstam On

You could use the get_form method on your ModelAdmin, and customize the form to what you wish.

In this case, you would have to change the fields widget to a checkbox, and set the value to request.user on form validation (if checked).

0
Suresh Jaganathan On

You can customize it as follows in admin.py

class MyModelWidget(forms.ModelForm):
    approved = forms.BooleanField(widget=forms.CheckboxInput())

    class Meta:
        model = MyModel
admin.site.register(MyModel, MyModelWidget)

Refer https://docs.djangoproject.com/en/1.9/ref/contrib/admin/

0
Ohad the Lad On

In your form.py:

class YOURMODELForm(forms.ModelForm):
    approved = forms.ModelChoiceField(queryset=User.objects.order_by('name'))