fgalvao
fgalvao

Reputation: 460

How to submit data to database using Django ModelForm?

I'm learning some Django and right now i'm having difficulties with Forms. What i want to do is create a form that let people leave messages on the page, that will be shown in that same page (just like a blog comment system). I created a class and the ModelForm like this, following the documentation

class Recado(models.Model):
    recado = models.TextField()
    data = models.DateTimeField(auto_now_add=True)
    nome = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)

    def __unicode__(self):
        return self.recado

class RecadoForm(ModelForm):
    class Meta:
        model = Recado
        exclude = ('data',)

Then here's my view:

def index(request):
    RecadoForm = modelform_factory(Recado, exclude=('data'))
    form = RecadoForm()
    lista_recados = Recado.objects.order_by('-data')
    template = loader.get_template('recados/index.html')
    context = Context({'lista_recados': lista_recados,})
    return render_to_response("recados/index.html", { "form": form,}, context_instance=RequestContext(request))

And the template:

<div class="conteudo-site conteudo-recados">
    <form method="post" action="salvar_recado">
        {% csrf_token %}            
        {{ form.as_p }}
        <br /><input class="button" type="submit" value="Deixar Recado" />
    </form>
    {% if lista_recados %}
        {% for recado in lista_recados %}
            <p>{{ recado.nome }}</p>
            <p>{{ recado.data }}</p>
            <p>{{ recado.recado }}</p>
            <br />
        {% endfor %}
    {% else %}
        <p>Ainda não existem recados. Deixe o seu :)</p>
    {% endif %}
</div>

This generates the form correctly on the page, but when i click the on the submit button it doesn't save the data on the database, and now i can't figure out what to do. Tried some things with views but nothing worked.

Can someone help me, please? Thank you very much.

Upvotes: 3

Views: 5670

Answers (2)

Leandro
Leandro

Reputation: 2247

If you are working with Django 1.5 try THIS

Maybe your view could be that:

class RecadoFormView(FormView):
    model_class = RecadoForm
    template_name = 'recados/index.html'

    def valid_form(self, form):
        form.instance.save() # Or form.save()
        return super(RecadoFormView, self).valid_form(form)

Upvotes: 0

matino
matino

Reputation: 17715

You need add POST condition in your view, validate the form and then save it: https://docs.djangoproject.com/en/dev/topics/forms/#using-a-form-in-a-view

Upvotes: 5

Related Questions