I have 2 test models, Model1 and Model2. Model2 has the OneToOneField key to Model1, but I can not assign the Model1_id to Model2_id to keep the relationship of the models, I do not know how to access that data from the views.py to assign it in form_is_valid, when I save the first form, I can not send it with reverse_lazy, since I must pass the pk, if I enter it manually to URL, with a select I can assign it, but I think that should be done in the backend
My models are from:
apps/formularios/models.py
class Modelo1(models.Model):
nombre = models.CharField(max_length=20)
apellidos = models.CharField(max_length=50)
class Modelo2(models.Model):
relacionModelo1 = models.OneToOneField(Modelo1, blank=False, null=False, on_delete=models.CASCADE)
curp = models.CharField(max_length=18)
nacionalidad = models.CharField(max_length=50)
my forms
apps/forms.py
class Modelo1Form(forms.ModelForm):
class Meta:
model = Modelo1
fields = ['nombre', 'apellidos']
labels = {
'nombre': 'Nombre(s)',
'apellidos': 'Apellidos',
}
widgets = {
'nombre': forms.TextInput(),
'apellidos': forms.TextInput(),
}
class Modelo2Form(forms.ModelForm):
class Meta:
model = Modelo2
fields = ['relacionModelo1', 'curp', 'nacionalidad']
labels = {
'curp': 'CURP',
'nacionalidad': 'Nacionalidad',
}
widgets = {
'relacionModelo1': forms.HiddenInput(),
'curp': forms.TextInput(),
'nacionalidad': forms.TextInput(),
}
My views.py
class Model1CreateView(CreateView):
model = Modelo1
form_class = Modelo1Form
template_name = 'form.html'
success_url = reverse_lazy('agregar:formulario2')
#no se como pasarle la pk a la siguiente página
class Model2CreateView(CreateView):
#no sé como asiganrle la pk del formulario1 al campo relacionModelo1
model = Modelo2
form_class = Modelo2Form
template_name = 'form.html'
success_url = reverse_lazy('agregar:formulario1')
Project URL
from django.conf.urls import url
import views
app_name = "agregar"
urlpatterns = [
url(r'nuevo1/$', views.Model1CreateView.as_view(), name='formualario1'),
url(r'nuevo2/(?P<pk>\d+)/$', views.Model2CreateView.as_view(), name='formulario2'),
]