Как в python-django реализовать выбор users = User.objects.all() в шаблоне /compose.html, таким образом <form><select>{{ users }}</select></form>
Distributor ID: Debian
Description: Debian GNU/Linux 6.0.6 (squeeze)
Release: 6.0.6
Codename: squeeze
Python 2.6.6
django.VERSION
(1, 2, 3, 'final', 0)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/fields.py
....
class CommaSeparatedUserInput(widgets.Input):
input_type = 'text'
def render(self, name, value, attrs=None):
if value is None:
value = ''
elif isinstance(value, (list, tuple)):
value = (', '.join([user.username for user in value]))
return super(CommaSeparatedUserInput, self).render(name, value, attrs)
class CommaSeparatedUserField(forms.Field):
widget = CommaSeparatedUserInput
def __init__(self, *args, **kwargs):
recipient_filter = kwargs.pop('recipient_filter', None)
self._recipient_filter = recipient_filter
super(CommaSeparatedUserField, self).__init__(*args, **kwargs)
....
/forms.py
class ComposeForm(forms.Form):
"""
A simple default form for private messages.
"""
recipient = CommaSeparatedUserField(label=_(u"Recipient"))
...
/models.py
class Message(models.Model):
"""
A private message from user to user
"""
...
recipient = models.ForeignKey(User, related_name='received_messages', null=True, blank=True, verbose_name=_("Recipient"))
...
/compose.html
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="{% trans "Send" %} »"/>
</form>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Примечание:
/views.py
def compose(request, recipient=None, form_class=ComposeForm,
template_name='django_messages/compose.html', success_url=None, recipient_filter=None):
"""
Displays and handles the ``form_class`` form to compose new messages.
Required Arguments: None
Optional Arguments:
``recipient``: username of a `django.contrib.auth` User, who should
receive the message, optionally multiple usernames
could be separated by a '+'
``form_class``: the form-class to use
``template_name``: the template to use
``success_url``: where to redirect after successfull submission
"""
if request.method == "POST":
sender = request.user
form = form_class(request.POST, recipient_filter=recipient_filter)
if form.is_valid():
form.save(sender=request.user)
messages.info(request, _(u"Message successfully sent."))
if success_url is None:
success_url = reverse('messages_inbox')
if request.GET.has_key('next'):
success_url = request.GET['next']
return HttpResponseRedirect(success_url)
else:
form = form_class()
if recipient is not None:
recipients = [u for u in User.objects.filter(username__in=[r.strip() for r in recipient.split('+')])]
form.fields['recipient'].initial = recipients
return render_to_response(template_name, {
'form': form,
}, context_instance=RequestContext(request))
compose = login_required(compose)