【问题标题】:How to remove character "T" in a DateTimeField in Django Vue.js?如何在 Django Vue.js 的 DateTimeField 中删除字符“T”?
【发布时间】:2020-06-26 01:14:53
【问题描述】:

我有一个包含 cmets 的列表,这些 cmets 有一个时刻字段,即 DateTimeField。在这个 DateTimeField 中,我有例如这个 --> 2020-06-03T15:32:01.803027 我想删除那个 T 字符,或者用空格替换。

我使用 Django 作为后端,使用 Vue.js 作为前端。 我可以通过将 settings.py 文件中的 USE_TZ = True 更改为 False 选项来删除 Z 字符。但是我不能删除 T 字符,这就是我所需要的。我已经尝试从前端使用方法和计算属性删除 T 字符,但是我不能在 DateTimeField 上使用 replace("T", " ") 方法,我只能在 String 上使用它

<template lang="html">
    <div class="container">
       <div class="row">
           <div class="col text-left">
               <h2>Detalles del partido</h2>
           </div>
       </div>

        <div class="row">
           <div class="col">
               <div class="card">
                   <div class="card-body">

                       <form>
                        <form @submit="onSubmit">

                        <div class="form-group row">
                            <label for="nombreLocal" class="col-sm-2 col-form-label">Local</label>    
                            <div class="col-sm-6">
                             <input type="text" name="nombreLocal" class="form-control" readonly v-model.trim="form.nombreLocal">
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="nombreVisitante" class="col-sm-2 col-form-label">Visitante</label>    
                            <div class="col-sm-6">
                             <input type="text" name="nombreVisitante" class="form-control" readonly v-model.trim="form.nombreVisitante">
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="resultado" class="col-sm-2 col-form-label">Resultado</label>    
                            <div class="col-sm-6">
                             <input type="text" name="resultado" class="form-control" readonly v-model.trim="form.resultado">
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="pronosticoSistema" class="col-sm-2 col-form-label">Pronóstico del sistema</label>    
                            <div class="col-sm-6">
                             <input type="text" name="pronosticoSistema" class="form-control" readonly v-model.trim="form.pronosticoSistema">
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="premio" class="col-sm-2 col-form-label">Premio</label>    
                            <div class="col-sm-6">
                             <input type="number" name="premio" class="form-control" readonly v-model.trim="form.premio">
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="dificultad" class="col-sm-2 col-form-label">Dificultad</label>    
                            <div class="col-sm-6">
                             <input type="text" name="dificultad" class="form-control" readonly v-model.trim="form.dificultad">
                            </div>
                        </div>

                        <div class="rows">
                            <div class="col text-left">
                            <b-button size="sm" variant="primary" :to="{ name:'CreatePronostico', params: {partidoId: this.partidoId} }">
                            Pronosticar
                            </b-button>    
                            <b-button size="sm" variant="primary" :to="{ name:'CreateComentario', params: {partidoId: this.partidoId}}">
                            Comentar
                            </b-button>
                            <b-button size="sm" type="submit" class="btn-large-space" :to="{ name: 'PronosticadorUsuario'}">Atrás</b-button>
                            </div>
                        </div>

                        </form>
                        <br>
                        <h2>Comentarios</h2>
                        <br>
                        <div class="comentarios">
                            <b-table striped hover 
                                :items="comentarios" 
                                :fields="fields"
                                :sort-by.sync="sortBy" 
                                :sort-desc.sync="sortDesc">
                                <template v-slot:cell(action)="data">
                                    <b-button size="sm" variant="primary" :to="{ name:'CreateComentarioRespuesta', params: {comentarioId: data.item.id} }">
                                        Responder
                                    </b-button>
                                    <b-button size="sm" variant="primary" :to="{ name:'DarMeGusta', params: {comentarioId: data.item.id} }">
                                        Me gusta
                                    </b-button>
                                    <b-button size="sm" variant="primary" :to="{ name:'EditComentario', params: {comentarioId: data.item.id} }">
                                        Editar
                                    </b-button>
                                    <b-button size="sm" variant="danger" :to="{ name:'DeleteComentario', params: {comentarioId: data.item.id} }">
                                        Eliminar
                                    </b-button>
                                </template>
                            </b-table>
                        </div>  


                       </form> 
                    </div>   
                </div>
            </div> 
        </div>       
    </div>  
</template>

<script>
import axios from 'axios'
import swal from 'sweetalert'
import router from "../../router";

export default {

    mounted() {
        this.checkLoggedIn();
    },

    data() {
        return {
            sortBy: 'momento',
            sortDesc: false,
            partidoId: this.$route.params.partidoId,
            form: {
                nombreLocal: '',
                nombreVisitante: '',
                resultado: '',
                pronosticoSistema: '',
                premio: '',
                dificultad: ''
            },
        
            fields: [
                { key: 'id', label: 'Número de comentario' },
                { key: 'momento', label: 'Momento', sortable: true},
                { key: 'texto', label: 'Texto' },
                { key: 'meGustas', label: 'Número de "me gustas"', sortable: true},
                { key: 'autor', label: 'Autor' },
                { key: 'comentarioRespuesta', label: 'Responde a' },
                { key: 'action', label: '' }
            ],
            comentarios: []
        }
    },
    methods: {

        checkLoggedIn() {
         this.$session.start();
        if (!this.$session.has("token")) {
            router.push("/auth");
            }
        },

        onSubmit(evt){
            evt.preventDefault()

            const path = `http://localhost:8000/api/v1.0/partidos/${this.partidoId}/`

            axios.get(path, this.form).then((response) =>{

                this.form.nombreLocal = response.data.nombreLocal
                this.form.nombreVisitante = response.data.nombreVisitante
                this.form.resultado = response.data.resultado
                this.form.pronosticoSistema = response.data.pronosticoSistema
                this.form.premio = response.data.premio
                this.form.dificultad = response.data.dificultad

            })
            .catch((error) => {
                console.log(error)
            })

        },

        getPartido (){
            const path = `http://localhost:8000/api/v1.0/partidos/${this.partidoId}/`

            axios.get(path).then((response) =>{

                this.form.nombreLocal = response.data.nombreLocal
                this.form.nombreVisitante = response.data.nombreVisitante
                this.form.resultado = response.data.resultado
                this.form.pronosticoSistema = response.data.pronosticoSistema
                this.form.premio = response.data.premio
                this.form.dificultad = response.data.dificultad

            })
            .catch((error) => {
                console.log(error)
            })
        },

    getComentarios (){

      const path = 'http://localhost:8000/api/v1.0/comentarios/'
      axios.get(path).then((response) => {
        this.comentarios = response.data
      })
      .catch((error) => {
        console.log(error)
      })
    },

},

    computed: {
      comentariosFormateados: function (){
          var res = [];
          for(var i = 0; i < this.comentarios.length; i++){
              this.comentarios[i].momento.toISOString().replace('T', '');
              res.push(comentarios[i]);
          }
        return res;
      }

    },

    created() {
        this.getPartido(),
        this.getComentarios()
    }
}
</script>>

<style lang="css" scoped>
</style>

【问题讨论】:

  • 日期时间字段在哪里?
  • DateTimeField在后台,我放上来,给大家看
  • @MeL 我试过用这个,但不知道具体怎么用,在哪里用,能举个例子吗?
  • 你能展示你的models.py文件吗?

标签: javascript django vue.js


【解决方案1】:

只需返回您想要的格式的 Django DateTime 对象,例如:

myDateTime = strftime(MyModel.objects.get(id=id).moment, "%Y-%m-%d %H:%M:%S.%f")

或者:

comment = MyModel.objects.get(id=id)
moment = strftime(comment.moment, "%Y-%m-%d %H:%M:%S.%f")
comment.formatted_moment = moment
...

然后以该格式(格式化字符串)将其返回到您的视图。

【讨论】:

    【解决方案2】:

    我已经解决了这个问题:

    formatMomento(value) { const formattedDate = DateTime.fromISO(value).toLocaleString(DateTime.DATETIME_SHORT); return formattedDate; },

    并从 formatter 属性调用它:

    fields: [
                { key: 'id', label: 'Número de comentario' },
                { key: 'momento', formatter: "formatMomento", label: 'Momento', sortable: true},
                { key: 'texto', label: 'Texto' },
                { key: 'meGustas', label: 'Número de "me gustas"', sortable: true},
                { key: 'autor', formatter: "nombreDeUsuario", label: 'Autor' },
                { key: 'comentarioRespuesta', label: 'Responde al comentario:' },
                { key: 'action', label: '' }
            ],
    

    【讨论】:

      猜你喜欢
      • 2016-01-25
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      相关资源
      最近更新 更多