سؤال

I've 4 models that I need to store data at once. For that I'm thinking using ModelForms.

I've tested with 2 ModelForm's at the same time but it is not working. Here is the code.

Model:

class Main(models.Model):
    section             = models.ForeignKey(Section)
    user                = models.ForeignKey(User)
    title               = models.CharField(max_length=250)
    date_inserted       = models.DateTimeField(auto_now_add=True)
    date_last_update    = models.DateTimeField(auto_now=True)

    def __unicode__(self):
    return self.title

    # To order in the admin by name of the section
    class Meta:
    ordering = ['date_inserted']


class BicycleAd(models.Model):
    main                = models.ForeignKey(Main)
    bicycleadtype       = models.ForeignKey(BicycleAdType)
    bicycleaditemkind   = models.ForeignKey(BicycleAdItemKind) # MPTT Model
    bicycleadcondition  = models.ForeignKey(BicycleAdCondition)
    country             = models.ForeignKey(GeonamesCountry)       
    city                = models.ForeignKey(GeonamesLocal) 
    date_inserted       = models.DateTimeField(auto_now_add=True)
    date_last_update    = models.DateTimeField(auto_now=True)

    # To order in the admin by name of the section
    class Meta:
    ordering = ['date_inserted']   

Forms:

class MainForm(forms.ModelForm):
    class Meta:
    model = Main
    exclude = ('user', 'section')

class BicycleAdForm(forms.ModelForm):
    class Meta:
    model = BicycleAd
    exclude = ('main', 'bicycleadtype', 'bicycleaditemkind', 'bicycleadcondition', 'city')

View:

def submit_data_entry_view(request):
    form_main      = MainForm(request.POST)
    form_bicyclead = BicycleAdForm(request.POST)

    return render_to_response('app/submit_data_entry.html', {'form_main': form_main, 'form_bicyclead': form_bicyclead}, context_instance=RequestContext(request))

Template:

<form method="post" action="">
    {{form_main}}
    {{form_bicyclead}}
</form>

At the end I only get the"form_bicyclead" outputed in the browser? How can I get the two forms at once?

Best Regards,

هل كانت مفيدة؟

المحلول

are you using submit_data_entry_view to render forms too? shouldn't it be like -

def submit_data_entry_view(request):

    if request.method == 'POST': #form submit
        form_main      = MainForm(request.POST)
        form_bicyclead = BicycleAdForm(request.POST)

        #now process and save the form

        return <whatever_you_want>
    elif request.method == 'GET': #first time rendering the form
        form_main      = MainForm()
        form_bicyclead = BicycleAdForm()

        return render_to_response('app/submit_data_entry.html', {'form_main': form_main, 'form_bicyclead': form_bicyclead}, context_instance=RequestContext(request))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top