在其他 Django 表单中获取另一个 Django 表单的 Id

问题描述 投票:0回答:1

大家好,我想创建这样的多步骤表单: 询问连接名称和连接类型并将其保存在数据库中 之后将用户重定向到新表单以获取连接详细信息,但我想要一个字段作为外键指向在上一个表单中创建的项目。

型号:

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

我的表格:

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"]

现在我想知道我必须如何创建我的观点,谢谢大家的帮助。

python django django-forms django-viewsets
1个回答
0
投票

我向 Codeium AI 询问,它返回了以下代码:

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
© www.soinside.com 2019 - 2024. All rights reserved.