我正在尝试通过它的id来检索另一个视图中的Instance对象,该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}}正在运作,因为我已将其放置在此模板中的其他位置。
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'),
]
答案 0 :(得分:0)
在您看来尝试更改此行,
obj = Instance.objects.get(id=int(instance_id))