Deepak Bartwal
Deepak Bartwal

Reputation: 25

Changing Id of django form in for loop

I'm stuck in my code. Need help.

This is my front end. I am rendering forms stored in "form_list". The problem is that the forms stored are of same type and thus produce input fields with same "id" and same "name".

This is my view:-

@login_required
def VideoLinkView(request):
    """view to save the video links """
    current_form_list = []
    current_form = None
    if request.method == 'GET':
        vl = VideoLink.objects.filter(company=CompanyModel.objects.get(owner=request.user))
        for link in vl:
            current_form = VideoLinkForm(link.__dict__)
            current_form_list.append(current_form)
        return render(request, "premium/video_link.html", context={'form_list':current_form_list})

This is my html template :-

{% for form in form_list %}
    <div class="form-group">
        <label for="id_video_link">Video Link:</label>
        {{ form.video_link }}
    </div>
{% endfor %}

How can I create different "id" and different "name" in each iteration of for loop's input tag, automatically without having knowledge of no form stored in form_list. I tried {{ forloop.counter}} it didn't worked, perhaps I made some mistake. Also, raw python don't work in template.

Thanks in Advance.

Upvotes: 1

Views: 1003

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599470

The way you are creating your forms is wrong in two ways. Firstly, the first positional argument is for the values submitted by the user; passing this arg triggers validation, among other things. If you are passing values for display to prepopulate the form, you must use the initial kwarg:

current_form = VideoLinkForm(initial={...dict_of_values...})

However, even that is not correct for your use case here. link is a model instance; you should use the instance kwarg:

current_form = VideoLinkForm(instance=link)

Now, to solve the problem you asked, you could just pass a prefix as well as I originally recommended:

for i, link in enumerate(vl):
    current_form = VideoLinkForm(instance=link, prefix="link{}".format(i))

However, now that you have shown all the details, we can see that this is not the best approach. You have a queryset; so you should simply use a model formset.

from django.forms import modelformset_factory
VideoLinkFormSet = modelformset_factory(VideoLink, form=VideoLinkForm, queryset=vl)
current_form_list = VideoLinkFormSet()

Upvotes: 1

Related Questions