mirror of
https://github.com/django/django.git
synced 2025-04-12 11:32:20 +00:00
minor edits to widgets.py to satisfy missing attributes test case, completed and passing test case for new filtered select functionality
This commit is contained in:
parent
a9528e68c8
commit
7a4bd305fd
3
.gitignore
vendored
3
.gitignore
vendored
@ -20,4 +20,5 @@ tests/screenshots/
|
||||
venv/
|
||||
.venv/
|
||||
env/
|
||||
.env/
|
||||
.env/
|
||||
myproject/staticfiles
|
@ -40,6 +40,10 @@ class FilteredSelectMultiple(forms.SelectMultiple):
|
||||
super().__init__(attrs, choices)
|
||||
|
||||
def get_context(self, name, value, attrs):
|
||||
if name is None:
|
||||
name = "None"
|
||||
if attrs is None:
|
||||
attrs = {}
|
||||
context = super().get_context(name, value, attrs)
|
||||
widget_attrs = context["widget"]["attrs"]
|
||||
widget_attrs["class"] = "selectfilter"
|
||||
|
22
myproject/admin.py
Normal file
22
myproject/admin.py
Normal file
@ -0,0 +1,22 @@
|
||||
from django.contrib import admin
|
||||
from django.forms import ModelForm
|
||||
from django.contrib.admin.widgets import FilteredSelectMultiple
|
||||
from .models import ParentModel, ChildModel
|
||||
|
||||
class ChildModelForm(ModelForm):
|
||||
class Meta:
|
||||
model = ChildModel
|
||||
fields = '__all__'
|
||||
widgets = {
|
||||
'related_field': FilteredSelectMultiple('Related Items', False),
|
||||
}
|
||||
|
||||
class ChildInline(admin.TabularInline):
|
||||
model = ChildModel
|
||||
form = ChildModelForm
|
||||
extra = 1
|
||||
|
||||
class ParentModelAdmin(admin.ModelAdmin):
|
||||
inlines = [ChildInline]
|
||||
|
||||
admin.site.register(ParentModel, ParentModelAdmin)
|
BIN
myproject/db.sqlite3
Normal file
BIN
myproject/db.sqlite3
Normal file
Binary file not shown.
22
myproject/manage.py
Executable file
22
myproject/manage.py
Executable file
@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env python
|
||||
"""Django's command-line utility for administrative tasks."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
"""Run administrative tasks."""
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Couldn't import Django. Are you sure it's installed and "
|
||||
"available on your PYTHONPATH environment variable? Did you "
|
||||
"forget to activate a virtual environment?"
|
||||
) from exc
|
||||
execute_from_command_line(sys.argv)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
14
myproject/models.py
Normal file
14
myproject/models.py
Normal file
@ -0,0 +1,14 @@
|
||||
from django.db import models
|
||||
|
||||
class ParentModel(models.Model):
|
||||
name = models.CharField(max_length=255)
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
class ChildModel(models.Model):
|
||||
parent = models.ForeignKey(ParentModel, on_delete=models.CASCADE, related_name="children")
|
||||
related_field = models.ManyToManyField(ParentModel, related_name="related_items")
|
||||
|
||||
def __str__(self):
|
||||
return f"Child of {self.parent.name}"
|
0
myproject/myapp/__init__.py
Normal file
0
myproject/myapp/__init__.py
Normal file
22
myproject/myapp/admin.py
Normal file
22
myproject/myapp/admin.py
Normal file
@ -0,0 +1,22 @@
|
||||
from django.contrib import admin
|
||||
from django.forms import ModelForm
|
||||
from django.contrib.admin.widgets import FilteredSelectMultiple
|
||||
from .models import ParentModel, ChildModel
|
||||
|
||||
class ChildModelForm(ModelForm):
|
||||
class Meta:
|
||||
model = ChildModel
|
||||
fields = '__all__'
|
||||
widgets = {
|
||||
'related_field': FilteredSelectMultiple('Related Items', False),
|
||||
}
|
||||
|
||||
class ChildInline(admin.TabularInline):
|
||||
model = ChildModel
|
||||
form = ChildModelForm
|
||||
extra = 1
|
||||
|
||||
class ParentModelAdmin(admin.ModelAdmin):
|
||||
inlines = [ChildInline]
|
||||
|
||||
admin.site.register(ParentModel, ParentModelAdmin)
|
6
myproject/myapp/apps.py
Normal file
6
myproject/myapp/apps.py
Normal file
@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class MyappConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'myapp'
|
30
myproject/myapp/migrations/0001_initial.py
Normal file
30
myproject/myapp/migrations/0001_initial.py
Normal file
@ -0,0 +1,30 @@
|
||||
# Generated by Django 5.2.dev20241207001149 on 2024-12-08 21:12
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='ParentModel',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=255)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='ChildModel',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('parent', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='children', to='myapp.parentmodel')),
|
||||
('related_field', models.ManyToManyField(related_name='related_items', to='myapp.parentmodel')),
|
||||
],
|
||||
),
|
||||
]
|
0
myproject/myapp/migrations/__init__.py
Normal file
0
myproject/myapp/migrations/__init__.py
Normal file
14
myproject/myapp/models.py
Normal file
14
myproject/myapp/models.py
Normal file
@ -0,0 +1,14 @@
|
||||
from django.db import models
|
||||
|
||||
class ParentModel(models.Model):
|
||||
name = models.CharField(max_length=255)
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
class ChildModel(models.Model):
|
||||
parent = models.ForeignKey(ParentModel, on_delete=models.CASCADE, related_name="children")
|
||||
related_field = models.ManyToManyField(ParentModel, related_name="related_items")
|
||||
|
||||
def __str__(self):
|
||||
return f"Child of {self.parent.name}"
|
47
myproject/myapp/tests.py
Normal file
47
myproject/myapp/tests.py
Normal file
@ -0,0 +1,47 @@
|
||||
from django.test import TestCase
|
||||
from django.contrib.admin.widgets import FilteredSelectMultiple
|
||||
|
||||
class WidgetContextTests(TestCase):
|
||||
def test_widget_context(self):
|
||||
widget = FilteredSelectMultiple(verbose_name="Test Field", is_stacked=False)
|
||||
context = widget.get_context(name="test", value=None, attrs={"id": "test_id"})
|
||||
widget_attrs = context["widget"]["attrs"]
|
||||
|
||||
self.assertIn("class", widget_attrs)
|
||||
self.assertEqual(widget_attrs["class"], "selectfilter")
|
||||
self.assertEqual(widget_attrs["data-field-name"], "Test Field")
|
||||
self.assertEqual(widget_attrs["data-is-stacked"], 0)
|
||||
self.assertEqual(widget_attrs["id"], "test_id")
|
||||
|
||||
def test_widget_context_stacked(self):
|
||||
widget = FilteredSelectMultiple(verbose_name="Test Field", is_stacked=True)
|
||||
context = widget.get_context(name="test", value=None, attrs={"id": "test_id"})
|
||||
widget_attrs = context["widget"]["attrs"]
|
||||
|
||||
self.assertIn("class", widget_attrs)
|
||||
self.assertEqual(widget_attrs["class"], "selectfilterstacked")
|
||||
self.assertEqual(widget_attrs["data-field-name"], "Test Field")
|
||||
self.assertEqual(widget_attrs["data-is-stacked"], 1)
|
||||
self.assertEqual(widget_attrs["id"], "test_id")
|
||||
|
||||
def test_widget_context_no_attrs(self):
|
||||
widget = FilteredSelectMultiple(verbose_name="Test Field", is_stacked=False)
|
||||
context = widget.get_context(name="test", value=None, attrs={}) # Use empty dict for attrs
|
||||
widget_attrs = context["widget"]["attrs"]
|
||||
|
||||
self.assertIn("class", widget_attrs)
|
||||
self.assertEqual(widget_attrs["class"], "selectfilter")
|
||||
self.assertEqual(widget_attrs["data-field-name"], "Test Field")
|
||||
self.assertEqual(widget_attrs["data-is-stacked"], 0)
|
||||
self.assertEqual(widget_attrs["id"], "id_test")
|
||||
|
||||
def test_widget_context_missing_name_or_attrs(self):
|
||||
widget = FilteredSelectMultiple(verbose_name="Test Field", is_stacked=False)
|
||||
|
||||
# Test with name=None and id not explicitly set
|
||||
context = widget.get_context(name=None, value=None, attrs={})
|
||||
self.assertEqual(context["widget"]["attrs"]["id"], "id_None") # Default id format for None name
|
||||
|
||||
# Test with attrs=None, expecting it to default to an empty dict
|
||||
context = widget.get_context(name="test", value=None, attrs=None)
|
||||
self.assertEqual(context["widget"]["attrs"]["id"], "id_test") # Default id format for valid name
|
3
myproject/myapp/views.py
Normal file
3
myproject/myapp/views.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.shortcuts import render
|
||||
|
||||
# Create your views here.
|
0
myproject/myproject/__init__.py
Normal file
0
myproject/myproject/__init__.py
Normal file
16
myproject/myproject/asgi.py
Normal file
16
myproject/myproject/asgi.py
Normal file
@ -0,0 +1,16 @@
|
||||
"""
|
||||
ASGI config for myproject project.
|
||||
|
||||
It exposes the ASGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/dev/howto/deployment/asgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
|
||||
|
||||
application = get_asgi_application()
|
129
myproject/myproject/settings.py
Normal file
129
myproject/myproject/settings.py
Normal file
@ -0,0 +1,129 @@
|
||||
"""
|
||||
Django settings for myproject project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 5.2.dev20241207001149.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/dev/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/dev/ref/settings/
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
STATIC_ROOT = BASE_DIR / "staticfiles"
|
||||
|
||||
STATICFILES_DIRS = [
|
||||
BASE_DIR.parent / "js_tests", # For the JavaScript tests
|
||||
BASE_DIR.parent / "node_modules", # Adjust the path for node_modules
|
||||
]
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = 'django-insecure-!!3hix%_eqnt@=4-1-jdfv8&&&_nn8x1%0trmaz$03eeu#%yoe'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'myapp',
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
|
||||
ROOT_URLCONF = 'myproject.urls'
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
'django.template.context_processors.request',
|
||||
'django.contrib.auth.context_processors.auth',
|
||||
'django.contrib.messages.context_processors.messages',
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = 'myproject.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': BASE_DIR / 'db.sqlite3',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/dev/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/dev/howto/static-files/
|
||||
|
||||
STATIC_URL = 'static/'
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/dev/ref/settings/#default-auto-field
|
||||
|
||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
27
myproject/myproject/urls.py
Normal file
27
myproject/myproject/urls.py
Normal file
@ -0,0 +1,27 @@
|
||||
"""
|
||||
URL configuration for myproject project.
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/dev/topics/http/urls/
|
||||
Examples:
|
||||
Function views
|
||||
1. Add an import: from my_app import views
|
||||
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
||||
Class-based views
|
||||
1. Add an import: from other_app.views import Home
|
||||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
||||
Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.contrib import admin
|
||||
from django.urls import path
|
||||
from django.conf import settings
|
||||
from django.conf.urls.static import static
|
||||
|
||||
urlpatterns = [
|
||||
path('admin/', admin.site.urls),
|
||||
]
|
||||
|
||||
if settings.DEBUG:
|
||||
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
16
myproject/myproject/wsgi.py
Normal file
16
myproject/myproject/wsgi.py
Normal file
@ -0,0 +1,16 @@
|
||||
"""
|
||||
WSGI config for myproject project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
|
||||
|
||||
application = get_wsgi_application()
|
Loading…
x
Reference in New Issue
Block a user