0
我在一個視圖內使用2個表單時遇到困難。這裏是我的代碼和問題:在一個視圖中處理Django中的兩個表單時發生的問題
型號
class Process(models.Model):
name = models.CharField(max_length = 200)
order = models.IntegerField(
default=0,
validators=[
MinValueValidator(0)
]
)
status = models.BooleanField(default = True)
process_owner = models.CharField(max_length = 200)
created_by = models.CharField(max_length = 200)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
class SubProcess(models.Model):
process = models.ForeignKey(Process, on_delete=models.CASCADE)
next_sub_process = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=False)
name = models.CharField(max_length = 200)
status = models.BooleanField(default = True)
sub_process_owner = models.CharField(max_length = 200)
created_by = models.CharField(max_length = 200)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
形式
class createProcessForm(ModelForm):
class Meta:
model = Process
fields = ['name', 'order',]
class createSubProcessForOneShotCreationForm(ModelForm):
class Meta:
model = SubProcess
fields = ['name',]
模板
<form action="{% url 'processmanagement:create_process_subProcess_step' %}" method="post">
{% csrf_token %}
<p>Process</p>
{{ form_process }}
<p>Sub Process</p>
{{ form_subProcess }}
<p></p>
<input type="submit" value="Submit" />
</form>
視圖
def create_process_subProcess_step(request):
if request.method == 'POST':
form_process = createProcessForm(request.POST)
print('form_process : ' + str(form_process))
form_subProcess = createSubProcessForOneShotCreationForm(request.POST)
if form_process.is_valid() and form_subProcess.is_valid():
process_instance = form_process.save()
subProcess_instance = form_subProcess.save(commit=False)
subProcess_instance.process = process_instance
subProcess_instance.save()
return redirect('processmanagement:displayProcessAndSubProcess')
form_process = createProcessForm()
form_subProcess = createSubProcessForOneShotCreationForm()
context = {
'form_process' : form_process,
'form_subProcess' : form_subProcess
}
return render(request, 'processmanagement/create_process_subProcess_step', context)
當在一個視圖中創建2個表單並保存這些表單時,它看起來像來自第二個表單的名稱的數據在DB中保存在第一個和第二個對象中,而第一個表單應該填充第一個對象,第二個表單應該填充第二個對象。例如:在網頁中,您驗證:進程名稱= A,子進程名稱= B,在Db中,進程名稱= B,子進程名稱= B。 我該如何處理? MariaDb results
我經歷了不同的主題,如自動提交,緩存問題,數據庫問題(我已經從SQLite更改爲MariaDB),但沒有任何幫助。
你應該接受讓未來的搜索者知道它解決了你的問題的答案。 –