Django用按钮

时间:2017-12-02 16:52:07

标签: django amazon-web-services amazon-s3

我正在尝试创建一个按钮,一旦点击就会在AWS中创建一个S3存储桶。当谈到Django时,我仍然有点绿,所以我不确定如何让它运行。我阅读了一些教程,但是所有教程都展示了如何在单击按钮时向数据库添加内容。 以下是我到目前为止所做的事情:

views.py

class createS3(TemplateView):
template_name = 'project/create_s3.html'

def get(self, request):
    form = S3Form()
    return render(request, self.template_name, {'form': form})

def createBucket(self, bucketName):
    form = S3Form(request.POST)
    s3 = boto3.resource('s3')
    if form.is_valid():
        name = form.cleaned_data['name']
    s3.create_bucket(Bucket=name)

def post(self, request):
    form = S3Form(request.POST)
    if form.is_valid():
        name = form.cleaned_data['name']
    args = {'form':form, 'name':name}
    return render(request, self.template_name, args)

这是模板:

{% include "home/_header.html" %}
{% block content %}
{% load staticfiles %}
 <div class="mainPage">
   <div class="s3Wrapper">
      <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" name="create" class="button create">Create</button>
      </form>
    </div>
  </div>
{% endblock content %}

现在我的问题是,如何点击按钮调用createBucket功能?或者我是否需要创建一个新的url并在那里传递'name'变量来创建一个新的存储桶?

谢谢!

1 个答案:

答案 0 :(得分:3)

你为什么不这样做:

def createBucket(self, bucketName):
    s3 = boto3.resource('s3')
    s3.create_bucket(Bucket=bucketName)

def post(self, request):
    form = S3Form(request.POST)
    if form.is_valid():
        name = form.cleaned_data['name']
        self.createBucket(name)
    ...