我正在使用自定义表单(不是ModelForm),我正在尝试将其很好地插入到django界面中。问题是表单的布局与“常规管理表单”不同,我无法使小部件工作。
我正在使用:
现在我正确显示了所显示的表单,但它没有被排版,因为另一个表单将是自动完成小部件无法正常工作
这是我的模板代码:
{% extends "admin/change_form.html" %}
{% block field_sets %}
{{ form }}
{% endblock %}
admin.py文件:
class UsersInEventAdmin(ExportMixin):
list_display = ('user', 'event', 'options_selected', 'payed', 'user_phone',
'user_email', 'user_have_certificate')
list_filter = ('event__name', 'payed')
search_fields = ["^event__name",
"^user__user__first_name",
"^user__user__last_name"]
ordering = ["event__name", "user__user__last_name",
"user__user__first_name"]
form = SportifInEventAdminForm
# Extend for prefilled forms
def get_urls(self):
urls = super(UsersInEventAdmin, self).get_urls()
my_urls = [
url(r'^([0-9]+)/foo/$',
self.admin_site.admin_view(self.event_registration_form))
]
return my_urls + urls
def event_registration_form(self, request, event):
# Populate the options for the event
options = [
dict(description=e.description,
choices=[(-1, 'Aucun')]+[
(c.id, c.description)
for c in EventOptionChoice.objects.filter(option=e)
])
for e in EventOption.objects.filter(event_id=event)]
# Parse the request
if request.method == 'POST':
print('Got a form!')
form = UserInEventGenericForm(request.POST, event_options=options)
if form.is_valid():
# Save the form
# TODO
# Return the form once again
form = UserInEventGenericForm(event_options=options)
else:
print('creating new form')
form = UserInEventGenericForm(event_options=options)
request.form = form
# import pdb; pdb.set_trace()
data = {
'form': form,
'opts': self.model._meta,
'change': False,
'is_popup': False,
'save_as': False,
'has_delete_permission': True,
'has_add_permission': False,
'has_change_permission': False
}
return render(request,
"admin/event_registration_form.html",
data,
context_instance=RequestContext(request))
和我的forms.py:
class UserInEventGenericForm(forms.Form):
'''Dynamically generate a form for given set of questions'''
user = forms.CharField(label='User',
widget=AutoCompleteSelectWidget(SportifLookup),
required=True)
def __init__(self, *args, **kwargs):
if "event_options" in kwargs:
options = kwargs.pop('event_options')
else:
options = []
super(UserInEventGenericForm, self).__init__(*args, **kwargs)
self.fields['user'].widget = AutoCompleteSelectWidget(
lookup_class=SportifLookup)
for i, option in enumerate(options):
self.fields['option_%s' % i] = forms.ChoiceField(
choices=option['choices'],
label=option['description'])