How does one add default (hidden) values to form templates in Django?

django, django-templates, django-urls, python

Solution

The widget `django.forms.widgets.HiddenInput` will render your field as hidden.

In most cases, I think you'll find that any hidden form value could also be specified as a url parameter instead. In other words:

<form action="new/{{your_hidden_value}}" method="post">
....
</form>

and in urls.py:

^/new/(?P<hidden_value>\w+)/

I prefer this technique myself because I only really find myself needing hidden form fields when I need to track the primary key of a model instance - in which case an "edit/pkey" url serves the purposes of both initiating the edit/returning the form, and receiving the POST on save.

Problem

Given a Django.db models class: ``` class P(models.Model): type = models.ForeignKey(Type) # Type is another models.Model class name = models.CharField() ``` where one wishes to create a new P with a specified type, i.e. how does one make "type" to be a default, hidden field (from the user), where type is given likeso: ``` http://x.y/P/new?type=3 ``` So that in the form no "type" field will appear, but when the P is saved, its type will have id 3 (i.e. Type.objects.get(pk=3)). Secondarily, how does one (& is it possible) specify a "default" type in the url, via urls.py, when using generic Django views, viz. ``` urlpatterns = ('django.generic.views.create_update', url(r'^/new$', 'create_object', { 'model': P }, name='new_P'), ) ``` I found that terribly difficult to describe, which may be part of the problem. :) Input is much appreciated!

Original source