James Kolber James Kolber - 4 months ago 10
Python Question

ModelForm won't create instance of model

I am trying to create a frontend form in my Django site that will allow users to add entries to my SQL database.

But when I use the form nothing happens in my database. What am I doing wrong?

I thought the right way would be to use the ModelForm technique.

My models looks like this:

class Actor(models.Model):
name = models.CharField(max_length=200)
wage = models.IntegerField(default=3100)

def __str__(self):
return self.name


So I wrote this in my forms.py:

from django import forms
from .models import Actor

class ActorForm(forms.ModelForm):
class Meta:
model = Actor
fields = ['name', 'wage']
form = ActorForm()


I then added this to my views.py:

def get_actor(request):
if request.method == 'POST':
form = ActorForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/scenes/thanks/')
else:
form = ActorForm()

return render(request, 'scenes/actor.html', {'form': form})

def thanks(request):
return render(request, 'scenes/thanks.html',)


And this in a template called actors.html

<form action="/scenes/actor/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />



Answer

You have to call the model form's save() method after checking that it's valid:

def get_actor(request):
    if request.method == 'POST':
        form = ActorForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/scenes/thanks/')
    else:
        form = ActorForm()

    return render(request, 'scenes/actor.html', {'form': form})