Skip to content

Commit

Permalink
Allowed overriding Role provided initkwargs in as_view(). (#58)
Browse files Browse the repository at this point in the history
* Merge role default and provided initkwargs, allowing overidding by
providing duplicates.
* Ensure provided initkwargs override role defaults.
  • Loading branch information
carltongibson authored Aug 1, 2024
1 parent a92ad4b commit 775241e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
5 changes: 3 additions & 2 deletions src/neapolitan/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from django.urls import path, reverse, NoReverseMatch
from django.urls import NoReverseMatch, path, reverse
from django.utils.decorators import classonlymethod
from django.utils.functional import classproperty
from django.utils.translation import gettext as _
Expand Down Expand Up @@ -456,7 +456,8 @@ def as_view(cls, role: Role, **initkwargs):
)

def view(request, *args, **kwargs):
self = cls(**initkwargs, **role.extra_initkwargs())
# Merge Role default and provided initkwargs.
self = cls(**{**role.extra_initkwargs(), **initkwargs})
self.role = role
self.setup(request, *args, **kwargs)
if not hasattr(self, "request"):
Expand Down
21 changes: 20 additions & 1 deletion tests/tests.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import os

from django.core.management import call_command
from django.test import TestCase
from django.http import HttpResponse
from django.test import RequestFactory, TestCase
from django.urls import reverse
from django.utils.html import escape

from neapolitan.views import CRUDView, Role, classonlymethod

from .models import Bookmark, NamedCollection
Expand Down Expand Up @@ -175,6 +177,23 @@ def test_lookup_url_converter(self):
self.assertEqual(response.status_code, 200)
self.assertContains(response, self.main_collection.name)

def test_overriding_role_initkwargs(self):
"""as_view must proritise initkwargs over Role extra_initkwargs."""

class InitKwargsCRUDView(CRUDView):
model = Bookmark

def detail(self, request, *args, **kwargs):
return HttpResponse(self.template_name_suffix)

view = InitKwargsCRUDView.as_view(
role=Role.DETAIL,
template_name_suffix='_test_suffix'
)
request = RequestFactory().get('/')
response = view(request)
self.assertContains(response, '_test_suffix')


class RoleTests(TestCase):
def test_overriding_url_base(self):
Expand Down

0 comments on commit 775241e

Please sign in to comment.