Disclaimer: I'm new to Django and testing
I have some models in Django admin, but I'm overriding the save_model() function of a particular model. I'm unable to test Model.create() because the admin save_model() override isn't called. What would be the right way to test this function? Any example code would be very much appreciated :) Here's mine:
models.py
class Page(models.Model):
title = models.CharField(max_length=100)
content = models.CharField(max_length=50000)
path = models.CharField(max_length=300, unique=True,
help_text='Leave this blank to automatically generate a path.',
blank=True
)
pub_date = models.DateTimeField('publication date', default=timezone.now)
def __str__(self):
return self.title
admin.py
class NavigationInline(admin.StackedInline):
model = Navigation
class PageForm(forms.ModelForm):
content = forms.CharField(widget=TinyMCE(attrs={'cols': 120,
'rows': 20})
)
class Meta:
fields = ('title', 'pub_date')
model = Page
class PageAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['title', 'content', 'path']}),
('Scheduling', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
form = PageForm
inlines = [NavigationInline]
def save_model(self, request, obj, form, change):
obj.save()
# All kinds of craziness to be tested!
In the end I used the django client. I didn't do this initially because I was having trouble with a 'managementform data is missing or has been tampered with' error, and I ended up checking the data posted to the form to realise that I wasn't posting the required 'TOTAL-FORMS' values. Once I added these, the client testing worked fine:
class ModelAdminTests(TestCase):
def create_page(self, title, content, parent_page_id=''):
self.client = Client()
self.client.login(username='admin', password='Password123')
self.client.post(
'/admin/pages/page/add/',
{
'title': title,
'content': content,
'pub_date_0': '2017-01-01',
'pub_date_1': '12:00:00',
'navigation-0-title': 'Home',
'navigation-0-weight': 0,
'navigation-0-parent': parent_page_id,
'navigation-TOTAL_FORMS': '1',
'navigation-INITIAL_FORMS': '0',
'navigation-MAX_NUM_FORMS': '1',
},
follow=True,
)
self.client.logout()
def setUp(self):
User.objects.create_superuser('admin', '[email protected]', 'Password123')
def test_route_created_with_page(self):
"""
When a page is created, a route should always be created also.
"""
page_title = 'Test'
page_content = 'This is the test page.'
self.create_page(
title=page_title,
content=page_content,
)
route = Route.objects.filter(pk=1).exists()
self.assertTrue(route)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With