我有一个表单,其中定义的数据带有一些隐藏字段,即IP地址,因为不需要在表单页面上向用户显示该表单。
用户选择地址大小后,view.py函数将计算并划分出IP块。
我希望将此IP与其他信息一起保存。
请参见下面的代码
我以为通过了account = account_form.save(commit=False)
然后调用account.next_subnet(负责IP cal)
然后运行一个account.save()
#models.py
class Account(models.Model):
id = models.AutoField(primary_key=True, editable=False)
us = models.CharField(max_length=100, blank=False)
account = models.CharField(max_length=100, blank=False)
network_size = models.CharField(max_length=100, blank=False)
network_range = models.CharField(max_length=100, blank=False)
budget = models.CharField(max_length=100, blank=False)
account_number = models.IntegerField(blank=True, null=True)
class Meta:
db_table = "xxxx"
def __str__(self):
return self.account
#forms.py
class AccountForm(ModelForm):
class Meta:
model = Account
fields = (us', 'account', 'network_size', 'budget',)
CHOICES = (('small', 'small'),('medium', 'medium'),('large','large'),)
choices=[(x, x) for x in range(500,10000 )]
widgets = {
'us': forms.TextInput(attrs={'placeholder': 'us', 'class': 'form-control'}),
'account': forms.TextInput(attrs={'placeholder': 'account', 'class': 'form-control'}) ,
'network_size': forms.Select(choices=CHOICES,attrs={'class': 'form-control'}),
'budget': forms.Select(choices=choices,attrs={'class': 'form-control'}),
'account_number':forms.HiddenInput(),
'network_range':forms.HiddenInput(),
}
#views.py
@login_required(login_url='/portal/sign-in/')
def portal_create_account(request, *args, **kwargs):
account_form = AccountForm(request.POST)
if request.method == "POST":
account_form = AccountForm(request.POST)
if account_form.is_valid():
account = account_form.save(commit=False)
account = account_form.cleaned_data['account']
network_size = account_form.cleaned_data['network_size'];print(network_size)
nb = pynetbox.api("http://REDACTED","REDACTED")
get_parent_pref = nb.ipam.prefixes.get(30);print(get_parent_pref)
prefix = nb.ipam.prefixes.get(prefix=get_parent_pref);print("listpre"+str(prefix))
if network_size == "small":
account.next_subnet = prefix.available_prefixes.create({'prefix_length': 28})['prefix']
elif network_size == "medium":
account.next_subnet = prefix.available_prefixes.create({'prefix_length': 25})['prefix']
elif network_size == "large":
account.next_subnet = prefix.available_prefixes.create({'prefix_length': 24})['prefix']
account.save()
return redirect(portal_account)
return render(request, 'portal/create_account.html', {
"account_form": account_form
})
答案 0 :(得分:1)
我认为问题在于这两行
account = account_form.save(commit=False) account = account_form.cleaned_data['account']
account
的第二个定义将覆盖第一个定义,这在您的情况下不太好。您实际上想将第二个命名为其他名称,然后可以继续填充account
并以account.save()
结尾应该有用。