0
我想通過它的ID已經從模板中隱藏的輸入字段傳遞但無法獲取對象的其他視圖中檢索實例對象。通過在Django中的id字段檢索數據庫對象
這裏是我的文件:
BuildImage.html
{% block content %}
<form class="form-horizontal" method="POST" id="dockerForm">
{% csrf_token %}
<fieldset>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-user bigicon"></i><label for="package">Docker Image Tag Name:</label></span>
<div class="col-md-8">
<input type="text" name="tagName" id="tagName" placeholder="e.g node_image/istiogui" class="form-control" required>
<input type="hidden" id="id" name="id" value="{{ id }}">
</div>
</div>
<div class="form-group">
<div class="col-xl-12 text-center">
<button type="button" class="btn btn-primary btn-info"><a href="/gui" style="color:white">Back</a></button>
<button type="submit" class="btn btn-primary btn-info">Build</button>
</div>
</div>
</fieldset>
</form>
{{ id }} is working as I have placed it at another place in this template.
models.py
class Instance(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, related_name='instances')
name = models.CharField(max_length=255)
serverFile = models.TextField(default='', blank=False)
jsonPackageFile = models.TextField(default='', blank=False)
created_at = models.DateTimeField(default=timezone.now, editable=False)
class Meta:
ordering = ['-created_at']
class ImageModel(models.Model):
tagName = models.CharField(max_length=255)
id = models.ForeignKey(Instance, primary_key=True)
views.py
class BuildImage(LoginRequiredMixin, CreateView):
def get(self, request, *args, **kwargs):
return render(request, 'instances/BuildImage.html', {})
def post(self, request, *args, **kwargs):
if request.method == 'POST':
pathlib.Path("mydir").mkdir(parents=True, exist_ok=True)
dockerfile = """
FROM node
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/ap
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY . /usr/src/app
EXPOSE 8080
CMD [ "npm", "start" ]"""
cFile = open("mydir/dockerfile", "w")
cFile.write(dockerfile)
cFile.close()
the_form = forms.BuildImageForm(request.POST)
if the_form.is_valid():
data = the_form.cleaned_data
instance_id = data['id']
obj = Instance.objects.all(id=str(instance_id))
title = obj.name
code = obj.serverFile
package = obj.jsonPackageFile
cFile = open("mydir/"+ title, "w")
cFile.write(code)
cFile.close()
cFile = open("mydir/package.json", "w")
cFile.write(package)
cFile.close()
return HttpResponse(status=200)
urls.py
urlpatterns = [
url(r'^create/$', views.CreateInstance.as_view(), name='create'),
url(r'^buildImage/$', views.BuildImage.as_view(), name='buildImage'),
]
它拋出另一個錯誤,'文件「/用戶/阿卜杜勒/文檔/文件名爲「IGUI/instances/views.py」,第60行,後 obj = Instance.objects.all(id = int(instance_id)) TypeError:int()參數必須是字符串, e實體或數字,而不是'實例' [22/Jul/2017 05:35:06]「POST/user/instance/buildImage/HTTP/1.1」500 14104' –