django-admin:如何在一个Object保存后重定向到URL?

时间:2017-11-05 21:46:23

标签: python django django-admin

创建用户后,我正在使用Django Signals触发代码我在另一个模型类上保存了其他数据,它被触发但它没有重定向到其他数据对象页面。

这是我的models.py

from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class Customers(models.Model):
    user = models.OneToOneField(User)
    business_name = models.CharField(max_length=250)
    address = models.CharField(max_length=500)
    area = models.CharField(max_length=250)
    city = models.CharField(max_length=250)
    state = models.CharField(max_length=250)
    pincode = models.IntegerField(default='0')
    phone = models.IntegerField(default='0')
    mobile = models.IntegerField(default='0')

    def create_customer(sender, **kwargs):
        if kwargs['created']:
            customer_profile = Customers.objects.create(user=kwargs['instance'])

    post_save.connect(create_customer, sender=User)

这是我的admin.py

from django.contrib import admin
from .models import Customers
from django.shortcuts import redirect

admin.site.register(Customers)

class Customers(admin.ModelAdmin):
    def response_add(self, request, obj, post_url_continue=None):
        return redirect('/admin/app/customers/add/')

    def response_change(request, obj):
        return redirect('/admin/app/customers/add/')

厌倦了寻找答案,但没有任何效果,请在此纠正我。

1 个答案:

答案 0 :(得分:1)

看起来您正在注册管理员配置。有关更多信息,请参阅Django docs on the register decorator。语法是用@admin.register(<model>)装饰你的函数,或者如果你想手动注册模型管理配置,那么admin.site.register(<model>, <model admin>)

我建议将class Customers(admin.ModelAdmin):更改为class CustomersAdmin(admin.ModelAdmin):或类似内容以停止命名空间冲突。

见下面的例子:

from django.contrib import admin
from .models import Customers
from django.shortcuts import redirect


@admin.register(Customers)
class CustomersAdmin(admin.ModelAdmin):
    def response_add(self, request, obj, post_url_continue=None):
        return redirect('/admin/app/customers/add/')

    def response_change(request, obj):
        return redirect('/admin/app/customers/add/')