[Django]-How do I populate a hidden required field in django forms?

1👍

I was able to do something like this in the template and that worked!

<input type="hidden" name="queue" value="9" />
👤DeA

3👍

You can use formsets to be able to assign a specific value and show specific inputs to the user like this

2👍

I just did this last night!

In forms.py declare the field with the HiddenInput widget (be sure to render it):

scope = CharField(max_length=60,widget=HiddenInput())

Then, in views.py you can apply the initial value:

form = MyForm(initial={'scope': 'public'})

Or using a CBV:

initial = {'scope':'public'}

1👍

Don’t make a hidden field. Create another form class that doesn’t contain the field (subclassing will prevent repetition), then set the value in the view.

instance = form.save(commit=False)
instance.queue = 9
instance.save()

1👍

You can override POST data.

if request.method in ('POST', 'PUT'):
    data = request.POST.copy()
    data['queue'] = 9
    form = PublicTicketForm(data, request.FILES)

1👍

I needed to have a page which populate using GET args but not display the input fields (to prevent users to accidentally change the config of the objects), so I did this in my admin.py:

from django.contrib import admin
from django.forms import HiddenInput

from .models import SimpleNote

class SimpleNoteAdmin(admin.ModelAdmin):
    list_display = ("id",)

    def get_form(self, request, obj=None, change=False, **kwargs):
        form = super(SimpleNoteAdmin, self).get_form(request, obj, change, **kwargs)
        form.base_fields['content_type'].widget = HiddenInput()
        form.base_fields['object_id'].widget = HiddenInput()
        if "content_type" in request.GET and "object_id" in request.GET:  # simple note does not exist, so we must create it using GET parameters
            form.base_fields['object_id'].initial = request.GET['object_id']
            form.base_fields['content_type'].initial = request.GET['content_type']
        return form

admin.site.register(SimpleNote, SimpleNoteAdmin)

Leave a comment