Home > Net >  How to insert a search engine instead of a list in the Django model
How to insert a search engine instead of a list in the Django model

Time:01-16

I am creating a model and a field is presented as a list, I would like it not to be a list but a search engine, this in the administrator when I want to insert new data in my table, I would like the author part to be a search engine and not a list.

from django.conf import settings
from django.db import models
from django.utils import timezone


class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

[enter image description here]()

I don't know if this can be done in the model.

CodePudding user response:

In the ModelAdmin, you can make the item searchable, with:

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    autocomplete_fields = ['author']
    # …

Note: You can set a field editable=False [Django-doc]. Then the field does not show up in the ModelForms and ModelAdmins by default. In this case for example with publish.


Note: Django's DateTimeField [Django-doc] has a auto_now_add=… parameter [Django-doc] to work with timestamps. This will automatically assign the current datetime when creating the object, and mark it as non-editable (editable=False), such that it does not appear in ModelForms by default.

CodePudding user response:

What you are looking for is raw_id_fields in your admin. This allows you to input the id directly or look up the related table by clicking the search icon.

In your model admin:

class PostAdmin(admin.ModelAdmin):
    raw_id_fields = ('author',)
  • Related