About Showing Model-form Fields only for Staff Users
You can show particular model-form fields conditionally using this technique:
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "content"]
def __init__(self, request, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request = request
if request.user.is_staff:
if self.instance._state.adding:
is_featured_initial = False
else:
is_featured_initial = self.instance.is_selected
model_field = Post._meta.get_field("is_featured")
self.fields["is_featured"] = model_field.formfield(
initial=is_featured_initial,
)
def save(self, commit=True):
instance = super().save(commit=False)
if "is_featured" in self.fields:
instance.is_featured = self.cleaned_fields["is_featured"]
if commit:
instance.save()
self.save_m2m()
return instance
Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django App for You
Django GDPR Cookie Consent app
For Django websites that use cookies.
Django App for You