KennyPowers
KennyPowers

Reputation: 5015

Add custom view to Django admin

I'm trying to get custom view working in Django admin. I have the next model:

class Reseller(models.Model):
    first_name = models.CharField(max_length=64, verbose_name='First Name')
    last_name = models.CharField(max_length=64, verbose_name='Last Name')
    email = models.CharField(max_length=64, verbose_name='E-mail')
    password = models.CharField(max_length=64, blank=True, editable=False)

This is how I added a custom button (reset password). Custom view (extends change_form.html) I have for this:

{% extends "admin/change_form.html" %}

{% load i18n %}

{% block object-tools %}
{% if change %}
  <ul class="object-tools">
  <li><a href="reset_password/">Reset Password</a></li>
  </ul>

{% endif %}
{% endblock %}

That's what I have in admin.py

from django.conf.urls.defaults import patterns
from django.contrib import admin
from django.shortcuts import redirect
from django.shortcuts import render_to_response
from django.template import RequestContext

from myapp.resellers.models import Reseller

class ResellerAdmin(admin.ModelAdmin):
    list_display = ('id', 'first_name', 'last_name', 'email')
    list_filter = ('email')
    search_fields = ('first_name', 'last_name', 'email')
    ordering = ['-id', ]

    def get_urls(self):
        urls = super(ResellerAdmin, self).get_urls()
        my_urls = patterns('',
                           (r'(?P<id>\d+)/reset_password/$',
                            self.admin_site.admin_view(self.reset_password)),
                        )
        return my_urls + urls

    def reset_password(self, request, id):
        entry = Reseller.objects.get(pk=id)
        [...GENERATE AND SEND PASSWORD FUNCTION GOES HERE...]
        return redirect(entry)


admin.site.register(Reseller, ResellerAdmin)

When I run this code I get the next: `argument of type 'Reseller' is not iterable.

Upvotes: 2

Views: 2211

Answers (1)

thikonom
thikonom

Reputation: 4267

If you only pass the model as an argument to redirect then the models get_absolute_url() method will be called, which you presumably have not defined (see docs).
So go ahead and add a get_absolute_url() method to your Reseller class.

Upvotes: 2

Related Questions