from django.contrib import admin from django import forms from .models import Neo4jProfile class Neo4jProfileForm(forms.ModelForm): """ Custom form to allow secure password & API key updates in Django Admin. """ password = forms.CharField( widget=forms.PasswordInput(render_value=True), required=False, help_text="Leave blank to keep the current password." ) openai_api_key = forms.CharField( widget=forms.PasswordInput(render_value=True), required=False, help_text="Leave blank to keep the current API key." ) class Meta: model = Neo4jProfile fields = "__all__" def clean_password(self): """ Ensure that the password field is only updated if changed. """ password = self.cleaned_data.get("password") if not password and self.instance: return self.instance.password # Keep the existing password if left blank return password def clean_openai_api_key(self): """ Ensure that the OpenAI API key is only updated if changed. """ api_key = self.cleaned_data.get("openai_api_key") if not api_key and self.instance: return self.instance.openai_api_key # Keep the existing API key if left blank return api_key @admin.register(Neo4jProfile) class Neo4jProfileAdmin(admin.ModelAdmin): form = Neo4jProfileForm list_display = ("name", "uri", "model_name") # Display only non-sensitive info search_fields = ("name", "uri", "model_name") # Enable search functionality list_filter = ("model_name",) # Allow filtering by AI model exclude = ("password", "openai_api_key") # Keep sensitive fields hidden in the list view def save_model(self, request, obj, form, change): """ Custom save behavior to log when an admin modifies a profile. """ if change: self.message_user(request, f"Updated Neo4j Profile: {obj.name}") else: self.message_user(request, f"Created new Neo4j Profile: {obj.name}") super().save_model(request, obj, form, change)