w.y
w.y

Reputation: 109

How do I delete a field from my Django ModelForm?

I'm trying to hide and delete two fields from showing in a form I created in the Django administration page using ModelForm. I looked at answers that said I should use the "exclude" meta field, but I don't know why it's not working in my case. Here is my code:

models.py:

class Activity(models.Model):
    type = models.CharField(max_length=50, default="")
    title = models.CharField(max_length=200, default="")
    description = models.CharField(max_length=500)
    owner = models.ForeignKey(User, related_name="owner")
    college = models.CharField(max_length=200)
    location = models.CharField(max_length=200)
    room = models.CharField(max_length=200)
    startDate = models.DateTimeField(null=True, blank=True)
    endDate = models.DateTimeField(null=True, blank=True)
    attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True)
    volunteer = models.ManyToManyField(Volunteer, related_name="volunteers",null=True, blank=True)

I'm trying to exclude the "attendee & volunteer" fields from displaying in the Django administration form.

In admin.py I have:

from django.contrib import admin
from django import forms
from KSUvity.models import Activity


class ActivityForm(forms.ModelForm):

    class Meta:
        model = Activity
        exclude = ['attendee', 'volunteer',]

class ActivityAdmin(admin.ModelAdmin):
    exclude = ['attendee', 'volunteer',]
    form = ActivityForm

admin.site.register(Activity, ActivityAdmin)

Upvotes: 0

Views: 565

Answers (3)

Borut
Borut

Reputation: 3364

You have to use ModelAdmin option to exclude fields from form in Django administration, either ModelAdmin.exclude or ModelAdmin.fields. Below is an example:

class ActivityAdmin(admin.ModelAdmin):
    exclude = ('attendee', 'volunteer', )

To make it work, you register model like this:

admin.site.register(Activity, ActivityAdmin)

You add this code to admin.py file.

Upvotes: 0

Davit Tovmasyan
Davit Tovmasyan

Reputation: 3588

You have to create an admin.py file in your app and register your models Follow the instuctions See the example below

from django import forms
from django.contrib import admin
from myapp.models import Person

class PersonForm(forms.ModelForm):

    class Meta:
        model = Person
        exclude = ['name']

class PersonAdmin(admin.ModelAdmin):
    exclude = ['age']
    form = PersonForm

admin.site.register(Person, PersonAdmin)

Upvotes: 1

Umar Asghar
Umar Asghar

Reputation: 4064

You can use either fields or exclude in one class.

In your app admin field add this code.

app_name/admin.py

from django.contrib import admin


class ActivityAdmin(admin.ModelAdmin):
    exclude = ('attendee', 'volunteer',)

Upvotes: 0

Related Questions