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?
+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
2009-01-09 22:47:51
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
2009-02-15 21:04:16
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
2009-02-16 05:21:35
What would you do if the form is creating the instance of the model?
Anthony
2009-04-20 03:51:46
Not sure what you mean - can you clarify?
Daniel
2009-04-24 02:50:35