django admin slug auto populate

To auto-populate a slug field in Django admin based on another field, follow these steps:

  1. Create a Model: Define a model with the fields you need, including the slug field that you want to auto-populate based on another field.

```python from django.db import models from django.utils.text import slugify

class YourModel(models.Model): title = models.CharField(max_length=100) # Other fields slug = models.SlugField(max_length=100, blank=True) ```

  1. Override the save Method: Override the save method of the model to automatically generate the slug based on the specified field and save it to the slug field.

```python class YourModel(models.Model): title = models.CharField(max_length=100) # Other fields slug = models.SlugField(max_length=100, blank=True)

   def save(self, args, *kwargs):
       if not self.slug:
           self.slug = slugify(self.title)  # Generate slug from title
       super().save(args, *kwargs)

```

  1. Register the Model in Admin: Register the model in the Django admin to view and manage it through the admin interface.

```python from django.contrib import admin from .models import YourModel

@admin.register(YourModel) class YourModelAdmin(admin.ModelAdmin): list_display = ('title', 'slug') # Other configurations ```

  1. Migrate Changes: Apply the changes to the database by running migrations to create or alter the table based on the updated model.

bash python manage.py makemigrations python manage.py migrate

Now, when you create or update an instance of YourModel in the Django admin, the slug field will be automatically populated based on the title field. Adjust the field names and configurations according to your specific use case.