当我在django admin中保存模型时,我需要一种显示中间页面的方法。
我想要完成的是在“保存”模型之后,显示一个页面,其中列出了模型的所有属性,然后有一个显示Print
的按钮。单击save
时,我曾经使用Jquery对话框div来解决这个问题。这意味着我在实际保存模型之前显示了设置打印视图,但我现在需要模型首先验证。
它就像“删除模型”操作的实现方式一样。我似乎无法找到从哪里开始寻找。
修改
我开始在django.contrib.admin.options.py
查找response_change
和response_add
方法。不知道如何覆盖它们。它只需要一个特定的模型,因此它不是通用的。我还发现了类ModelAdmin中的模板列表。仍然不确定如何在不破坏管理员的情况下继续进行。
编辑2: 在下面添加了我的工作解决方案。
答案 0 :(得分:5)
您可以创建一个表单,对“您确定”步骤进行额外的验证步骤。
在models.py中给出了这个模型:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=100)
在forms.py中添加表单:
from django import forms
from .models import Person
class PersonForm(forms.ModelForm):
i_am_sure = forms.BooleanField(required=False, widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
super(PersonForm, self).__init__(*args, **kwargs)
if self.errors.get('i_am_sure'):
# show the 'are you sure' checkbox when we want confirmation
self.fields['i_am_sure'].widget = forms.CheckboxInput()
def clean(self):
cleaned_data = super(PersonForm, self).clean()
if not self.errors:
# only validate i_am_sure once all other validation has passed
i_am_sure = cleaned_data.get('i_am_sure')
if self.instance.id and not i_am_sure:
self._errors['i_am_sure'] = self.error_class(["Are you sure you want to change this person?"])
del cleaned_data['i_am_sure']
return cleaned_data
class Meta:
model = Person
如果你想在Django admin中使用它。在admin.py中指定此表单:
from django.contrib import admin
from .forms import PersonForm
from .models import Person
class PersonAdmin(admin.ModelAdmin):
form = PersonForm
admin.site.register(Person, PersonAdmin)
但请注意,Django管理表单上存在隐藏输入的错误。 There's a solution to that on this Stack Overflow question
答案 1 :(得分:2)
您可以向ModelAdmin添加视图和网址,并覆盖您的modeladmin添加视图以进行相应的重定向。
class MyModelAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super(MyModelAdmin, self).get_urls()
my_urls = patterns('',
(r'^my_view/$', self.my_view)
)
return my_urls + urls
def my_view(self, request):
# custom view which should return an HttpResponse
pass
答案 2 :(得分:0)
所以,经过一些编码后我就开始工作了。
我的modeladmin现在看起来像这样
class MyModelAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super(MyModelAdmin, self).get_urls()
my_urls = patterns('',
(r'^my_view/$', self.my_view)
)
return my_urls + urls
def my_view(self,request,pk):
from django.shortcuts import render_to_response
from django.template import RequestContext
object = Model.objects.get(pk=pk)
model_dict = model_object.__dict__
return render_to_response('admin/app_name/model/model_view.html',locals(),context_instance=RequestContext(request))
@csrf_protect_m
@transaction.commit_on_success
def add_view(self, request, form_url='', extra_context=None):
"The 'add' admin view for this model."
model = self.model
opts = model._meta
if not self.has_add_permission(request):
raise PermissionDenied
ModelForm = self.get_form(request)
formsets = []
inline_instances = self.get_inline_instances(request)
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES)
if form.is_valid():
new_object = self.save_form(request, form, change=False)
form_validated = True
else:
form_validated = False
new_object = self.model()
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(data=request.POST, files=request.FILES,
instance=new_object,
save_as_new="_saveasnew" in request.POST,
prefix=prefix, queryset=inline.queryset(request))
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, False)
self.save_related(request, form, formsets, False)
self.log_addition(request, new_object)
log.info('The new object has %s id' % new_object.id)
return HttpResponseRedirect('/admin/draws/contest/contest_view/%s' % new_object.id) <-- changed to my new one
.................
.................
在templates/admin/app_name/model_view.html
中创建了一个html模板,就是这样!