Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide a primary key field in a Django form

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?

like image 485
Fred Larson Avatar asked Jan 09 '09 03:01

Fred Larson


1 Answers

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:

from django.shortcuts import render_to_response, get_object_or_404
from models import MyModel

def edit(request, my_id):
    obj = get_object_or_404(MyModel, 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))
like image 110
Daniel Naab Avatar answered Sep 20 '22 16:09

Daniel Naab