Creating multiple objects in django view from ajax post

I have the following model: C objects contained by objects B contained in object A

I have a dynamic form in the template and using jQuery functions I can add dynamically several fields to this form, each group of fields representing objects (B or C)

When posting with a post action, I would like to create a tree of objects. My goal is to create an object tree when checking this template.

It currently works, but I think my solution is really dirty:

  • Creating lists with js / jquery, according to the number of elements that I have in my form
  • Passing these lists using $ .post as data arguments
  • Using lists in a query, creating objects in a django data model in a view

I am sure there really is a better solution: p

  • Use multiple messages to create objects through different views (other than A, B and C)? (But problems with synchronization ..)
  • Use json to represent objects directly on the js / jquery side?
  • Another solution?

Thanks a lot - edited for clarity

EDIT:

Note: My data model is different here (I simplified it earlier) So: Session is the former “Object A”, Exercise is the “Object B” Repetition is the “Object C” - Sorry for that, I hope it will be clear enough (I will fix in the last post)

Some progress here, on your part, guys :) I played a little with Form and FormSet. Obviously its powerful :)

So now I have the following view:

class RepetitionForm(forms.Form): weight = forms.CharField() count = forms.CharField() def workoutForm(request): RepetitionFormSet = formset_factory(RepetitionForm, extra=1) if request.method == 'POST': repetitionFormSet = RepetitionFormSet(request.POST) user = get_object_or_404(User, pk=1) session = Session(date=datetime.date.today(), user=user) session.save() exerciseTypeRef = get_object_or_404(ExerciseTypeRef, pk=1) exercise = Exercise(session = session, exerciseTypeRef = exerciseTypeRef) exercise.save() if repetitionFormSet.is_valid(): for repetitionForm in repetitionFormSet.cleaned_data: if(repetitionForm.is_valid()): weight = repetitionForm.data['weight'] count = repetitionForm.data['count'] return HttpResponse("ok") else: repetitionFormSet = RepetitionFormSet() return render_to_response('workoutForm.html', {'formSet': repetitionFormSet}, context_instance=RequestContext(request)) 

The side of the template is similar:

 {% csrf_token %} {{ formSet.management_form }} <ul id="idUlFormSet"> {% for item in formSet %} <li> {{ item }} </li> {% endfor %} 

(The template uses additional code to add instances with a dynamic form, as this smart post by Django describes - a dynamic built-in FormSet Javascript with auto-completion , I will not explain here)

Currently, when submitting the form, I got this error from the view:

"Weight" key not found in

If i try

 repetitionItem.isValid() 

The RepetitionForm object does not have the isValid attribute

The same problem occurs if I use forms.ModelForm instead of forms.Form

I'm stuck: p

My models

 class User(models.Model): name = models.CharField(max_length=100) mail = models.CharField(max_length=100) dateCreated = models.DateTimeField('User creation date') def __unicode__(self): return self.name class Session(models.Model): date = models.DateField('Session Date') user = models.ForeignKey(User) def __unicode__(self): return self.date.strftime("%Y/%m/%d") class ExerciseTypeRef(models.Model): name = models.CharField(max_length=100) desc = models.CharField(max_length=300) def __unicode__(self): return self.name class Exercise(models.Model): session = models.ForeignKey(Session) exerciseTypeRef = models.ForeignKey(ExerciseTypeRef) def __unicode__(self): return self.exerciseTypeRef.name class Repetition(models.Model): exercise = models.ForeignKey(Exercise) count = models.IntegerField() weight = models.IntegerField() 
+3
source share
2 answers

Make a model model for your model "A" like this.

 class FormA(forms.ModelForm) : """Signup Form""" class Meta : model = ObjectA 

In your opinion:

 from django.forms.models import modelformset_factory def form(request) : # Use Modelformset_factory and exclude the FK fields FormBSet = modelformset_factory(ObjectB, exclude=('objecta',)) FormCSet = modelformset_factory(ObjectC, exclude=('objectb',)) if request.method == "POST" : forma = FormA(request.POST, prefix="forma") formbset = FormBSet(request.POST, prefix="formbset") formcset = FormCSet(request.POST, prefix="formcset") if forma.is_valid() and formbset.is_valid() and formcset.is_valid() : # save a a = forma.save() # save a into b for formb in formbset: b = formb.save(commit=False) b.objecta = a b.save() # save b into c for formc in formcset: c = formc.save(commit=False) c.objectb = b c.save() ... 
  • when initializing the modelForms model in the view, give them a prefix
  • commit = False so you can save the resulting object from a previous save operation
  • Use Formsets (https://docs.djangoproject.com/en/dev/topics/forms/formsets/#formsets) to manage n * instances of B and C

EDIT

use from django.forms.models import modelformset_factory NOT formset_factory, also pay attention to the exclude paramater parameter.

see https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets

+2
source

It works now!

Made some mistakes:

 RepetitionFormSet = formset_factory(RepetitionForm, extra=1) if request.method == 'POST': repetitionFormSet = repetitionFormSet(request.POST) #should be repetitionFormSet = RepetitionFormSet(request.POST) 

is_valid IS CRUCIAL (objects don't populate instead!) and I tried to call

 repetitionForm.isValid() 

What a Java function should be, but does not exist in django form objects! (stupid to me)

And finally, sometimes I tested my code without filling in the fields, throwing a KeyError exception. I'm not sure if this is normal, I will have to deal with it now

Thanks a lot to Francis!

0
source

All Articles