开发者

Django: how do I include the same field multiple times in a Django form?

I've got a basic friend invite form in my Django app that looks like this:

class FriendInviteForm(forms.Form):
    email = forms.EmailField()

It works perfectly when a user is inviting a single person, but I'd like to allow the user to invite as many of their friends as they'd like. The implementation I am trying to build would be to display the form with 3 email fields, and allow the user to开发者_Go百科 dynamically add more fields on the client side using jQuery.

What is the best way to handle the creation of such a form, and how would I process the email fields in my view? Can I still use Django's built in forms for this?

Thanks!


I think formsets does not help here much because the OP wants to have a single form. I would just make a form with a multiline text field, ask the user to enter one email per line, or separate them by semicolons, and parse emails from there when the form is submitted.

If you do need to have separate fields I would look into array fields. I myself have not done this, but for example, here is a similar question: Django equivalent of PHP's form value array/associative array

or maybe this one is even better: Django: create HTML input array using a django form


Why not to use Django formsets as mentioned above? You can define extra Email fields like this:

email_formset = formset_factory(EmailForm, extra=2)
group_name_form = GroupNameForm()  # Additional form for usefull data.

Then use it in your template with additional form:

<form action="" method="post">
    {% csrf_token %}

    {{ group_name_form.as_p }}

    {{ email_formset.as_p }}

    <input type="submit" value="Send Invites"> <!-- Single Submit button -->
</form>

And finaly, when in your views.py you can handle both forms like:

def view(request):
    if request.method == 'POST':
        email_formset = formset_factory(EmailForm, extra=2)
        email_formset = email_formset(request.POST)
        group_name_form = GroupNameForm(request.POST)

        # And validate both forms if needed.
        if email_formset.is_valid() and group_name_form.is_valid():
            # Do something with cleaned_data.
            group_name_form.cleaned_data['something']
            for form_data in email_formset.cleaned_data:
                print form_data

So this way you will have one submit button, one HTML form but two django form representations. What to do with them - only your choice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜