只有一个字段需要用户输入。其他依赖于该字段,并在保存表单之前以编程方式填充。将其他字段添加到ModelForm并使其隐藏是唯一的解决方案,还是有更好的方法?
class Sentence(models.Model):
sent = models.CharField(max_length=150) # Only this field needs user input
sent_correct = models.CharField(max_length=300, blank=True)
msg_list = ArrayField(models.CharField(max_length=500), blank=True, default=list)
pub_date = models.DateTimeField(default=timezone.now)
class SentenceForm(ModelForm):
class Meta:
model = Sentence
fields = ['sent']
# I want to avoid attribute error in the view and programatically populate the fields before saving the form
def home(request):
sentences = Sentence.objects.all()
if request.method == 'POST':
form = SentenceForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
form.save(commit=False)
sent = cd['sent']
# here I need to process sent and populate other fields with
# the results then save the form
form.save()
return render(request, 'home.html', {'sentences': sentences, 'msg_list': msg_list, 'form': form})
else:
form = SentenceForm()