ashes999
ashes999

Reputation: 1324

Django get modelformset_factory input field ID's in html template

I am trying to get the input ids for my forms in an HTML template in order to write a javascript code to trigger the input field from as you click on a div. I am trying to print the id of every input field in the template however right now my code is not showing anything on the page:

in my **template I currently have:**

    {% for form in formset %}
        {% for field in form.fields %}
            {{ field.auto_id }}
        {% endfor %}
    {% endfor %} 

And this is my view:

@login_required
def post_create(request):
    data = dict()
    ImageFormset = modelformset_factory(Images,form=ImageForm,extra=4)
    if request.method == 'POST':
        form = PostForm(request.POST)
        formset = ImageFormset(request.POST or None, request.FILES or None)
        if form.is_valid():    
            post = form.save(False)
            post.author = request.user
            #post.likes = None
            post.save()
            for f in formset:
                try:
                    i = Images(posts=post, image=f.cleaned_data['image'])
                    i.save()
                except Exception as e:
                    break
            data['form_is_valid'] = True
            posts = Post.objects.all()
            posts = Post.objects.order_by('-last_edited')
            data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request)
        else:
            data['form_is_valid'] = False
    else:
        form = PostForm  
        formset = ImageFormset(queryset=Images.objects.none())     
    context = {
    'form':form,
    'formset':formset,
    }
    data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request)
    return JsonResponse(data) 

I was wondering if this is the best way to do this, however, is there any way to get the ID of the fields dynamically? or should I write separate functions for each div that will trigger a specific input field?

Thanks in advance!

Upvotes: 0

Views: 310

Answers (1)

ashes999
ashes999

Reputation: 1324

SOLVED:

so apparently i was using the incorrect loop the id of my field can be aquired using:

    {% for form in formset %}
        {{ form.image.auto_id }}
    {% endfor %}

Upvotes: 0

Related Questions