Question

I have a view and its template that handles and prints a form. The form has a ChoiceField that takes a list of models as choices. Here is my view, template and form:

*views.py*
def index(request):
    form = dbForm()
    print "form is: ", form
    return render(request, 'Directories/index.html', {'form':form})

*index.html*
<div id="content" align="center">                   
<form action="" method="get">   {% csrf_token %}
    {{form.as_p}}  
    <input type="submit" value="Edit" name="_add" />
</form>

*forms.py*
model_classes = []

class dbForm(forms.Form):
    model_classes_field = forms.ChoiceField(choices=models())

def models():
    apps = get_app('Directories')
    for model in get_models(apps):
        model_classes.append( (model._meta.verbose_name, model._meta.db_table), )
    return model_classes

The model choice submitted is sent to another view where a ModelForm displays the model's fields and expects data for each of the fields to be submitted. The submitted data are then stored in the database and the user is redirected back to the index to start again from the beginning. Here is the view, template and form:

*views.py*
def modelUpdate(request):
    if 'update' in request.POST: # If the form has been submitted...
        form_class = get_dynamic_form(request.GET['model_classes_field']) 
        form = form_class(request.POST)         
        if form.is_valid(): # All validation rules pass
            row = form.save() #saves into database 
            return render(request, 'Directories/index.html')
        else:
            print "form errors: ", form.errors
            return HttpResponse('ERROR -- Return to form submission')


*create.html*
<form action="" method="post"> {% csrf_token %}
{% for f_name in field_names %} 
    {% if not forloop.first %}      
        {{f_name}}: <input id="edit-{{f_name}}" type="text" name={{f_name}} /><br />
    {% endif %}
{% endfor %}<br />
<input type="submit" name="update" value="Update" />
<input type="reset" name="Clear" value="Clear" />
</form>

*forms.py*
#create a ModelForm using a dynamic model
def get_dynamic_form(c_model):
    model_class = get_model('Directories', c_model)
    class ObjForm(forms.ModelForm ):
        class Meta:
            model = model_class
return ObjForm

The problem occurs when the form is redirected back to the index.html return render(request, 'Directories/index.html') after the data have been saved into the database. What happens is that the index.html does not display the form {{form.as_p}}at all. Although when i check print "form is: ", form in my server (Apache) error.log, my form is there printed as it should be.

I cannot understand why the data are not rendered in my template after the redirection occurs but still they are displayed correctly in my server log.

Was it helpful?

Solution

You should pass the form instance to your template as you do in index view. Your code shall be updated to

def modelUpdate(request):
    if 'update' in request.POST: # If the form has been submitted...
        form_class = get_dynamic_form(request.GET['model_classes_field']) 
        form = form_class(request.POST)         
        if form.is_valid(): # All validation rules pass
            row = form.save() #saves into database 
            #------------------------------------------------v pass it to template
            return render(request, 'Directories/index.html', {'form': form})
        else:
            print "form errors: ", form.errors
            return HttpResponse('ERROR -- Return to form submission')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top