On Thursday, January 30, 2014 9:08:22 AM UTC-8, Wnt2bsleepin wrote:
I am new to Django and am trying to save two objects from the same form.Models:class ReadmeTemplate(models.Model):"""Represents a bugfix READMEContains step models, which contain multiple steps."""def __unicode__(self):return self.titletitle = models.CharField(max_length=200) author = models.CharField(max_length=200) user = models.ForeignKey(User,editable=False) class Step(models.Model):"""Represents a single step in a Readme Template"""step_text = models.TextField()readme = models.ForeignKey(ReadmeTemplate) I am able to save the ReadmeTemplate fine, but the Steps are not able to be saved. Here is what I am trying in the view.def createTemplate(request):StepFormSet = modelformset_factory(Step, max_num=100, form=CreateStepForm,extra=1)if(request.method == 'POST'):readme_form = CreateReadmeTemplateForm(request.POST) step_forms = StepFormSet(request.POST)if readme_form.is_valid() and step_forms.is_valid():try:readme_object = readme_form.save()readme_object.user = request.userreadme_object.save()step_forms.readme_id = readme_object.idstep_forms.save()except forms.ValidationError, error:readme_object = Nonereturn HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % (escape(readme_object._get_pk_ val()), escape(readme_object))) return render(request,'App/newtemplate.html',{'readme_ form':readme_form,'step_forms' : step_forms}) else:readme_form = CreateReadmeTemplateForm()step_forms = StepFormSet(queryset=Step.objects.none()) return render(request,'App/newtemplate.html',{'readme_ form':readme_form,'formset': step_forms}) Is there anyway to get the id of the readme object and assign it to the step object? Thanks for any help.
All you need to do is to set the readme_object to the readme attribute of step_forms, Django will extract the id for you and set it appropriately.
step_forms.readme = readme_object
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+unsubscribe@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/a98fdc71-e2d8-4d77-8ba7-60d34a718cf7%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
No comments:
Post a Comment