Reading Dynamic Checkbox in Django

2015-04-28 Thread Ken Nguyen
Hi Folks,

First time posting on here so if I violate any laws, please forgive me.  I 
also posted the same question 
on 
StackOverflow but didn't get any answers so I'm hoping this place will get 
more attention.

I'm having a hard time reading whether the checkbox is checked or not.  I 
created a formset with just the first_name and last_name since my initial 
page is only asking for those 2 information.  Once entered and validated, 
the next page will show a checkbox next to the duplicate names.

Here are the things that I've tried:

   - Changed the checkbox's name to iterate with the for-loop for 
   uniqueness.  (Regardless if I check the box or not, the results are always 
   the same {'overwrite': False}.)
   - Added the Boolean value with the first_name & last_name formset 
   (Result - 'ManagementForm data is missing or has been tampered with')

I think the problem lies with obtaining the 'POST' data.  Any help is much 
appreciated.


*Step 1*




*Step 2*



*Step 3* *- Output Expectation*

John Doe Location A 1 ("1" is checked)

James Smith Location A 0 ("0" is not checked)


*forms.py*

from django import forms
from django.forms.formsets import BaseFormSet


class UserInfo (forms.Form):

first_name = forms.CharField (max_length = 20, required = False)
last_name = forms.CharField (max_length = 20, required = False)
overwrite = forms.BooleanField (required = False)


class BaseUserInfoFormSet (BaseFormSet):

def clean (self):
if any (self.errors):
return

firstnames = []
lastnames = []
errors = []

for form in self.forms:
firstname = form.cleaned_data.get ('first_name')
lastname = form.cleaned_data.get ('last_name')

if ((firstname in firstnames) or (lastname in lastnames)) and 
len (errors) < 2:
errors.append ('First and/or last name must be unique')
if ((firstname == '') or (lastname == '')) and len (errors) < 2:
errors.append ('First and/or last name cannot be blanked')

firstnames.append (firstname)
lastnames.append (lastname)

if errors:
raise forms.ValidationError (errors)

return self.cleaned_data


#class DuplicateForm (forms.Form):
#overwrite = forms.BooleanField (required = False)

*views.py*

from django.shortcuts import render, render_to_response
from django.forms.formsets import formset_factory
from userinfo.forms import UserInfo
from userinfo.forms import BaseUserInfoFormSet
from userinfo.addName import webform


# Create your views here.
def addname (request):
UserInfoSet = formset_factory (UserInfo, formset = BaseUserInfoFormSet, 
extra = 2, max_num = 3)
if request.method == 'POST':
formset = UserInfoSet (request.POST)

if formset.is_valid ():
location = request.POST ['site']
names = formset.cleaned_data

request.session ['location'] = location
request.session ['names'] = names

for name in names:
firstname = name.get ('first_name')
lastname = name.get ('last_name')

if firstname and lastname:
webform (firstname, lastname, location)

context = {'names': names, 'location': location}
return render (request, 'userinfo/response.html', context)

else:
formset = UserInfoSet ()

context = {
'formset': formset,
'first_name_0': request.POST.get ('form-0-first_name', ''),
'last_name_0': request.POST.get ('form-0-last_name', ''),
'first_name_1': request.POST.get ('form-1-first_name', ''),
'last_name_1': request.POST.get ('form-1-last_name', ''),
}

return render (request, 'userinfo/addname.html', context)


def response (request):
location = request.session ['location']
names = request.session ['names']

UserInfoSet = formset_factory (UserInfo, formset = BaseUserInfoFormSet, 
extra = 2, max_num = 3)
if request.method == 'POST':
formset = UserInfoSet (request.POST)

if formset.is_valid ():
data = formset.cleaned_data
for duplicate in data:
overwrite = duplicate.get ('overwrite')

#if request.method == 'POST':
#form = DuplicateForm (request.POST)

#if form.is_valid ():
#data = form.cleaned_data

#for duplicate in data:
#overwrite = duplicate.get ('overwrite')


context = {'names': names, 'location': location, 'data': data}
return render (request, 'userinfo/results.html', context)

return render_to_response ('No valid data.')


*addname.html*





Add Name


 

Django BooleanField Checkbox Returns Empty

2015-04-29 Thread Ken Nguyen
I read every corner of the documentation but couldn't figure out why the 
BooleanField Form doesn't return 'True' when the checkbox is checked. Is 
this a valid test? Shouldn't formset.cleaned_data = [{True}, {False}]?



>>> from django import forms
>>> from django.forms.formsets import formset_factory
>>>
>>> class CheckBox (forms.Form):
...overwrite = forms.BooleanField (required = False)
...
>>>
>>> data = {
... 'form-TOTAL_FORMS': '2',
... 'form-INITIAL_FORMS': '0',
... 'form-MAX_NUM_FORMS': '3',
... 'checkbox-0-overwrite': True,
... 'checkbox-1-overwrite': False,
...}
>>>
>>> CheckboxFormSet = formset_factory (CheckBox)
>>> formset = CheckboxFormSet (data)
>>> formset.is_valid ()
True
>>> formset.cleaned_data
[{}, {}]
>>>


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2fe2c1e6-5644-464e-8e35-36d22e5257b1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How to Process Multi Step Forms in Django?

2015-05-01 Thread Ken Nguyen


I've made some attempted to use formwizard but there wasn't much 
documentation about it so I decided to stay with the basic. I've 
successfully obtained and display the data from the first form to the 
second form and added some checkbox next to the data to allow user to 
choose whether to overwrite or ignore the duplicate data found in the 
backend process. The problem I have is the second form doesn't know how 
retrieve the data of the first form after hitting "Confirm" button. The 
form2.html template invalidated the data completely since it called itself 
again by the form action after submitting the data. Is there a way to solve 
this or a better approach to this?

*forms.py*

class NameForm (forms.Form): 
first_name = forms.CharField (required = False)
last_name = forms.CharField (required = False)

class CheckBox (forms.Form):
overwrite = forms.BooleanField (required = False)

views.py

def form1 (request):

NameFormSet = formset_factory (NameForm, formset = BaseNodeFormSet, extra = 
2, max_num = 5)

if request.method == 'POST':

name_formset = NameFormSet (request.POST, prefix = 'nameform')

if name_formset.is_valid ():
data = name_formset.cleaned_data

context = {'data': data}
return render (request, 'nameform/form2.html', context)
else:
name_formset = NameFormSet (prefix = 'nameform')

 context = {..}

 return render (request, 'nameform/form1.html', context)

def form2 (request):

CheckBoxFormSet = formset_factory (CheckBox, extra = 2, max_num = 5)

if request.method == 'POST':

checkbox_formset = CheckBoxFormSet (request.POST, prefix = 'checkbox')

if checkbox_formset.is_valid ():
data = checkbox_formset.cleaned_data

context = {'data': data}
return render (request, 'nameform/success.html', context)

else:
checkbox_formset = CheckBoxFormSet (prefix = 'checkbox')

 return HttpResponse ('No overwrite data.')



*form2.html*






{% load staticfiles %}

User Information


User Information:




First Name
Last Name
Overwrite

{% for info in data %}

{{ info.first_name }}
{{ info.last_address }}


{% endfor %}





Cancel




-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/27760adf-7d0d-4544-a645-72a7969c58a9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to Process Multi Step Forms in Django?

2015-05-04 Thread Ken Nguyen


Thank you for the input.  I've already tried what you've suggested but 
still the same result, "Management Form Data is Missing."  It's not going 
to know the "first_name" and "last_name" the second time around since I 
have the variable

{{ info.first_name }} and {{ info.last_name }}

My* form2.html* currently looking like so:

{% for info in data %}



{{ info.first_name }}
{{ info.last_name }}


{% endfor %}


When you say inherit from form1 and just add the checkboxes, can you 
elaborate that?  How do I inherit it?  Do you mean just replicate the first 
form and add checkboxes to it?

Thanks,

Ken


On Saturday, May 2, 2015 at 1:24:22 PM UTC-7, Bernardo Brik wrote:
>
> You should add the same fields (first_name and address) to form2 and 
> render them with hidden inputs.
> You can try to make form2 inherit from form1 and just add the checkbox.
>
> On Friday, May 1, 2015 at 9:58:28 PM UTC-3, Ken Nguyen wrote:
>>
>> I've made some attempted to use formwizard but there wasn't much 
>> documentation about it so I decided to stay with the basic. I've 
>> successfully obtained and display the data from the first form to the 
>> second form and added some checkbox next to the data to allow user to 
>> choose whether to overwrite or ignore the duplicate data found in the 
>> backend process. The problem I have is the second form doesn't know how 
>> retrieve the data of the first form after hitting "Confirm" button. The 
>> form2.html template invalidated the data completely since it called itself 
>> again by the form action after submitting the data. Is there a way to solve 
>> this or a better approach to this?
>>
>> *forms.py*
>>
>> class NameForm (forms.Form): 
>> first_name = forms.CharField (required = False)
>> last_name = forms.CharField (required = False)
>>
>> class CheckBox (forms.Form):
>> overwrite = forms.BooleanField (required = False)
>>
>> views.py
>>
>> def form1 (request):
>>
>> NameFormSet = formset_factory (NameForm, formset = BaseNodeFormSet, 
>> extra = 2, max_num = 5)
>>
>> if request.method == 'POST':
>>
>> name_formset = NameFormSet (request.POST, prefix = 'nameform')
>>
>> if name_formset.is_valid ():
>> data = name_formset.cleaned_data
>>
>> context = {'data': data}
>> return render (request, 'nameform/form2.html', context)
>> else:
>> name_formset = NameFormSet (prefix = 'nameform')
>>
>>  context = {..}
>>
>>  return render (request, 'nameform/form1.html', context)
>>
>> def form2 (request):
>>
>> CheckBoxFormSet = formset_factory (CheckBox, extra = 2, max_num = 5)
>>
>> if request.method == 'POST':
>>
>> checkbox_formset = CheckBoxFormSet (request.POST, prefix = 
>> 'checkbox')
>>
>> if checkbox_formset.is_valid ():
>> data = checkbox_formset.cleaned_data
>>
>> context = {'data': data}
>> return render (request, 'nameform/success.html', context)
>>
>> else:
>> checkbox_formset = CheckBoxFormSet (prefix = 'checkbox')
>>
>>  return HttpResponse ('No overwrite data.')
>>
>>
>>
>> *form2.html*
>>
>>
>> 
>> 
>> 
>> 
>> {% load staticfiles %}
>> 
>> User Information
>> 
>> 
>> User Information:
>> 
>> 
>> 
>> 
>> First Name
>> Last Name
>> Overwrite
>> 
>> {% for info in data %}
>> 
>> {{ info.first_name }}
>> {{ info.last_address }}
>> > value="1">
>> 
>> {% endfor %}
>> 
>> 
>> 
>> 
>> 
>> Cancel
>> 
>> 
>> 
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/797bdc71-28e4-4277-b645-7c0be9593b27%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to Process Multi Step Forms in Django?

2015-05-04 Thread Ken Nguyen
Hi Bernardo,

Using your hidden method works.  I can see the "hidden" value from Form2 
but how do I use those hidden information in form2 so it can redisplay 
correctly?  First time around, it will use the variable from form1.  The 
second time around it should use the hidden information without the 
variable.  How do I achieve that?

You are correct!  I cannot carry the information to the second method in 
view having it the way it is so I've added the session under the 
cleaned_data of form1 and retrieved it at the beginning of form2.

data = name_formset.cleaned_data
request.session ['location'] = location
request.session ['data'] = data

Step 1:  Form1 - Display First Name, Last Name, and location Input Field
Step 2:  Once user submit the information, render the data to form2 and add 
the checkbox next to it.
Step 3:  User choose to select the overwrite checkbox and then click 
"Confirm".
Step 4:  Form2 in view checked for 'POST' method and process cleaned data 
or return empty form2.  This stage created a "Management Form is Missing 
Error" because of the variables that I used in form1 to create the form2 
template are no longer there.  The {{ checkbox_formset.management_form }} 
is already in the template.

Here you can see that the names are displaying correctly.  By the way, I 
made an error in my original post.  It was supposed to be "last_name" not 
"last_address".




form2.html
form2.html




{% load staticfiles %}

User Information


User Information:

{{ checkbox_formset.management_form }}



First Name
Last Name
Overwrite

{% for info in data %}



{{ info.first_name }}
{{ info.last_name }}


{% endfor %}





Cancel







-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1ca19690-d44f-48e3-8755-d0530ac7fc03%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to Process Multi Step Forms in Django?

2015-05-04 Thread Ken Nguyen
Nevermind what I said on my last post, something is internally wrong with 
my second form.  It can't even render when I hard coded the first_name, 
last_name and the checkboxes.  Still getting Management Form Data is 
Missing.





{% load staticfiles %}

User Information


User Information:


{{ checkbox_formset.management_form }}




First Name
Last Name
Overwrite


John
Doe




John
Smith










Cancel





-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/37a2f383-72fd-4eb4-ad99-c482b80c5d9a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to Process Multi Step Forms in Django?

2015-05-05 Thread Ken Nguyen
I've finally figured it out after weeks of troubleshooting and here's how I 
do it.

In the original post, my views takes in the request from form1 and renders 
it to form2.  I would get the dreadful "Management Form Data is Missing" 
error no matter what I did and it led to asking a bunch of questions on 
here.  I decided to isolate the 2 forms to see if that rendered.  It took a 
few tries before getting both forms and templates to work separately.  What 
I noticed was form1.html's action was equal to "none" which was what I 
wanted.  It would render and posted the form with the errors to itself 
without redirecting to another page.  I then discovered that the address 
was still hooked to form1 instead of form2 after it had rendered.  In 
another word when form1 rendered the data to form2, the address was still 
on userinfo/form1.html when it should have been userinfo/form2.html in 
order for action to call the correct form in views.  The magic that I used 
to fix the issue was *HttpResponseRedirect*.  I saved the data retrieved 
from form 1 in a session and recovered it from beginning of form 2.  I used 
session to render data from form 2 instead of rendering directly from form 
1.

*Changes to form1 in views.py*

   - Save the data in a session for access in different part of views
   - Re-direct to form2 instead of render data from form1
   
def form1 (request):
...
if formset.is_valid ():
location = request.POST ['site']
data = formset.cleaned_data

request.session ['names'] = data

return HttpResponseRedirect ('form2')
...

*Changes to form2 in views.py*

   - Retrieve data from session
   - Do something with data from form2.   For my case, I merged both 
   dictionary into one.

def form2 (request):

data = request.session ['names']
...
if checkbox_formset.is_valid ():
for i, form in enumerate (checkbox_formset.cleaned_data):
data [i].update (form)  # This will give me a list of name 
dictionary with the checkbox appended
  
  context = {'data': data}
return render (request, 'userinfo/success.html', context)
else:
checkbox_formset = CheckBoxFormSet (prefix = 'checkbox')

 context = {'checkbox_formset': checkbox_formset, 'data': data, 
'location': location}
 return render (request, 'userinfo/form2.html', context)


*form2.html*





{% load staticfiles %}

Confirmation


Submitted Entries:
{% csrf_token %}

  
Firstname
Lastname
Location
Overwrite
Index
  
  {% for info in data %}
  
{{ info.first_name }}
{{ info.last_name }}
{{ location }}
{{ checkbox_formset.management_form }}


{{ forloop.counter0 }}
  
  {% endfor %}



Cancel





All there's left to do is create a template for success.html





Success


Submitted Entries:

{% for info in data %}
{{ info.first_name }} {{ info.last_name }} {{ 
info.overwrite }}
{% endfor %}

Add more names



Hope this will help some stragglers.  Nevertheless, thanks to Bernardo for 
helping me all along.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/df776fc2-c413-47ee-8703-11f530efffca%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to Process Multi Step Forms in Django?

2015-05-05 Thread Ken Nguyen
Hi Bernardo,

I appreciate the feedback.  I've heard of many ways to pass data between 
methods in views such as session, write to a file, or use formwizard.  It 
is still a problem accessing the session from the "cleaned_data"?  This is 
my first time hearing about query string, care to explain or giving me an 
example of how it works?  In the meantime, I'll read up on it.

Thanks,
Ken

P.S. - In some part of my code, you may notice the "location"parameter.  
You can ignore it or not include it in my code.  I was cut and paste so I 
didn't catch it. 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/181d8f1d-9728-400b-bac7-ddc205214dcc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.