简体   繁体   English

在 Django view.py 中设置 ForeignKey

[英]Set ForeignKey in Django view.py

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})

My criminalForm has a ForeignKey field cust_id and i need to set it to the auto-generated Primary key of clientForm我的criminalForm有一个ForeignKey 字段cust_id ,我需要将它设置为clientForm的自动生成的主键

I can't figure out the correct way to do this?我想不出正确的方法来做到这一点? They both have an associated model ClientInfo and OCC if I need to use them somehow to accomplish this?如果我需要以某种方式使用它们来完成此操作,它们都有关联的 model ClientInfoOCC

Models and Forms: models.py型号和 Forms: 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)

EDIT编辑

I'm now getting "FORM NOT VALID" in my console when running the code below:运行以下代码时,我现在在控制台中收到“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")

Here's the structure of the OCC table in the database这是数据库中OCC表的结构数据库结构

You should check if both forms are valid, and after saving the clientForm , you can set the .cust_id of the .instance wraooed in the criminalForm :您应该检查两个forms 是否有效,并在保存clientForm后,您可以设置.cust_id.instancecriminalForm中:

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] .注意:如果 POST 请求成功,您应该进行redirect [Django-doc]以实现Post/Redirect/Get模式 [wiki] This avoids that you make the same POST request when the user refreshes the browser.这样可以避免在用户刷新浏览器时发出相同的 POST 请求。


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.注意:通常不会将后缀_id添加到ForeignKey字段,因为 Django 会自动添加带有_id后缀的“twin”字段。 Therefore it should be cust , instead of cust_id .因此它应该是cust ,而不是cust_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM