Thursday, January 30, 2014

App_step.readme_id may not be NULL

I am new to Django and am trying to save two objects from the same form. 

Models:

class ReadmeTemplate(models.Model):
    """
        Represents a bugfix README

        Contains step models, which contain multiple steps.
    """

    def __unicode__(self):
        return self.title

    title = 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.user
                readme_object.save()
                step_forms.readme_id = readme_object.id
                step_forms.save()
            except forms.ValidationError, error:
                readme_object = None

            return 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.

--
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/1b99affb-a246-45cd-9f3d-b011361254e3%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment