使用JS呈现Django表单 [英] Using JS to render Django form

查看:34
本文介绍了使用JS呈现Django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习在Django项目中利用纯JS.作为服务器端开发人员,这些概念对我来说相对较新,因此需要帮助.

I'm learning to utilize pure JS in Django projects. Being a server-side developer the concepts are relatively new for me, so need a hand.

想象一个用户可以在其中张贴文本和/或上传图像的表单.可以将其视为一个简单的Django形式,如下所示:

Imagine a form where a user can post text, and/or upload an image. Think of it as a simple Django form like so:

class PostForm(forms.Form):
    image = forms.ImageField(required=False)
    reply = forms.CharField(required=False, widget=forms.Textarea(attrs={'cols':30,'rows':3,'class': 'cxl','autocomplete': 'off','autofocus': 'autofocus'}))

    def __init__(self,*args,**kwargs):
        super(PostForm, self).__init__(*args,**kwargs)
        self.fields['image'].widget.attrs['id'] = 'browse_image_btn'

    def clean(self):
        data = self.cleaned_data
        # perform cleaning
        return data

如果我要以HTML形式呈现此表单,则将执行以下操作:

If I were to render this form in HTML, something like the following would do:

<form action="{% url 'post_content' %}" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ post_form.reply }}<br>
    {{ post_form.image }}
    <label for="browse_image_btn" style="cursor: pointer;"><img alt="Select photo" src="{{ STATIC_URL }}img/upload.svg" width="70" height="70"></label>        
    <input type="submit" value="submit">
</form>

但是如何仅通过JS创建此HTML?

But how do I create this HTML solely via JS?

用例::设想一个包含一长串内容的页面,每个页面下方都有一个 reply 按钮.仅当用户按下 reply 按钮后,上方的表单才会显示在特定内容下.此外,按下相同的按钮也可以将其切换为 off .

Use-case: imagine a page that contains a long list of content, with a reply button under each. The form above only appears under specific content once the user has pressed the reply button. Moreover, pressing the same button toggles it off too.

我似乎无法全力以赴地解决这样的问题.请提供建议,最好提供一个示例.我希望了解最有效,可扩展的方法,可以在专业环境中进行部署.只有纯JS,没有JQuery.

I can't seem to wrap my head around solving a problem like that. Please advise, preferably with an illustrative example. I'd prefer to understand the most efficient, scalable way to do this, one that can be deployed in professional settings. Only pure JS, no JQuery.

我对此进行了尝试,但是由于我是JS新手,所以他们半生不熟.这是到目前为止我得到的:

I've made attempts at this, but they're half-baked since I'm a JS newbie. Here's what I've got so far:

  var okBtn = document.createElement('button');
    setUpSubmitBtn(okBtn);
   e.target.parentNode.insertAdjacentElement('afterend', okBtn);

   var camBtn = document.createElement('img');
    setUpCameraBtn(camBtn);
   e.target.parentNode.insertAdjacentElement('afterend', lineBreak);
   e.target.parentNode.insertAdjacentElement('afterend', camBtn);

   var replyBox = document.createElement('textarea');
    setUpReplyBox(replyBox);
   e.target.parentNode.insertAdjacentElement('afterend', replyBox);

可以使用简单的JS函数来创建上述每个小部件:

Where there are simple JS functions to create each of the widgets referred above:

function setUpReplyBox(replyBox) {
    replyBox.classList.add('mts');
    replyBox.setAttribute('id', 'reply-message');
    replyBox.setAttribute('style', 'display:inline');
    replyBox.setAttribute('placeholder', 'Reply');
}

function setUpSubmitBtn(okBtn) {
    okBtn.classList.add('btn', 'bcb', 'bs', 'mts');
    okBtn.setAttribute('style','border:none;height:25px;display:inline;');
    okBtn.setAttribute('id','reply-ok');
    okBtn.innerHTML = "OK";
}

function setUpCameraBtn(camBtn) {
    camBtn.setAttribute('id','camera');
    camBtn.setAttribute('src','/static/img/cam1.svg');
    camBtn.setAttribute('width','45');
    camBtn.setAttribute('height','45');
    camBtn.setAttribute('style','display:inline;float:right;');
}

我觉得我在做错/错.正确的模式可能会简单得多.

I feel like I'm doing it the hard/wrong way. The right pattern is probably going to be much simpler.

推荐答案

希望有帮助:

var formTemplate = document.querySelector('#form-template form');
var idInput = document.getElementById('id-input');

function toggleReply(e) {
  if (!formTemplate) return;

  e.target.parentNode.insertBefore(formTemplate, e.target);
  idInput.value = e.target.getAttribute('data-id');
};

Array.from(document.querySelectorAll('button.reply'))
  .forEach(btn => btn.onclick = toggleReply)

form + .reply {
  display: none;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div id="form-template" style="display: none;">
  <form action="" method="POST" enctype="multipart/form-data">
      <input id="id-input" type="hidden" name="id" value="">
      <div class="form-group">
        <label for="reply">Reply:</label>
        <textarea class="form-control" type="text" name="text"></textarea>
      </div>
      <input type="submit" class="btn btn-default pull-right" value="submit">
  </form>
</div>

<div class="container">
  <div class="list-group">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">Comment title</h3>
      </div>
      <div class="panel-body">
        Comment content
      </div>
      <div class="panel-footer clearfix">
        <button class="reply btn btn-default pull-right" type="button" data-id="24">Reply</button>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">Comment title</h3>
      </div>
      <div class="panel-body">
        Comment content
      </div>
      <div class="panel-footer clearfix">
        <button class="reply btn btn-default pull-right" type="button" data-id="25">Reply</button>
      </div>
    </div>
  </div>
</div>

这篇关于使用JS呈现Django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆