如何在django 3.1中基于另一个字段保存模型之前更改模型字段

时间:2020-10-13 13:23:45

标签: django django-models django-forms django-admin

我需要能够将Settings模型的KeyIndex字段设置为等于的值

lastExtension-firstExtension

我该怎么做

这是我模型的内容 models.py

class Settings(models.Model):
 
    KeyIndex = models.CharField(max_length=150, blank=True, name='Key_Index')

    firstExtension = models.CharField(max_length=15, blank=False, null=False, default='1000')
    lastExtension = models.CharField(max_length=15, blank=False, null=False, default='1010')

    def save(self, *args, **kwargs):
        f = int(self.firstExtension)
        l = int(self.lastExtension)
        a = [0] * (l - f)
        self.KeyIndex = str(a)
       
        return super(Settings, self).save()



class KeyFiles(models.Model):
    setting = models.ForeignKey(Settings, on_delete=models.CASCADE)
    keyFile = models.FileField(upload_to='key File', null=True, blank=True, storage=CleanFileNameStorage,
                               validators=[FileExtensionValidator(allowed_extensions=['bin']), ])

这是我表格的内容 forms.py

class ShowAdminForm(forms.ModelForm):

    class Meta:
        model = Settings
        fields = '__all__'

    files = forms.FileField(
        widget=forms.ClearableFileInput(attrs={"multiple": True}),
        label=_("Add key Files"),
        required=False,validators=[FileExtensionValidator(allowed_extensions=['bin'])]
    )


    def save_keyFile(self, setting):
        
          file = KeyFiles(setting=setting, keyFile=upload)
          file.save()
            

和t admin.py

class KeyFilesAdmin(admin.TabularInline):
    model = KeyFiles


@admin.register(IPPhone_Settings)
class IPPhoneSettingsAdmin(admin.ModelAdmin):
    form = ShowAdminForm
    inlines = [KeyFilesAdmin]

    def save_related(self, request, form, formsets, change):
        super(IPPhoneSettingsAdmin, self).save_related(request, form, formsets, change)
        
    

0 个答案:

没有答案