views:

1158

answers:

2

I'd prefer my primary key field weren't visible in my edit page. If I make it an AutoField, it isn't rendered in the HTML form. But then the primary key value isn't in my POST data either. Is there a simple way to render the AutoField as a hidden field?

+2  A: 

you could specify its widget as a hidden field

bchhun
+3  A: 

If you don't intend your user to be able to change something on a form, then you should instead place it in the URL or some other context. You're opening yourself up to security issues (or at least extra use cases) otherwise.

In the urls.py:

(r'^edit/?P<my_id>[\d]+)/$', views.edit),

and in view.py:

def edit(request, my_id):
    obj = MyModel.objects.get(id=my_id)
    if request.POST:
        form = MyForm(request.POST, instance=obj)
        if form.is_valid():
            form.save()
            #
            # do other stuff....
            #
    else:
        form = MyForm(instance=obj)

    return render_to_response(template_name, {
        "form": form
    }, context_instance=RequestContext(request))
Daniel
I like what you did here. do you have thoughts on how to hide multiple fields in the rendered HTML form? I have a feeling I need to switch to using formsets (or stop using ModelForms) to get the granularity I want :/
neoice
Well, if they're all values that the user can't change, they can also go in the url: `(r'^edit/?P<my_id>[\d]+)/?P<my_field>[.]+/$', views.edit)`. Otherwise, in ModelForms set each field's widget to HiddenInput (or set the existing widget's display style to `none`.)
Daniel
What would you do if the form is creating the instance of the model?
Anthony
Not sure what you mean - can you clarify?
Daniel