I try to fill empty fields when I save model form, but unfortunately, it doesn't work properly.
this is my view:
def bylaw_save(request):
form = BylawForm(initial={'who_created': request.user.username})
if request.method == 'POST':
form = BylawForm(request.POST)
if form.is_valid():
gdn = GlobalDocNumber.objects.get(pk=1)
gdn.gdn += 1
gdn.save()
raspr_num = form.cleaned_data['raspr_num'][:]
raspr_num = raspr_num.split('/')
bylaw = form.save(commit=False)
bylaw.district = 'unfilled'
bylaw.department = 'unfilled'
bylaw.performer = 'unfilled'
bylaw.check_type = 'unfilled'
bylaw.save()
return bylaw_form(request, msg='test')
else:
return bylaw_form(request, msg='test')
return render(request, 'bylaw/bylaw_form.html', {'form': form})
this is fraction of my form:
district = ModelChoiceField(required=False, queryset=DistrictsMenu.objects.all(), to_field_name="district",
widget=Select(attrs={'id': "district", 'class': 'form-control col-6'}))
department = ModelChoiceField(required=False, queryset=DepartmentsMenu.objects.all(), to_field_name="department",
widget=Select(attrs={'id':"department", 'class': "form-control col-6"}))
UPDATE: This is my model with default='Unfilled', according to Arthur M and Rohan suggestions (But it also doesn't work, it gives me a "NOT NULL constraint failed: bylaw_bylawmodel.department" error, in this case I don't fill department field):
class BylawModel(models.Model):
raspr_date = models.DateField()
district = models.CharField(max_length=255, default='Unfilled')
department = models.CharField(max_length=255, default='Unfilled')
organization = models.CharField(max_length=255, default='Unfilled')
inn = models.IntegerField()
performer = models.CharField(max_length=255, default='Unfilled')
check_type = models.CharField(max_length=255)
date_proved = models.DateField()
raspr_num = models.CharField(max_length=255, unique=True)
who_created = models.CharField(max_length=255)
when I save this from, it always fills with 'unfilled'. How can I fill empty values only if they are really empty?
答案 0 :(得分:0)
这样做
bylaw.fieldName = 'unfilled'
您正在覆盖从表单发送的值。
如果您不想在模型中添加默认值(我建议这样做),则可以添加一个简单的:
if not bylaw.fieldName:
bylaw.fieldName = 'unfilled'
对于您的每个字段。