Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit data to database using Django ModelForm?

Tags:

python

django

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.

like image 830
fgalvao Avatar asked Jun 18 '26 00:06

fgalvao


1 Answers

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

like image 98
matino Avatar answered Jun 19 '26 15:06

matino