Django 1.6.5 - Unable to load initial data from fixtures - django-models

I tried to load initial-data as suggested in djangoproject. But I couldn't able to load object on my database. But when I tried to load data, it always says
> python manage.py loaddata ./fixtures/initial_data.json
Installed 0 object(s) from 0 fixture(s)
But I have data on the initial_data.json [/test-project/tableTest/tableTest/fixtures/initial_data.json]
[
{
"model":"tableTest.person",
"pk":1,
"fields": {
"name":"Kevin"
}
},
{
"model":"tableTest.person",
"pk":2,
"fields": {
"name":"Harry"
}
},
{
"model":"tableTest.person",
"pk":3,
"fields": {
"name":"Piter"
}
}
]
#models.py
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=100, verbose_name="full name")
I also tried ./manage.py loaddata pwd/tableTest/fixtures/initial_data.json but could not succeed. Please help me to suggest what I have missed.

This issue arises because I write definition for model at project directory instead of app directory and Table I defined on model was not created on running syncdb. Later I create a app and move fixtures, models.py,views.py to app directory, rewrite urls.py. Then the data was loaded successfully.

Related

Why is my static React app not displaying on AWS despite being accessible?

I am having great difficulty understanding why my bucket link is still going 403 despite the fact I have created the bucket, uploaded the bucket to S3 and now it is telling me that I am not able to access the link with the public link. The code looks good; why is this not working? Is this an IAM's issue that I am not configuring?
Below is my infrastructure-stack.ts file:
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as iam from 'aws-cdk-lib/aws-iam';
export class InfrastructureStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const bucket = new s3.Bucket(this, 'WebsiteBucket', {
// Specify Bucket Name Here
bucketName: 'example-cdk-project',
// Specify the index document for our website
websiteIndexDocument: 'index.html',
// Allow public access to our bucket
blockPublicAccess: new s3.BlockPublicAccess({ restrictPublicBuckets: false })
});
// Create a bucket policy allowing anyone to access the objects in bucket
const bucketPolicy = new iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: [
`${bucket.bucketArn}/*`
],
// v2 conversion, previously with v1 this was [new iam.Anyone]
principals: [new iam.AnyPrincipal()],
})
// Add the policy to bucket
bucket.addToResourcePolicy(bucketPolicy);
}
}
Is there any additional policy I have to add on? This is the first time I am using TypeScript to create a bucket that I can then upload my React example site to. I feel as if something is missing, when I upload the content to the bucket, it updates and I have no problem logging into my AWS repository.
What am I missing?

Window.OneSignal showing 404 error when i am trying to use it with next.js

I am trying to implement OneSignal web push notifications with the next.js web app. I followed this article
to implement it. But it is not implementing properly as it shows an error. I have doubt that where should I place the window.OnseSignal code shown in step 7.
What I did?
I built a component name NewOneSignal instead of pasting it in App.js (because there is no App.js file in next.js) whose code is given below:
import React, { useEffect } from "react";
const NewOneSignal=()=>{
useEffect(()=>{
window.OneSignal = window.OneSignal || [];
const OneSignal = window.OneSignal;
},[]);
return (
OneSignal.push(()=> {
OneSignal.init(
{
appId: "i pasted my app id here", //STEP 9
promptOptions: {
slidedown: {
enabled: true,
actionMessage: "We'd like to show you notifications for the latest Jobs and updates about the following categories.",
acceptButtonText: "OMG YEEEEESS!",
cancelButtonText: "NAHHH",
categories: {
tags: [
{
tag: "governmentJobs",
label: "Government Jobs",
},
{
tag: "PrivateJobs",
label: "Private Jobs",
}
]
}
}
},
welcomeNotification: {
"title": "The website",
"message": "Thanks for subscribing!",
}
},
//Automatically subscribe to the new_app_version tag
OneSignal.sendTag("new_app_version", "new_app_version", tagsSent => {
// Callback called when tag has finished sending
console.log('new_app_version TAG SENT', tagsSent);
})
);
})
)
}
export default NewOneSignal;
And imported this component in the document.js file. According to this article, I have to put step 8 code in the useEffect but didn't work also, I have tried that also
I am very much sure that the problem is in this file. I paste the OneSignalsdk script in head section of the _document.js file.Also, i moved the two service worker files in a public folder as shown in the article. Please help me to make this code work

react native (expo) load markdown files

I'm having some troubles loading markdown files (.md) into my react native (non-detached expo project).
Found this awesome package that allows me to render it. But can't figure out how to load the local .md file as a string.
import react from 'react';
import {PureComponent} from 'react-native';
import Markdown from 'react-native-markdown-renderer';
const copy = `# h1 Heading 8-)
| Option | Description |
| ------ | ----------- |
| data | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext | extension to be used for dest files. |
`;
export default class Page extends PureComponent {
static propTypes = {};
static defaultProps = {};
render() {
return (
<Markdown>{copy}</Markdown>
);
}
}
BTW: I tried googling, but can't get the suggestions to work
https://forums.expo.io/t/loading-non-media-assets-markdown/522/2?u=norfeldtconsulting
I tried the suggested answers for reactjs on SO, but the problem seems to be that it only accepts .js and .json files
Thanks to #Filipe's response, I got some guidance and got a working example that will fit your needs.
In my case, I had a .md file on the assets/markdown/ folder, the file is called test-1.md
The trick is to get a local url for the file, and then use the fetch API to get its content as a string.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Markdown from 'react-native-markdown-renderer';
const copy = `# h1 Heading 8-)
| Option | Description |
| ------ | ----------- |
| data | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext | extension to be used for dest files. |
`;
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
copy: copy
}
}
componentDidMount() {
this.fetchLocalFile();
}
fetchLocalFile = async () => {
let file = Expo.Asset.fromModule(require("./assets/markdown/test-1.md"))
await file.downloadAsync() // Optional, saves file into cache
file = await fetch(file.uri)
file = await file.text()
this.setState({copy: file});
}
render() {
return (
<Markdown>{this.state.copy}</Markdown>
);
}
}
EDIT: In order to get get rid of the error
Unable to resolve "./assets/markdown/test-1.md" from "App.js"
you would need to add the packagerOpts part of #Filipe's snippet into your app.json file.
app.json
{
"expo": {
...
"assetBundlePatterns": [
"**/*"
],
"packagerOpts": {
"assetExts": ["md"]
},
...
}
}
EDIT 2:
Answering to #Norfeldt's comment:
Although I use react-native init when working on my own projects, and I'm therefore not very familiar with Expo, I got this Expo Snack that might have some answers for you: https://snack.expo.io/Hk8Ghxoqm.
It won't work on the expo snack because of the issues reading non-JSON files, but you can test it locally if you wish.
Using file.downloadAsync() will prevent the app making XHR calls to a server where your file is hosted within that app session (as long as the user does not close and re-open the app).
If you change the file or modify the file (simulated with a call to Expo.FileSystem.writeAsStringAsync()), it should display the updated as long as your component re-renders and re-downloads the file.
This will happen every time your app is closed and re-open, as the file.localUri is not persisted per sessions as far as I'm concerned, so your app will always call file.downloadAsync() at least once every time it's opened. So you should have no problems displaying an updated file.
I also took some time to test the speed of using fetch versus using Expo.FileSystem.readAsStringAsync(), and they were on average the same. Often times Expo.FileSystem.readAsStringAsync was ~200 ms faster, but it 's not a deal breaker in my opinion.
I created three different methods for fetching the same file.
export default class MarkdownRenderer extends React.Component {
constructor(props) {
super(props)
this.state = {
copy: ""
}
}
componentDidMount() {
this.fetch()
}
fetch = () => {
if (this.state.copy) {
// Clear current state, then refetch data
this.setState({copy: ""}, this.fetch)
return;
}
let asset = Expo.Asset.fromModule(md)
const id = Math.floor(Math.random() * 100) % 40;
console.log(`[${id}] Started fetching data`, asset.localUri)
let start = new Date(), end;
const save = (res) => {
this.setState({copy: res})
let end = new Date();
console.info(`[${id}] Completed fetching data in ${(end - start) / 1000} seconds`)
}
// Using Expo.FileSystem.readAsStringAsync.
// Makes it a single asynchronous call, but must always use localUri
// Therefore, downloadAsync is required
let method1 = () => {
if (!asset.localUri) {
asset.downloadAsync().then(()=>{
Expo.FileSystem.readAsStringAsync(asset.localUri).then(save)
})
} else {
Expo.FileSystem.readAsStringAsync(asset.localUri).then(save)
}
}
// Use fetch ensuring the usage of a localUri
let method2 = () => {
if (!asset.localUri) {
asset.downloadAsync().then(()=>{
fetch(asset.localUri).then(res => res.text()).then(save)
})
} else {
fetch(asset.localUri).then(res => res.text()).then(save)
}
}
// Use fetch but using `asset.uri` (not the local file)
let method3 = () => {
fetch(asset.uri).then(res => res.text()).then(save)
}
// method1()
// method2()
method3()
}
changeText = () => {
let asset = Expo.Asset.fromModule(md)
Expo.FileSystem.writeAsStringAsync(asset.localUri, "Hello World");
}
render() {
return (
<ScrollView style={{maxHeight: "90%"}}>
<Button onPress={this.fetch} title="Refetch"/>
<Button onPress={this.changeText} title="Change Text"/>
<Markdown>{this.state.copy}</Markdown>
</ScrollView>
);
}
}
Just alternate between the three to see the difference in the logs.
From what I know, this cannot be done within expo. I use react-native and run it on my mobile for development.
react-native use Metro as the default bundler, which also suffers from similar problems. You have to use haul bundler instead.
npm install --save-dev haul
npx haul init
npx haul start --platform android
In a seperate terminal run react-native run-android. This would use haul instead of metro to bundle the files.
To add the markdown file, install raw-loader and edit the haul.config.js file. raw-loader imports any file as a string.
Customise your haul.config.js to look something like this:
import { createWebpackConfig } from "haul";
export default {
webpack: env => {
const config = createWebpackConfig({
entry: './index.js',
})(env);
config.module.rules.push({
test: /\.md$/,
use: 'raw-loader'
})
return config;
}
};
Now you can import the markdown file by using const example = require('./example.md')
Haul supports webpack configuration so you can add any custom babel transform you want.
I don't know exactly where the problem lies, but I added html files to the project, and I'd imagine it would be very similar.
Inside your app.json, try adding these fields:
"assetBundlePatterns": [
"assets/**",
],
"packagerOpts": {
"assetExts": ["md"]
},
The packagerOpts makes it so the standalone will bundle the .md files. I'd imagine you already have an assets folder, but just in case you don't, you will need one.
Then, on AppLoading, loading the assets with Asset.loadAsync might not be needed, but it's a good idea to rule out. Check out the documentation on how to use it.
When importing the file, there are three ways you might want to do so, that change depending on the environment. I'll copy this excerpt from my Medium article:
In the simulator, you can access any file in the project. Thus, source={require(./pathToFile.html)} works. However, when you build a standalone, it doesn’t work quite in the same way. I mean, at least for android it doesn’t. The android webView doesn’t recognise asset:/// uris for some reason. You have to get the file:/// path. Thankfully, that is very easy. The assets are bundled inside file:///android_asset (Careful, don’t write assets), and Expo.Asset.fromModule(require(‘./pathToFile.html')).localUri returns asset:///nameOfFile.html. But that’s not all. For the first few times, this uri will be correct. However, after a while, it changes into another file scheme, and can’t be accessed in the same way. Instead, you’ll have to access the localUri directly. Thus, the complete solution is:
/* Outside of return */
const { localUri } = Expo.Asset.fromModule(require('./pathToFile.html'));
/* On the webView */
source={
Platform.OS === ‘android’
? {
uri: localUri.includes('ExponentAsset')
? localUri
: ‘file:///android_asset/’ + localUri.substr(9),
}
: require(‘./pathToFile.html’)
}
(A constant part of the uri is ExponentAsset, that’s why I chose to check if that was part of it)
That should probably solve your problem. If it doesn't, comment what's going wrong and I'll try to help you further. Cheers!
If you want to load .md file with react-native cli (without expo). I've got a solution for you)
Add https://github.com/feats/babel-plugin-inline-import to your project
Add config .babelrc file with code inside:
{
"presets": ["module:metro-react-native-babel-preset"],
"plugins": [
[
"inline-import",
{
"extensions": [".md", ".txt"]
}
],
[
"module-resolver",
{
"root": ["./src"],
"alias": {}
}
]
]
}
Add to your metro.config.js such code
const metroDefault = require('metro-config/src/defaults/defaults.js');
...
resolver: {
sourceExts: metroDefault.sourceExts.concat(['md', 'txt']),
}
....
Reload your app

firebase get current project name react

Is there a way to retrieve the current project name that was activated through firebase use project-name? I've set up several projects in firebase as different environments. Since using the same codebase my problem is that the script doesn't know which configurations to use.
Found this related issue process.env.GCLOUD_PROJECT and according to docs it's automatically populated but only seems to return undefined.
So I have a config and using it like this;
const config = {
prod: {
apiKey: ...
},
stage: {
apiKey: ...
}
};
const config = process.env.ACTIVE_ENV === 'production' ? prodConfig : devConfig;
firebase.initializeApp(config);
What I'm trying to achieve is that when I run firebase use stage-proj it will populate the right config details and also for running firebase deploy.

Create unique instance of provider ionic 3

I am creating an Ionic app. I have 3 providers - database provider, portfolio provider and user provider. All 3 are Injectable. I have created it this way because several other pages need to use their function calls (i.e. they should not share the same data, they all should create new instances)
Both the portfolio and user provider import the database provider, as the need to make the same database calls to retrieve data.
I have 1 page - ViewPortfolio. The ViewPortfolio page imports the user provider (to know who the user is) and portfolio provider (to get the users portfolio data). For some reason, these 2 providers seem to be sharing the same instance for database provider. This is how I use them:
PORTFOLIO PROVIDER
import { DatabaseProvider } from '../providers/database-provider';
#Injectable()
#Component({
providers: [DatabaseProvider]
})
export class PortfolioProvider {
public portfolio_list: any = new BehaviorSubject<Array<string>>([]);
constructor(private dbProvider: DatabaseProvider) {
this.dbProvider.enableDataListener(this.protfolio_path); // set path
this.dbProvider.db_listener.subscribe(value => { // subscribe to data in the path
// do stuff
});
}
}
The user portfolio is the same, the only difference is the path its listening to is different.
However, when I change data in the portfolio path, the subscribe call is also triggered in the user path (and vice versa). Thus, even though I added DatabaseProvider in the components providers, its not creating unique instances. Why is this?
I figured it might be because I am importing them both on the same page but I am not convinced that's why it is not working. How do I make the 2 providers use unique instances on databaseprovider, while calling them both on the same page?
This is what my app.moudle.ts file looks like (please note that DatabaseProvider is not included in my app.module.ts file)
// ... more imports
import { PortfolioProvider } from '../providers/portfolio-provider';
import { UserProvider } from '../providers/user-provider';
#NgModule({
declarations: [
MyApp,
// ... more
],
imports: [
// ... more
IonicModule.forRoot(MyApp, {
backButtonText: '',
tabsPlacement: 'bottom'
}),
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
// ... more
],
providers: [
// ... more
PortfolioProvider,
UserProvider
]
})
export class AppModule {}
Thanks,
Did you remove the provider from app.module.ts (root AppModule)?
From the Angular Documentation:
Scenario: service isolation
While you could provide VillainsService in the root AppModule (that's where you'll find the HeroesService), that would make the VillainsService available everywhere in the application, including the Hero workflows.
If you generated the provider using ionic-cli, it'll automatically add it to the root AppModule.

Resources