Skip to content

Instantly share code, notes, and snippets.

@Kenan7
Created October 24, 2024 20:06
Show Gist options
  • Save Kenan7/0a5169242f13b95acd362e5d7a841607 to your computer and use it in GitHub Desktop.
Save Kenan7/0a5169242f13b95acd362e5d7a841607 to your computer and use it in GitHub Desktop.
reverse m2m widget in django admin
from django import forms
from django.contrib import admin
from django.db import models
from django.contrib.admin import widgets
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.utils.translation import gettext as _
class CustomUserForm(forms.ModelForm):
company_structures = forms.ModelMultipleChoiceField(
queryset=CompanyStructure.objects.all(),
widget=widgets.RelatedFieldWidgetWrapper(
widget=widgets.FilteredSelectMultiple('company structures', False),
rel=models.ManyToManyRel(
field=CustomUser,
to=CompanyStructure,
through=CustomUser.company_structures.through
),
admin_site=admin.site
)
)
password = ReadOnlyPasswordHashField(
label=_("Password"),
help_text=_(
"Raw passwords are not stored, so there is no way to see "
"the user’s password."
),
)
class Meta:
model = CustomUser
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance and self.instance.pk:
self.fields['company_structures'].initial = self.instance.company_structures.all()
password = self.fields.get("password")
if password:
if self.instance and not self.instance.has_usable_password():
password.help_text = _(
"Enable password-based authentication for this user by setting a "
"password."
)
user_permissions = self.fields.get("user_permissions")
if user_permissions:
user_permissions.queryset = user_permissions.queryset.select_related(
"content_type"
)
def save(self, commit=True):
instance = super().save(commit=False)
if commit:
instance.save()
# Save the ManyToMany relations
instance.company_structures.set(self.cleaned_data['company_structures'])
return instance
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
objects = CustomUserManager()
def __str__(self):
return self.username
class CompanyStructure(models.Model):
name = models.CharField(max_length=255)
users = models.ManyToManyField(
CustomUser,
related_name='company_structures',
blank=True
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment