我对这个任务有点困惑:
我有 2 个表:用户,代码
我想以特定模式生成随机代码。我已经把那部分写成一个函数,但是在 ModelAdmin 中很难实现这个函数。
因此,如果有人知道实现此目的的技巧,我将非常高兴。在用户表单中有一个按钮来调用函数就足够了,然后它会创建这些代码。
但是我该如何实现这样的按钮呢?有没有办法解决这个问题?
编辑:错字
解决方案: 由于我想为特定用户生成凭证,我可以像这样编辑admin.py:
class MyUserAdmin(UserAdmin):
def vouchers(self, obj):
return "<a href='%s'>Generate vouchers</a>" % reverse(gen_voucher_view, kwargs={'user':obj.pk,})
vouchers.allow_tags = True
list_display = (..., 'vouchers')
它代表我的用户模型的管理视图中的可点击链接。
现在我通过添加将链接连接到urls.py中的视图
url(r'admin/gen_vouchers/(?P<user>\w+)/$', gen_voucher_view, name='gen_voucher_view')
到 urlpatterns。
为了创建凭证,我在forms.py中提供了一个表格
class VoucherGeneratorForm(forms.Form):
user = forms.CharField(User, required=True, widget=forms.HiddenInput())
amount = forms.IntegerField(min_value=0, max_value=500, required=True)
readonly = ('user', )
在views.py中,我添加了我的视图函数:
@login_required
def gen_voucher_view(request, user):
if request.method == 'POST': # If the form has been submitted...
form = VoucherGeneratorForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# GENERATE vouchers here by using form.cleaned_data['amount']
# and user (generate_vouchers is a self defined function)
vouchers = generate_vouchers(user, form.cleaned_data['amount']
# set error or info message
if len(vouchers) == form.cleaned_data['amount']:
messages.info(request, "Successfully generated %d voucher codes for %s" % (form.cleaned_data['amount'], user))
else:
messages.error(request, "Something went wrong")
u = User.objects.get(pk=user)
form = VoucherGeneratorForm(initial={'user':user}) # An unbound form
return render_to_response('admin/codes.html', {'request': request, 'user':user, 'form':form, 'userobj': u}, context_instance=RequestContext(request))
else:
form = VoucherGeneratorForm(initial={'user':user}) # An unbound form
最后但并非最不重要的一点是创建一个模板admin/codes.html显示我的表单:
{% extends "admin/base_site.html" %}
{% load i18n admin_static static %}
{% block breadcrumbs %}
<div class="breadcrumbs">
<a href="{% url 'admin:index' %}">{% trans 'Home' %}</a>
›
<a href="{% url 'admin:admin_user_changelist' %}">{% trans 'Users' %}</a>
›
<a href="{% url 'admin:admin_vouchercode_changelist' %}">{% trans 'Vouchercodes' %}</a>
›
Voucher Generator
</div>
{% endblock %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}" />{% endblock %}
{% block content %}
<div id="content-main">
{% if request.user.is_active and request.user.is_staff or userobj and userobj.is_active and userobj.is_staff %}
<h1 id="generator_title">Generate vouchers for {{user}}</h1>
<form id="formular_generator" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<table>{{ form }}</table>
<button id="generatebutton" type="submit" name="action" value="generate">Generate</input>
</form>
{% else %}
<p>{% trans "You don't have permission to access this site." %}</p>
</div>
{% endif %}
{% endblock %}
{% block sidebar %}
{% endblock %}
完毕!
为了将它们导出为 pdf,我使用了管理操作,如下面的 Sumeet Dhariwal 所建议的那样。