Django frontend app not loading React Component - django

i am following tranversy Media Django-React tutorial. After the server is running ok, but the components in my App.js file are not displayed in the index.html. Kindly help on what could be wrong, all.
This is my project tree:
see the image
Then my app.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
class App extends Component {
render() {
return <h1>React App</h1>
}
}
ReactDOM.render(<App />, document.getElementById("app"));
My index.html
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://bootswatch.com/4/cosmo/bootstrap.min.css">
<title>Lead Manager</title>
{%load static%}
</head>
<body>
<h1></h1>
<div id="app"></div>
<script>src="{%static "frontend/main.js"%}"</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
index.js
import App from './components/App';
webpack.config.js
module.exports = {
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader:"babel-loader"
}
}]
}
}
The backend is working fine using the api.

Change this
<script>src="{%static "frontend/main.js"%}"</script>
to this
<script src="{%static "frontend/main.js"%}"></script>

Related

How to include HTML partials using Vite?

Is it possible to include snippets of shared HTML using Vite (vanilla)? I'm looking for a way to have the HTML prerendered without injecting via JS.
Something like:
<html>
<head>
{ include 'meta-tags' }
</head>
<body>
{ include 'nav' }
<h1>Hello World</h1>
<body>
</html>
vite-plugin-handlebars was the solution I was looking for. Partials were super easy to set up with this package:
Setup:
// vite.config.js
import { resolve } from 'path';
import handlebars from 'vite-plugin-handlebars';
export default {
plugins: [
handlebars({
partialDirectory: resolve(__dirname, 'partials'),
}),
],
};
File where you want to include partial:
<!-- index.html -->
{{> header }}
<h1>The Main Page</h1>
Rendered output:
<header>My Website</header>
<h1>The Main Page</h1>
You could use the vite-plugin-html that enables EJS templates in index.html:
// vite.config.js
import { defineConfig } from 'vite'
import { createHtmlPlugin } from 'vite-plugin-html'
export default defineConfig({
plugins: [
createHtmlPlugin({
entry: 'main.js',
/**
* Data that needs to be injected into the index.html ejs template
*/
inject: {
data: {
metaTags: `<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />`,
nav: `<nav>
Google |
Apple
</nav>`,
},
},
}),
],
})
<!-- index.html -->
<html>
<head>
<%- metaTags %>
</head>
<body>
<%- nav %>
<h1>Hello World</h1>
<body>
</html>
demo

Getting and inserting the value of a CSRF cookie set by Django in Angular

I'm having some trouble getting the CSRF integration between Django and Angular to work. I made an earlier broader post about that here.. The problem is that logged in users can't make post-requests from the front-end, but they can make the exact same requests from Django's browsable API through forms.
I'm setting a {% csrf_token %} at the index template that Django serves and I am using Angular's built it XSRFS strategy to set attack a header to http requests, but I think the problem is that I'm not catching the value provided by Django's generated csrf token and can't figure out how to implement gathering that data and attaching it to my Angular http-request cookies. Here's the code for the module that provides the strategy:
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '#angular/http'
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { RegisterComponent } from './register/register.component';
import { LoginComponent } from './login/login.component';
import { AlertComponent } from './_directives/alert.component';
import { ProfileComponent } from './profile/profile.component';
import { AuthGuardService } from './_guards/auth-guard.service';
import { AlertService } from './_services/alert.service';
import { AuthService } from './_services/auth.service';
import { UserService } from './_services/User.service';
#NgModule({
declarations: [
AppComponent,
RegisterComponent,
LoginComponent,
AlertComponent,
ProfileComponent,
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
HttpClientModule,
HttpModule
],
providers: [
{
provide: XSRFStrategy,
useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
And here is the output from the browser with the csrf-value that I think I need to attach somehow:
<input type='hidden' name='csrfmiddlewaretoken' value='9FKUKSXHbJfLClZniDXIHrMu2AEUtPQr4mGDfNSOZURHYVyKGBYvREIuucN0UsEM' />
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularWebapp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="/static/runtime.js"></script><script type="text/javascript" src="/static/polyfills.js"></script><script type="text/javascript" src="/static/styles.js"></script><script type="text/javascript" src="/static/vendor.js"></script><script type="text/javascript" src="/static/main.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>
Make sure that "csrfmidlewaretoken": {{csrf_token}} is submitted with the form.
Make sure {% csrf_token %} is inside <form></form> tags. If you are posting the data with ajax, add "csrfmidlewaretoken": {{csrf_token}} to your form data that is submitted.

Ionic 2 SignalR error " Please ensure jQuery is referenced before the SignalR client JavaScript file."

I'm trying to use signalR in ionic 2 app .For signalR im using
ms-signalr-client library.
Index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<title>Ionic App</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#4e8ef7">
<!-- cordova.js required for cordova apps -->
<script src="cordova.js"></script>
<!-- un-comment this code to enable service worker
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js')
.then(() => console.log('service worker installed'))
.catch(err => console.log('Error', err));
}
</script>-->
<link href="build/main.css" rel="stylesheet">
</head>
<body>
<!-- Ionic's root component and where the app will load -->
<ion-app></ion-app>
<!-- The polyfills js is generated during the build process -->
<script src="build/polyfills.js"></script>
<script src="build/main.js"></script>
<!-- The bundle js is generated during the build process -->
<!-- Zone.js and Reflect-metadata -->
<script src="build/js/Reflect.js"></script>
<script src="build/js/zone.js"></script>
<!--Below added jquery and signal-->
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../jquery.signalR.js"></script>
</body>
</html>
Using here
import { Injectable } from '#angular/core';
import $ from 'jquery';
import 'ms-signalr-client';
import 'rxjs/Rx';
#Injectable()
export class SignalRService {
connection: hubConnection;
hubProxy:any;
constructor() {
}
startConnection() {
console.log("Stage 1");
this.connection =$.hubConnection('http://192.168.0.213:9000');//Server Deployed
console.log("Stage 2");
this.hubProxy = this.connection.createHubProxy('broadcaster');
console.log("Stage 3");
this.connection.start({ jsonp: true })
.done(() => {
console.log('Now connected, connection ID=' + this.connection.id);
})
.fail((err) => {
console.log('Could not connect');
});
}
}
But this error appear every time. I have search but didn't find any solution.
Uncaught Error: jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.
Note: I have tired this library as well but it has an issue .
Issue:Ionic 2 signalr is not connecting with hub
In reference to this Ng2-signalr .I just copy code and its working fine now .
import 'expose-loader?jQuery!jquery';
import '../node_modules/signalr/jquery.signalR.js';
The only way I get it to work is by adding such code to the top of a vendors file:
import 'expose-loader?$!expose-loader?jQuery!jquery';
import './node_modules/signalr/jquery.signalR.min.js';
jQuery should be available globally through aliases that's why I use explose-loader import together with ProvidePlugin in webpack config:
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
Please note, you can use jQuery version 2 or above for signalR.
Hope this will help.

Trying to get QUnit working with Emberjs

I'm trying to setup ember-testing with QUnit to test my Ember.js application.
My problem is the app isn't rendering on the QUnit test page, and thus the visit('/') function isn't working.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MKTS Tests</title>
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="./bower_components/qunit/qunit/qunit.css">
<!--
<link rel="stylesheet" href="./css/foundation.css">
<link rel="stylesheet" href="./css/app.css">
-->
<style type="text/css">
#qunit-fixture, #app-root {
position: relative;
top: 0;
left: 0;
width: auto;
height: auto;
}
</style>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<!-- Libraries (Dependencies) -->
<script src="../app/bower_components/requirejs/require.js"></script>
<script src="../app/bower_components/jquery/dist/jquery.min.js"></script>
<script src="../app/bower_components/handlebars/handlebars.js"></script>
<script src="../app/bower_components/ember/ember.js"></script>
<script src="../app/bower_components/ember-data/ember-data.js"></script>
<!-- App and Templates -->
<script src="../app/scripts/app.js"></script>
<script src="../app/scripts/models/fleets.js"></script>
<script src="../app/scripts/routes/application_route.js"></script>
<script src="../app/scripts/routes/index_route.js"></script>
<script src="../app/scripts/router.js"></script>
<script src="../app/scripts/store.js"></script>
<!-- Test Helpers -->
<script src="./support/test_helper.js"></script>
<!-- Test Library -->
<script src="./bower_components/qunit/qunit/qunit.js"></script>
<script src="./spec/integration.js"></script>
<script src="./spec/unit.js"></script>
</body>
</html>
integration.js
test('hello world', function() {
//debugger;
//expect(1);
MarketSetupAdminUi.reset();
visit("/").then(function() {
var title = find('title');
equal(title.text(), 'Market Setup Tool', 'Title check');
});
});
test-helper.js
(function (host) {
var document = host.document;
var App = host.MarketSetupAdminUi;
var testing = function(){
var helper = {
container: function(){
return App.__container__;
},
controller: function( name ){
return helper.container().lookup('controller:' + name);
},
path: function(){
return helper.controller('application').get('currentPath');
}
};
return helper;
};
Ember.Test.registerHelper('path', function() {
return testing().path();
});
Ember.Test.registerHelper('getFoodController', function() {
return testing().controller('food');
});
// Move app to an element on the page so it can be seen while testing.
document.write('<div id="test-app-container"><div id="ember-testing"></div></div>');
App.rootElement = '#ember-testing';
App.setupForTesting();
App.injectTestHelpers();
function exists(selector) {
return !!find(selector).length;
}
}(window));
I updated the app to Ember 1.10.0 and Ember-data beta.15.
I'm planning to regenerate the app using Ember-CLI, which appears to have better testing.

Jquery tag-it autocomplete placement off

I am trying to use aehlke/tag-it and its autocomplete option. The autocomplete shows up but in an odd position.
Here is my code:
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'/>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css">
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link href="tag-it/css/jquery.tagit.css" rel="stylesheet" type="text/css">
<link rel='stylesheet' type='text/css' href='bootstrap/css/bootstrap.css'>
<link rel='stylesheet' type='text/css' href='style.css'>
</head>
<body>
<div class='container'>
<h2> Tagging Functions </h2>
<div class='row'>
<div class='span5'>
<ul id="myTags">
<!-- Existing list items will be pre-added to the tags -->
</ul>
</div>
</div>
</div>
<!-- Scripts -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script>
<script src="tag-it/js/tag-it.js" type="text/javascript" charset="utf-8"></script>
<script scr='bootstrap/js/bootstrap.js'></script>
<script src='js/main.js'></script>
</body>
</html>
AND JS:
// Main JS
$(document).ready(function() {
$("#myTags").tagit({
availableTags:['me', 'you']
});
});
It's because tag-it use curCSS wich was remove from jQuery on 1.8 so if you use any jQuery version higger than that... is not going to work.
A workaround could be to load jQuery 1.7.x and use jQuery.noConflict
This is my solution
//Save current jQuery
current_jquery = $.noConflict(true);
//Load the jQuery 1.7.3
current_jquery('<script>').appendTo($('head')).attr({
type: 'text/javascript',
id : 'jquery_173',
src : '//ajax.googleapis.com/ajax/libs/jquery/1.7.3/jquery.min.js'
});
//Keep jQuery 1.7.3 in a var to use it later
jquery_tagit = $.noConflict(true);
//Revert the jQuery that you where using to its original var $
$ = jQuery_actual;
//Load tag-it with jQuery 1.7.3
jquery_tagit.tagit({...});