我有一个包含reference_id的URL,该参考ID传递给我的HTML文件,以默认使用ModelForm的值。我的问题是我默认的字段ModelForm字段是另一个模型的外键。由于上述原因,我当前通过HTML文件执行的方式未提交表单。我想知道如何将该表单字段设置为默认值,该参数是通过URL传递的参数,使其变为只读,然后仍将其发布到模型中。在下面发布的表单中,这是我尝试默认设置的“引用”字段,而在HTML中,标记是我当前的操作方式。任何想法或替代方法都值得欢迎。
MODELS.PY
class Manifests(models.Model):
reference = models.ForeignKey(Orders)
cases = models.IntegerField()
description = models.CharField(max_length=1000)
count = models.IntegerField()
def __str__(self):
return self.cases
FORMS.PY
class CreateManifestForm(forms.ModelForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'description', 'count')
VIEWS.PY
def add_manifest(request, reference_id):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
form.save()
return redirect('add_manifest', reference_id=reference_id)
form = CreateManifestForm()
manifests = Manifests.objects.all()
context = {
'form': form,
'reference_id': reference_id,
'manifests' : manifests,
}
return render(request, 'add_manifest.html', context)
ADD_MANIFEST.HTML
<div class="container">
<form method="POST">
<br>
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference">Reference ID: </label><br>
<input type="text" value="{{ reference_id }}">
<br>
</div>
<div class="column">
<label for="form.description">Description: </label>
<br>
{{ form.description}}
</div>
<div class="column">
<label for="form.cases">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count">Count: </label>
<br>
{{ form.count }}
<br>
<br>
</div>
<br>
<br>
<button type="submit" name="add_mani" style="border-color: #7395AE;">Add Line</button>
</form>
URLS.PY
url(r'^add_manifest/(?P<reference_id>\d+)/$', add_manifest, name='add_manifest'),
答案 0 :(得分:0)
您可以在views.py
中修改表单创建的实例:
# ... import the Orders model
def add_manifest(request, reference_id):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
try:
order = Orders.objects.get(id=reference_id)
except Orders.DoesNotExist:
pass # do error handling here
instance.reference = order
instance.save()
return redirect('add_manifest', reference_id=reference_id)
form = CreateManifestForm()
manifests = Manifests.objects.all()
context = {
'form': form,
'reference_id': reference_id,
'manifests' : manifests,
}
return render(request, 'add_manifest.html', context)