Getting Id of another Django form inside of other Django form
Hi guys i want to create multiple forms like this: ask for connection name and connection type and save it in database and after that redirect user to new form for connection details but i want one field as foreign key pointed to item created in last form.
models:
from django import models
class Form1Model(models.Model):
name = models.CharField(max_length=100)
connection_type=models.CharField(max_length=100)
def __str__(self) -> str:
return self.name
class Form2Model(models.Model):
name=models.CharField(max_length=100)
protocol=models.CharField(max_length=5)
connection_name=models.ForeignKey(Form1, on_delete=models.CASCADE)
def __str__(self) -> str:
return self.name
my forms:
from django import forms
from inventory.models import Form1, Form2
class Form1Form(forms.ModelForm):
class Meta:
model = Form1
fields = "__all__"
class Form2Form(forms.ModelForm):
form1 = forms.ModelChoiceField(queryset=Form1.objects.all())
class Meta:
model = Form2
fields = ["form1", "name", "protocol"]
now i want to know how i must create my views thnx for help guys.
I asked from Codeium AI and it returned this code:
from django.shortcuts import render, redirect
from django.views.generic import CreateView
from .forms import Form1Form, Form2Form
from .models import Form1, Form2
class Form1CreateView(CreateView):
model = Form1
form_class = Form1Form
template_name = 'form1_form.html'
success_url = '/form2/' # redirect to form2 view
def form_valid(self, form):
form.save()
return redirect('form2', pk=form.instance.pk) # pass Form1 instance pk to form2 view
class Form2CreateView(CreateView):
model = Form2
form_class = Form2Form
template_name = 'form2_form.html'
def get_initial(self):
form1_pk = self.kwargs['pk']
form1_instance = Form1.objects.get(pk=form1_pk)
return {'form1': form1_instance} # pre-populate form1 field with Form1 instance
def form_valid(self, form):
form.save()
return redirect('success_url') # redirect to success URL
I accomplished something very similar to this using the below video utilizing the django form wizard. The one difference is that it won't submit between the forms, but one final submit once all the data is entered. This may end up being a better solution depending on your needs.
Maybe not an exact solution, but may lead you down the right path to finding the right solution for your situation.