views:

4155

answers:

3

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!

+5  A: 

To have a default Foreign Key in a model:

mydefault = Type.objects.get(pk=3)

class P(models.Model):
   type = models.ForeignKey(Type, default=mydefault) # Type is another models.Model class
   name = models.CharField()

Note that using pk=x is pretty ugly, as ideally you shouldn't care what the primary key is equal to. Try to get to the object you want by some other attribute.

Here's how you put defaults in your urls:

# URLconf
urlpatterns = patterns('',
    (r'^blog/$', 'blog.views.page'),
    (r'^blog/page(?P<num>\d+)/$', 'blog.views.page'),
)

# View (in blog/views.py)
def page(request, num="1"):
    # Output the appropriate page of blog entries, according to num.

In the above example, both URL patterns point to the same view -- blog.views.page -- but the first pattern doesn't capture anything from the URL. If the first pattern matches, the page() function will use its default argument for num, "1". If the second pattern matches, page() will use whatever num value was captured by the regex.

Harley
+5  A: 

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.

Daniel
+2  A: 

If you go with Andrew's approach of including the hidden value in the url and still want to use one of Django's built in form templates, there are ways for you to exclude the hidden field.

http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form

surtyaar