Foreign key and select the field value in the admin interface

I am trying to create an application where each element must be associated with some kind of user. Easy to put them together

user = models.ForeignKey(User) 

Unfortunately, in this case, in django admin, I get a selection box with all the users listed by their usernames. Also, I need their first_name and last_name. I just can't figure out if there is a way to show all the names together in this select list in the django admin interface.

+6
source share
2 answers

To do this, you need to create a custom Form and set the form attribute in ModelAdmin .

In this Form you need to redefine the field type of the user field form on the model to the custom ModelChoiceField .

ModelChoiceField has a method called label_from_instance , you need to override it to get the full name.

Code example

 ###################################### ## models.py ## ###################################### from django.db import models from django.contrib.auth.models import User class Item(models.Model): user = models.ForeignKey(User) name = models.CharField("name", max_length=60) def __unicode__(self): return self.name ###################################### ## forms.py ## ###################################### from django import forms from django.contrib.auth.models import User from .models import Item class CustomUserChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.get_full_name() class ItemForm(forms.ModelForm): user = CustomUserChoiceField(queryset=User.objects.all()) class Meta: model = Item ###################################### ## admin.py ## ###################################### from django.contrib import admin from .models import Item from .forms import ItemForm class ItemAdmin(admin.ModelAdmin): form = ItemForm admin.site.register(Item, ItemAdmin) 

Source Code Link

https://github.com/django/django/blob/1.4.5/django/forms/models.py#L948

Matters Related

+15
source

Django uses unicode (obj) (or a related function, str (obj)) in several places. In particular, to display the object on the Django admin site and as a value inserted into the template when it displays the object.

See __unicode__ from https://docs.djangoproject.com/en/dev/ref/models/instances/

You can change the __unicode__ method of the User class. The following are sample code.

 from django.db import models from django.contrib.auth.models import User def myunicode(self): return self.get_full_name() # Create your models here. class Item(models.Model): User.__unicode__ = myunicode user = models.ForeignKey(User) name = models.CharField("name", max_length=60) def __unicode__(self): return self.name 
+2
source

Source: https://habr.com/ru/post/944259/


All Articles