在Django模型中以特定格式创建自动id

时间:2017-07-26 15:44:58

标签: python django slug

我试图在模型中创建一个字段,只要某个实例以某种方式自动创建该字段。以下是相关代码:

models.py

class Student(models.Model):
    # This first field is what I'm focusing on
    student_id = models.CharField(max_length=128, unique=True)
    first_name = models.CharField(max_length=128)
    last_name = models.CharField(max_length=128)
    ssn = USSocialSecurityNumberField(null=False)
    gender = models.CharField(max_length=128, choices=GENDER_CHOICES)
    dob = models.DateField(auto_now=False, auto_now_add=False, db_column="date of birth")
    address = models.CharField(max_length=128)
    city = models.CharField(max_length=128)
    state = USStateField(choices=STATE_CHOICES, default='NJ')
    zipcode = USZipCodeField(blank=True)
    country = CountryField(default='US', blank=True)
    home_phone = models.CharField(max_length=128)
    cell_phone = models.CharField(max_length=128)
    email = models.EmailField(max_length=254, validators=[validate_email])
    background = models.CharField(max_length=128, choices=BACKGROUND_CHOICES)
    # This field is relevant
    location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield')
    workforce = models.CharField(max_length=128, choices=WORKFORCE_CHOICES, default='--')
    source = models.CharField(max_length=128, choices=SOURCE_CHOICES, default='individual')
    refer_by = models.CharField(max_length=128, choices=REFER_BY_CHOICES, default='no refer')
    last_status = models.CharField(max_length=128, choices=LAST_STATUS_CHOICES, default='followup')
    newsletter = models.BooleanField()
    created_by = models.CharField(max_length=128)
    # This field is relevant
    date = models.DateField(auto_now=False, auto_now_add=False)
    notes = models.TextField()

我想通过以特定格式自动创建student_id字段来使其变得不同:

AASSSYYMMDD

AA是' AV'当学生获得报酬时,' PS'当学生没有。我将它默认为PS' PS'现在所以不用担心。

SSS是该位置的前三个字母

YYMMDD分别是日期字段的年,月和日的最后两个数字

我听说我应该使用AutoSlugField或SlugField,但我遇到的每一个例子只会填充整个一个字段,当我想填充我的时候多个领域的某些部分放在一起。有谁知道如何正确地从不同的领域采取正确的格式?感谢。

编辑:这是其他一些代码:

forms.py

class StudentForm(forms.ModelForm):
    # STEP 1 FORM
    # student_id = forms.CharField(max_length=128, label="Student ID")
    # first_name = forms.CharField(max_length=128, label="First Name", widget=forms.TextInput(attrs={'class': 'form-control'}))
    # last_name = forms.CharField(max_length=128, label="Last Name")
    ssn = USSocialSecurityNumberField(widget=forms.TextInput(attrs={'class': 'form-control'}), label="SSN", help_text="Format: xxx-xx-xxxx")
    # gender = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'}), label="Gender", choices=GENDER_CHOICES)
    dob = forms.DateField(input_formats=['%m/%d/%Y'], widget=DateInput(format='%m/%d/%Y'), label="Date of birth", help_text="Format: mm/dd/yyyy")
    # contact_number = forms.CharField(max_length=128, label="Contact number")
    # address = forms.CharField(max_length=128, label="Address")
    # city = forms.CharField(max_length=128, label="City")
    # state = forms.ChoiceField(choices=STATE_CHOICES, initial="NJ", label="State")
    # zipcode = USZipCodeField(label="Zipcode")
    # country = forms.ChoiceField(choices=countries, label="Country", initial="US")
    home_phone = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control bfh-phone', 'data-format': '+1 (ddd) ddd-dddd'}), max_length=128, label="Home phone")
    cell_phone = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control bfh-phone', 'data-format': '+1 (ddd) ddd-dddd'}), max_length=128, label="Cell phone")
    email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'}), max_length=254, validators=[validate_email], label="Email")
    # background = forms.ChoiceField(choices=BACKGROUND_CHOICES, label="Background")
    # location = forms.ChoiceField(choices=LOCATION_CHOICES, initial="south_plainfield", label="Location")
    # workforce = forms.ChoiceField(choices=WORKFORCE_CHOICES, initial="--", label="Workforce")
    # source = forms.ChoiceField(choices=SOURCE_CHOICES, initial="individual", label="Source")
    # refer_by = forms.ChoiceField(choices=REFER_BY_CHOICES, initial="no refer", label="Refer by")
    # last_status = forms.ChoiceField(choices=LAST_STATUS_CHOICES, initial="followup", label="Last status")
    newsletter = forms.BooleanField(widget=forms.CheckboxInput(), label="Newsletter", required=False)
    # created_by = forms.CharField(max_length=128, label="Created by")
    date = forms.DateField(widget=forms.DateInput(attrs={'class': 'form-control'}), label="Date", help_text="Format: yyyy-mm-dd")
    notes = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'}), required=False, label="notes", help_text="less than 1000 characters")

    class Meta:
        model = Student
        fields = ('first_name', 'last_name', 'ssn', 'gender', 'dob', 'address', 'city', 'state', 'zipcode', 'country', 'home_phone', 'cell_phone', 'email', 'background', 'location', 'workforce', 'source', 'refer_by', 'last_status', 'newsletter', 'created_by', 'date', 'notes')

views.py

def add_Student(request):
    form = StudentForm()
    if request.method == 'POST':
        form = StudentForm(request.POST)

        if form.is_valid():
            form.save(commit=True)

            return render(request, 'students/add_student_success.html', {})
        else:
            print(form.errors)

    return render(request, 'students/add_student.html', {'form': form})

1 个答案:

答案 0 :(得分:0)

主要问题是,此字段是否是您模型中的primary_key

如果没有,那么主键将是Django的默认id,即AutoField()。所以现在你手动处理student_id

我建议创建一个post_save信号处理方法,您可以在其中设置student_id字段,就像我的示例中所示:

def method_for_student_id(sender, instance, created, **kwargs):
    if created:  # else it results in an infinite loop
        # business logic here to create the student id string
        student_id = ....

        instance.student_id = student_id
        instance.save()

post_save.connect(method_for_student_id, sender=Student)

我希望在你的情况下有所帮助 - 让我知道这是否有效!