在Django view.py中设置ForeignKey

2024-10-01 07:39:39 发布

您现在位置:Python中文网/ 问答频道 /正文

def clientinfo(request):
    clientForm = ClientInfoForm(prefix="client")
    criminalForm = OCCForm(prefix="criminal")

    if request.method == 'POST':
        clientForm = ClientInfoForm(request.POST,prefix="client")
        criminalForm = OCCForm(request.POST,prefix="criminal")

        criminalForm['cust_id_id'] = clientForm['id']
        
        if clientForm.is_valid() or criminalForm.is_valid():
            clientForm.save()
            criminalForm.save()
            print("SUCCESSFUL SUBMISSION")
            return render(request, 'submitted.html')

    return render(request, 'clientinfo.html',
                  {'form': clientForm, 'occform': OCCForm})

我的criminalForm有一个ForeignKey字段cust_id,我需要将它设置为自动生成的clientForm主键

我想不出正确的方法?它们都有一个相关的模型ClientInfoOCC,如果我需要以某种方式使用它们来实现这一点

模型和表格: models.py

from django.db import models
from django.forms import ModelForm, Select, TextInput, EmailInput, DateInput, NumberInput, CheckboxInput, ChoiceField

class ClientInfo(models.Model):
    SALUTATIONS = (
        (
            ('Miss', 'Miss'),
            ('Mr.', 'Mr.'),
            ('Mrs.', 'Mrs.'),
            ('Ms.', 'Ms.'),
            ('Dr', 'Dr'),
            ('Rev', 'Rev')
        )
    )
    RACE = (
        (
            ('A', 'Asian'),
            ('B', 'Black'),
            ('H', 'Hispanic/Latino'),
            ('N', 'Native American'),
            ('W', 'White')
        )
    )
    GENDER = (
        (
            ('F', 'Female'),
            ('M', 'Male')
        )
    )
    STATE = (
        (
            ('AK', 'Alaska'),
            ('AL', 'Alabama'),
            ('AR', 'Arkansas'),
            ('AZ', 'Arizona'),
            ('CA', 'California'),
            ('CO', 'Colorado'),
            ('CT', 'Connecticut'),
            ('DC', 'District of Columbia'),
            ('DE', 'Delaware'),
            ('FL', 'Florida'),
            ('GA', 'Georgia'),
            ('HI', 'Hawaii'),
            ('IA', 'Iowa'),
            ('ID', 'Idaho'),
            ('IL', 'Illinois'),
            ('IN', 'Indiana'),
            ('KS', 'Kansas'),
            ('KY', 'Kentucky'),
            ('LA', 'Louisiana'),
            ('MA', 'Massachusetts'),
            ('MD', 'Maryland'),
            ('ME', 'Maine'),
            ('MI', 'Michigan'),
            ('MN', 'Minnesota'),
            ('MO', 'Missouri'),
            ('MS', 'Mississippi'),
            ('MT', 'Montana'),
            ('NC', 'North Carolina'),
            ('ND', 'North Dakota'),
            ('NE', 'Nebraska'),
            ('NH', 'New Hampshire'),
            ('NJ', 'New Jersey'),
            ('NM', 'New Mexico'),
            ('NV', 'Nevada'),
            ('NY', 'New York'),
            ('OH', 'Ohio'),
            ('OK', 'Oklahoma'),
            ('OR', 'Oregon'),
            ('PA', 'Pennsylvania'),
            ('PR', 'Puerto Rico'),
            ('RI', 'Rhode Island'),
            ('SC', 'South Carolina'),
            ('SD', 'South Dakota'),
            ('TN', 'Tennessee'),
            ('TX', 'Texas'),
            ('UT', 'Utah'),
            ('VA', 'Virginia'),
            ('VT', 'Vermont'),
            ('WA', 'Washington'),
            ('WI', 'Wisconsin'),
            ('WV', 'West Virginia'),
            ('WY', 'Wyoming'),
        )
    )
    salutation = models.CharField(max_length=5, choices=SALUTATIONS, default='Miss.')
    last_name = models.CharField(max_length=20)
    first_name = models.CharField(max_length=20)
    address = models.CharField(max_length=125)
    city = models.CharField(max_length=15)
    state = models.CharField(max_length=2, choices=STATE)
    zip = models.CharField(max_length=5)
    phone = models.CharField(max_length=15)
    dob = models.DateField()
    age = models.IntegerField()
    employer = models.CharField(max_length=21)
    work_phone = models.CharField(max_length=15)
    workphext = models.CharField(max_length=5)
    mobile = models.CharField(max_length=15)
    ss_no = models.CharField(max_length=11)
    dl = models.CharField(max_length=12)
    race = models.CharField(max_length=1, choices=RACE)
    sex = models.CharField(max_length=1, choices=GENDER)
    email = models.EmailField(max_length=100)
    opt_out = models.BooleanField(default=False)
    refby_name = models.CharField(max_length=40)

# Adding model from database to forms and styling them with bootstrap
class ClientInfoForm(ModelForm):
    case_type = ChoiceField(choices=(('criminal','Criminal'),('domestic','Domestic')), widget=Select(attrs={'class':'form-control', 'id':'case_type'}))

    class Meta:
        model = ClientInfo

        widgets = {
            'salutation': Select(attrs={'class':'form-control col-sm-2'}),
            'first_name': TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name*'}),
            'last_name': TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name*'}),
            'phone': TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone Number*', 'data-inputmask': "'mask':'(999) 999-9999'", 'data-inputmask-clearincomplete': 'true'}),
            'email': EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email Address*'}),
            'dob': DateInput(attrs={'type': 'date', 'class': 'form-control', 'aria-describedby':'input_dob_label'}),
            'race': Select(attrs={'class': 'form-control', 'aria-describedby': 'input_race_label'}),
            'sex': Select(attrs={'class': 'form-control', 'aria-describedby': 'input_sex_label'}),
            'address': TextInput(attrs={'class': 'form-control', 'placeholder': 'Address*'}),
            'city': TextInput(attrs={'class': 'form-control', 'placeholder': 'City*'}),
            'state': Select(attrs={'class':'form-control', 'aria-describedby':'input_state_label',}),
            'zip': TextInput(attrs={'class': 'form-control', 'placeholder': 'Zip*',
                                      'data-inputmask': "'mask':'99999'",
                                      'data-inputmask-clearincomplete': 'true'}),
            'age': NumberInput(attrs={'class': 'form-control','placeholder':'Age*'}),
            'employer': TextInput(attrs={'class': 'form-control', 'placeholder': 'Employed By*'}),
            'work_phone': TextInput(attrs={'class': 'form-control col-sm-9', 'placeholder': 'Work Number', 'data-inputmask': "'mask':'(999) 999-9999'", 'data-inputmask-clearincomplete': 'true'}),
            'workphext': TextInput(attrs={'class': 'form-control col-sm-3', 'placeholder': 'Ext', 'maxlength': "6",}),
            'mobile': TextInput(attrs={'class': 'form-control', 'placeholder': 'Mobile Number', 'data-inputmask': "'mask':'(999) 999-9999'", 'data-inputmask-clearincomplete': 'true'}),
            'opt_out': CheckboxInput(attrs={'class': 'custom-control-input'}),
            'refby_name': TextInput(attrs={'class': 'form-control', 'placeholder': 'Referred By'}),

        }

        # Dynamically Create Form Fields based on widget details
        fields = []
        for widget in widgets:
            fields.append(widget)
        fields = tuple(fields)

class OCC(models.Model):
    cust_id = models.ForeignKey(ClientInfo,on_delete=models.CASCADE)
    charge = models.CharField(max_length=10)
    court_date = models.DateField()

class OCCForm(ModelForm):
    class Meta:
        model = OCC

        widgets = {
            'charge': TextInput(attrs={'class':'form-control'}),
            'court_date': DateInput(attrs={'type': 'date', 'class': 'form-control'})
        }

        # Dynamically Create Form Fields based on widget details
        fields = []
        for widget in widgets:
            fields.append(widget)
        fields = tuple(fields)

编辑

在运行以下代码时,我现在在控制台中看到“FORM NOT VALID”:

def clientinfo(request):
    clientForm = ClientInfoForm(prefix="client")
    criminalForm = OCCForm(prefix="criminal")

    if request.method == 'POST':
        clientForm = ClientInfoForm(request.POST,prefix="client")
        criminalForm = OCCForm(request.POST,prefix="criminal")
        if clientForm.is_valid() and criminalForm.is_valid():
            client = clientForm.save()
            criminalForm.instance.cust_id = client
            criminalForm.save()
            return redirect('submitted.html')
        else:
            print("FORM NOT VALID")

以下是数据库中OCC表的结构The database Structure


Tags: formdataprefixmodelsrequesttextinputlengthattrs
1条回答
网友
1楼 · 发布于 2024-10-01 07:39:39

您应该检查两个表单是否有效,保存clientForm后,您可以在criminalForm中设置.instance包装的.cust_id

from django.shorcuts import redirect

def clientinfo(request):
    clientForm = ClientInfoForm(prefix='client')
    criminalForm = OCCForm(prefix='criminal')
    if request.method == 'POST':
        clientForm = ClientInfoForm(request.POST, prefix='client')
        criminalForm = OCCForm(request.POST, prefix='criminal')
        if clientForm.is_valid() and criminalForm.is_valid():
            client = clientForm.save()
            criminalForm.instance.cust_id = client.pk
            criminalForm.save()
            return redirect('name-of-some-view')

    return render(
        request,
        'clientinfo.html',
        {'form': clientForm, 'occform': OCCForm}
    )

Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.


Note: Normally one does not add a suffix _id to a ForeignKey field, since Django will automatically add a "twin" field with an _id suffix. Therefore it should be cust, instead of cust_id.

相关问题 更多 >