Good day community. I have a problem when saving the data of a form of type ModelForm. And it is that when you sent the data of the form to my database the following error appears:
AttributeError at /Usuario/
'Persona' object has no attribute 'get'
Then I attach the code of my form, view and template.
Form:
class PersonaForm(ModelForm):
class Meta:
model = Persona
fields = '__all__'
def __init__(self, nombre, *args, **kwargs):
super(PersonaForm, self).__init__(*args, **kwargs)
self.fields['nombre'].initial = nombre
View:
def index(request):
nombre = Persona.objects.get(pk = 5)
if request.method == 'POST':
form = PersonaForm(request.POST or None,nombre)
if form.is_valid():
form.save()
return redirect('Usuario:index')
else:
form = PersonaForm(nombre)
context = {
'form':form,
}
return render(request, 'index.html', context)
Models:
class Nacion(models.Model):
pais = models.CharField('Nombre pais', max_length=50)
def __str__(self):
return self.pais
class Persona(models.Model):
nombre = models.CharField('Nombre', max_length=50)
apellido = models.CharField('Apellido', max_length=50)
edad = models.IntegerField('Edad')
nacionalidad = models.ForeignKey(Nacion, verbose_name=("Nacion"), on_delete=models.CASCADE)
def __str__(self):
return self.nombre
Template:
<form method="post" action="">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Enviar">
</form>
Basically I'm having problems saving my form, I think because there's something in my function __init__
that I'm not doing right, what I want with this code is to generate arguments in the form and those to pass them in the view.
I add the image of the error that appears in the browser, it is line 14 of the view: