R
R
Roman no_name2014-04-10 12:09:00
Django
Roman no_name, 2014-04-10 12:09:00

How to pass initial to form?

Faced such a problem. I want to send a message with the choice of a user who is friends.
Based on django 1.4 and CouchDB base. In the view I have the following:

def send_msg(request):
    if request.method == 'POST':
        form = Send_Msg_User(request.POST)
        if form.is_valid():
            friend_id = form.cleaned_data['selection']
            user_id = request.user._id
            msg = form.cleaned_data['msg']
            doc_id = uuid4().hex
            time = datetime.datetime.now()
            time = time.strftime('%Y-%m-%d %H:%M:%S')
            type_doc = "msg"
            status = "new"
            django_couch.db('msgdb')[doc_id] = {'type': type_doc, 'from': user_id, 'to': friend_id, 'time': time, 'status': status}
    else:
        user_id = request.user._id
        friends = django_couch.db().view('list/friends', include_docs=True, key=user_id).rows
        documents = [row.doc for row in friends]
        for row in documents:
            print row.id, row.first_name, row.last_name
        form = Send_Msg()
    return render_to_response('send_msg.tpl', {'form': form})

I need to pass the array documents = [row.doc for row in friends]to the form. How can this be done?
My form code is like this:
class Send_Msg(forms.Form):
    selection = forms.MultipleChoiceField(choices=(
    ))
    post = forms.CharField(min_length=10, widget=forms.Textarea(attrs={'width': "100%", 'cols': "70", 'rows': "20", }),
                           label="Ваше сообщение")

I need to get an array into a form and set the Choices.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Shikanov, 2014-04-10
@dizballanze

Overload __init__ method.

R
Roman no_name, 2014-04-10
@Romastr

Solved in this way:

class Send_Msg(forms.Form):
    def __init__(self, documents, *args, **kwargs):
        row = [(row.id, row.first_name+' '+row.first_name) for row in documents]
        super(Send_Msg, self).__init__(*args, **kwargs)
        self.fields['friends'] = forms.MultipleChoiceField(choices=row)
        self.fields['msg'] = forms.CharField(min_length=10, widget=forms.Textarea(attrs={'width': "100%", 'cols': "70", 'rows': "20", }),
                                             label="Ваше сообщение")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question