How can add a dropdown field with options and a default value in the Django admin?

To add a dropdown field with options in the Django admin, you can use the ChoiceField or ForeignKey field in your model. Here's an example:

  1. Define a model with a dropdown field:

from django.db import models

class MyModel(models.Model):
    CHOICES = (
        ('option1', 'Option 1'),
        ('option2', 'Option 2'),
        ('option3', 'Option 3'),
    )
    dropdown_field = models.CharField(max_length=20, choices=CHOICES, default='option1')
 

In the example above, CHOICES defines the available options for the dropdown field. Each option is a tuple containing a value and a human-readable label.

  1. Register the model in the admin site:

from django.contrib import admin
from .models import MyModel

admin.site.register(MyModel)

This will make the model accessible in the Django admin interface.

  1. Run the development server:

python manage.py runserver

Make sure your server is running so you can view the changes in the admin interface.

Now, when you access the admin site and navigate to the model you registered (MyModel in this case), you will see a dropdown field with the defined options. You can select one of the options from the dropdown while adding or editing an instance of the model.

In the example above, the default parameter is set to 'option1', which means that 'Option 1' will be selected by default when creating a new instance of MyModel.

Comments

Leave a Reply