4

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!

doniyor
  • 36,596
  • 57
  • 175
  • 260
Matthias Scholz
  • 1,015
  • 1
  • 13
  • 25

3 Answers3

0

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).

Alvin Lindstam
  • 3,094
  • 16
  • 28
0

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

In your form.py:

class YOURMODELForm(forms.ModelForm):
    approved = forms.ModelChoiceField(queryset=User.objects.order_by('name'))
Ohad the Lad
  • 1,889
  • 1
  • 15
  • 24