Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete ManyToManyField in Django from admin page and on button click

I have two models as follows:

models.py

from django.db import models
from django.contrib.auth.models import User

class Skill(models.Model):
    skill = models.CharField(max_length=50)

    def __str__(self):
        return self.skill

class Designer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    description = models.TextField(max_length=500, blank=True)    
    date_created = models.DateField(auto_now_add=True)
    profile_img = models.ImageField(upload_to="gallery",null=True, blank=True)
    skills = models.ManyToManyField(Skill, blank=True)
    experience = models.IntegerField(blank=True, null=True)
    account_type = models.CharField(max_length=10)

    def __str__(self):
        return self.user.username

Designer model extends from User model and it has ManyToMany relationship with Skill model. I can add skills to designer instance from admin page but there is no delete option. How can I get the delete option on admin page? I also would like to add the delete functionality on button click. How can I add it in the code?

like image 759
Lax_Sam Avatar asked Oct 27 '25 18:10

Lax_Sam


1 Answers

In ManyToMany relationship field there is no delete functionality we need to use remove an instance for that or in order to clear the field value we need to use clear link

say for your case

our_desire_skill = skills.objects.filter(skill=search_skill)
desiner_user = Designer.objects.get(user=our_desire_user)
desiner_user.skills.remove(our_desire_skill)

If you want to change ManyToManyFields from admin page need to make sure that field is like raw_id_fields link Then you can able to update your ManyToManyField store value from admin site.

like image 101
Shakil Avatar answered Oct 30 '25 09:10

Shakil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!