Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update form - using formsets - initial values unknown until runtime

Tags:

forms

django

I'm new to python and Django and have a simple question on how to update f form that has multiple fields of same type: I have been trying to do this with formsets:

I have a simple model to store categories:

class Category(BaseModel):
   categoryText = db.StringProperty()
   parentCat = db.IntegerProperty()

I want to create a form that would display all available categories in input fields so they could all be edited:

using formsets to display mulitple rows of the same type:

EDIT:

figured it out:

I had to create a list of dictionary items

categories = Category.objects.all()
initialStuff = []
oneFormV={}
for cat in categories:
    oneFormV.clear()
    oneFormV["categoryText"]=cat.categoryText
    oneFormV["parentCat"]=str(cat.parentCat)
    oneFormV["catID"]=str(cat.key().id())
    initialStuff.append(oneFormV.copy()) 


def showCategories(request):
    if request.POST:
       # code to update db
    else:
       categories = Category.objects.all()
       initialStuff = []
       for cat in categories:
         initialStuff += "'categoryText':u'" + cat.categoryText +"'," + "'parentCat':u'" + str(cat.parentCat) +"'," + "'catID':u'" + str(cat.key().id()) + "'"

       initialStuff =  initialStuff [:-1] # remove last comma
       CategoryFormSet = formset_factory(CategoryForm,extra=categories.count()) 
       formset = CategoryFormSet(initial= initialStuff )

       return render_to_response('adminCategories.html', {'formset': formset})

I am having problem with populating the initial data. When I generate in a loop it gives me errors :

class CategoryForm(forms.Form):
    categoryText = forms.CharField()
    parentCat = forms.CharField()
    catID = forms.CharField()

I am assuming I need to store the ID for the fields to update them!

Finally my question:

1) Am I doing this right or is there an easier way to accomplish this?

2) my problem has been passing initial values to a formset with initial values unknown until run time.

3) should I forget about formsets and do this by adding fields to the form with init?

4) what is the correct way of initializing form fields in a formset?

AM

like image 567
afshin Avatar asked Nov 14 '22 22:11

afshin


1 Answers

initialStuff must be list of dicts, not list of strings:

for cat in categories:    
  initialStuff.append( { categoryText: cat.categoryText,
  ...
     }
  )

So, don't remove the last comma.

If you use the operation += for list and str you get a list of strings (each str has length 1).

Please view the next: http://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset

like image 184
sergzach Avatar answered Dec 31 '22 06:12

sergzach