I have a template that creates a text entry field and a checkbox. When the checkbox is unchecked, the text field is disabled and cleared, when it's checked, it's enabled, and the user may or may not have typed in it. In my controller I need to distinguish between the 2 cases when the checkbox is unchecked, and the checkbox is checked but the text field is blank. I can get the value of the text field, but not of the checkbox. Is there some way to do this? I've googled this, and I see it's been asked a few times here, but noneof the solutions seem to work for me.
-
1Please show some code. Showing if a checkbox is checked is a fairly basic forms task.Daniel Roseman– Daniel Roseman2012-05-02 14:00:27 +00:00Commented May 2, 2012 at 14:00
-
1Code would be nice. Also consider using the Django Debug Toolbar. If this is a jQuery (or other JS) related situation, Firebug is your friend.Peter Rowell– Peter Rowell2012-05-02 14:07:20 +00:00Commented May 2, 2012 at 14:07
-
Perhaps my question isn't clear. I am not having any problems creating the checkbox, nor getting its state in my jQuery code. I need to get its state back in my python controller.Larry Martell– Larry Martell2012-05-02 14:20:51 +00:00Commented May 2, 2012 at 14:20
-
No, your question is perfectly clear. It's impossible to answer it though, because you still haven't shown any code.Daniel Roseman– Daniel Roseman2012-05-02 14:48:00 +00:00Commented May 2, 2012 at 14:48
-
It's part of a very large, complex app. There's no simple, minimal example I can post.Larry Martell– Larry Martell2012-05-02 15:15:58 +00:00Commented May 2, 2012 at 15:15
2 Answers
request.POST.get('my_checkbox_field')
P.S. In Django, they're called "views" not controllers.
UPDATE (based on comment)
I'm taking "controller" to mean "view" since Django doesn't have a concept of controllers and they're closest to views. If that's not the case, by all means correct me. Given that, all function-based views at the very least require a request parameter. If you're using class-based views, then request is simply stored on the view object, so you just need to modify it to self.request. I suggest you take some more time to thoroughly read the docs, as this is pretty much bare minimal understanding stuff that is well documented.
7 Comments
MeasurementData sounds like a model. Make sure your "view" is truly a subclass of View or one of its subclasses (DetailView, ListView, etc.)Are you looking for this?
def myview(request):
form = MyForm()
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
checkbox = request.POST.get('my_checkbox', False) # will be True if checked
if checkbox:
# check textfield content
else:
# do something else
return render_to_response(template, kwvars, context_instance=RequestContext(request))