Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 872
Brian M. Hunt Avatar asked Nov 07 '08 04:11

Brian M. Hunt


People also ask

What does {% mean in django?

{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What is form AS_P in django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.

What is get and post method in django?

GET and POSTDjango's login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET , by contrast, bundles the submitted data into a string, and uses this to compose a URL.


1 Answers

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.

like image 99
Daniel Naab Avatar answered Oct 02 '22 09:10

Daniel Naab