Can't upload multiple images in Django from react - javascript

Im sorry to ask this because there may be lot of tutorials for multiple file upload in django. but none of them clarified my doubts. Im new to Django please be patient with me.
Below is my django codes:
models.py
class Upload(models.Model):
file = models.FileField(upload_to='images/', default=False)
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('my_app.urls')),
]
urls.py
urlpatterns = [
path('image', UploadViewSet, name='image'),
]
views.py
class UploadViewSet(viewsets.ModelViewSet):
queryset = Upload.objects.all()
permission_classes = [
permissions.AllowAny
]
serializer_class = UploadSerializer
React
class Design extends Component {
state = {
file: null
}
handleFile(e) {
let file = e.target.files[0]
this.setState({ file: file })
}
handleUpload() {
let file = this.state.file
let formdata = new FormData()
formdata.append('images', file)
console.log('this one:', file)
axios({
url: "http://127.0.0.1:8000/image/",
method: "POST",
data: formdata,
}
).then(res => console.log(res))
}
render() {
return (
<div class="upload">
<h1>Upload Images</h1>
<br />
<br />
<Link to="/">
<button class="btn btn-warning">Back</button>
</Link>
<br />
<br />
<br />
<div className="d-flex p-4 z-depth-2">
<input type="file" multiple name="file" onChange={(e) => this.handleFile(e)} />
</div>
<br />
<br />
<br />
<button onClick={(e) => this.handleUpload(e)} class="btn btn-red">Upload</button>
</div>
);
}
}
export default Design; # <------sorry can't put this inside.
The images are successfully stored in images folder in django from react. but when i upload multiple files from react, django is receiving only one image.
please help me with some good solutions.
any solution is appreciable. Thank you in advance.

Related

ReactJS, Django , GraphQL - Uploading file

I am trying to upload a file in frontend and send the data to Django backend using graphql.
function Integrations() {
const [importTranscations] = useMutation(IMPORT_TRANSACTIONS);
function onChange({
target: {
validity,
files: [file],
},
}) {
if (validity.valid) {
importTranscations({ variables: { file } });
}
}
return (
<div
style={{
padding: "20px",
}}
>
<input type="file" required onChange={onChange} />
</div>
);
}
export default Integrations;
When I inspect the network tab and observe the graphql api call, I can observe that an empty object is being sent as 'file':
I have also added logs in the Django backend where I am using graphene-file-upload module. I am getting file as an empty Dictionary.
URLs:
from django.urls import path
from django.contrib import admin
from django.views.decorators.csrf import csrf_exempt
from graphene_file_upload.django import FileUploadGraphQLView
urlpatterns = [
path("admin/", admin.site.urls),
path("graphql/", csrf_exempt(FileUploadGraphQLView.as_view())),
]
Mutations:
import graphene
from graphene_file_upload.scalars import Upload
class ImportTransactionsMutation(graphene.Mutation):
class Arguments:
file = Upload(required=True)
task_id = graphene.String()
def mutate(self, info, file):
print("## DEBUGGING ## -> file", file)
task_id = "sample"
return ImportTransactionsMutation(task_id=task_id)
This is the output that I am seeing in the console:
## DEBUGGING ## -> file {}
Here is a link to codesandbox. You can open the network tab and check the graphql API.

Django and Vue: I keep geetting "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" in my website

I'm doing this project using Vue and Django, but when I run my code, I keep getting this error
"Failed to load resource: the server responded with a status of 500 (Internal Server Error)
127.0.0.1:8000/api/v1/products/winter/yellow-jacket-with-no-zipper:1"
I kept reloading and waited 30 minutes for this error to go away, but it keeps appearing.
I don't know if there is a problem in my javascript, because I don't have any errors when I run the vue project.
Here's my code I think has the problem.
Back end:
urls.py module in product package:
from django.urls import path, include
from product import views
urlpatterns = [
path('latest-products/', views.LatestProductsList.as_view()),
path('products/<slug:category_slug>/<slug:product_slug>', views.ProductDetail.as_view()),
]
Front end:
Product.vue script:
<template>
<div class="page-product">
<div class="columns is-multiline">
<div class="column is-9">
<figure class="image mb-6">
<img v-bind:src="product.get_image">
</figure>
<h1 class="title">{{ product.name }}</h1>
<p>{{ product.description }}</p>
</div>
<div class="column is-3">
<h2 class="subtitle">Information</h2>
<p>Price: <strong>{{ product.price }}</strong></p>
<div class="field has-addons mt-6">
<div class="control">
<input type="number" class="input" min="1" v-model="quantity">
</div>
<div class="control">
<a class="button is-dark">Add to Carts</a>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'Product',
data() {
return {
product: {},
quantity: 1
}
},
mounted() {
this.getProduct()
},
methods: {
getProduct() {
const category_slug = this.$route.params.category_slug
const product_slug = this.$route.params.product_slug
axios
.get(`/api/v1/products/${category_slug}/${product_slug}`)
.then(response => {
this.product = response.data
})
.catch(error => {
console.log("error")
})
}
}
}
</script>
Edit:
After some revision, I think the problem is caused by the views.py module in the product package
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Product
from .serializers import ProductSerializer
class LatestProductsList(APIView):
def get(self, request, format=None):
products = Product.objects.all()[0:4]
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
#I think its this line of code
class ProductDetail(APIView):
def get_object(self, category_slug, product_slug):
try:
return Product.objects.filter(category_slug=category_slug).get(slug=product_slug)
except Product.DoesNotExist:
raise Http404
def get(self, request, category_slug, product_slug, format=None):
product = self.get_object(category_slug, product_slug)
serializer = ProductSerializer(product)
return Response(serializer.data)
After revision of my code, I found out that I was right. The problem was the views.py module in the product package. It can be seen in the get_object function located in the ProductDetail class.
Original:
class ProductDetail(APIView):
def get_object(self, category_slug, product_slug):
try:
return Product.objects.filter(category_slug=category_slug).get(slug=product_slug)
except Product.DoesNotExist:
raise Http404
The problem was I needed to add another underscore/underline( this thing: _ ) when defining the category slug, so
category_slug=category_slug
becomes
category__slug=category_slug
New version:
class ProductDetail(APIView):
def get_object(self, category_slug, product_slug):
try:
return Product.objects.filter(category__slug=category_slug).get(slug=product_slug)
except Product.DoesNotExist:
raise Http404

What is the best way to use external JSON file data as a props for landing-section in different pages?

I am new to reactJS and I need an answer for this confusing problem.
I have a landing page that I want to use in my home and contact page. What I want is to send external JSON info as props to these pages and every time I create new page.
I have an external JSON file and I want to add it as a props to my landing page file
What is the best practice to do so, should I save within a state and send it as a props or send it directly as a props
JSON File:
{
"landing page" : {
"home": {
"id":1,
"image": "../media/video/Ai Motion5.mp4",
"title" : "MyAkbar for IT consultant & Services",
"description":"Boost up Your Works With our Services. My Incrediable Team is Here to Save Your Time and Money.",
"buttonOne": "Get A Demo"
},
"Contact" : {
"id":2,
"image": "../media/video/Ai Motion5.mp4",
"title" : "Contact",
"description":"sdadasdskdjaskljdas Team is Here to Save Your Time and Money.",
"buttonOne": "Get A Demo"
}
}
}
Home file:
import React, { Component } from 'react'
import LandingPage from "./landingPage/LandingPage"
import WaveSection from './waveSection/WaveSection'
import MyReview from "./reviewSection/MyReview"
import './styles/style.css'
import data from '../../json/data.json';
class Home extends Component{
render(){
return(
<div id='home' className='home'>
<LandingPage
title = {data['landing page'].home.title}
img = {data['landing page'].home.image}
description ={data['landing page'].home.description}
btn = {data['landing page'].home.buttonOne}
/>
<WaveSection/>
<MyReview/>
</div>
)
}
}
export default Home
Contact File:
import React, { Component } from 'react'
import video from '../../media/video/Ai Motion.mp4';
class Contact extends Component{
render(){
return(
<section className='contact-section landingPage-section'>
<div className="container">
<video autoPlay muted loop="True" id='myVideo' src={video}></video>
</div>
</section>
)
}
}
export default Contact
I will go with the first option (not storing it in state) as this data is static and the app does not modify it directly.

passing icons into a JS object

I have a js file with an array of objects, I am trying to load the attributes dynamically with a component and I cannot seem to figure out how to pass icons to the rendering component.
Here is the component that I am using to render the data:
import React, { Component } from 'react';
import SkillData from '../../store/skillData';
import './SkillsCard.css';
class SkillsCard extends Component {
state = { }
renderSkills = () =>
SkillData.map((skill, _id) =>
<div key={_id} className="skillCard col-sm-3 m-2">
<div className="top">
{/* ***line in question*** */}
<div className="icon">{skill.icon}</div>
<h5>{skill.title}</h5>
</div>
<div className="bottom">
{skill.techs.map((tech,index)=>(
<div className='skillCardList' key={index}> {tech}</div>
))}
</div>
</div>
);
render() {
return (
this.renderSkills()
);
}
}
export default SkillsCard;
and here is the file that I am pulling data from:
const SkillData = [
{
_id: '1',
icon: '../../assets/icons/frontend.png',
title: 'Front End',
techs: ['HTML5', 'CSS | SCSS', 'JavaScript', 'React | Redux', 'Angular']
},
{
_id: '2',
icon: '../../assets/icons/server.png',
title: 'Back End',
techs: ['NodeJS', 'Express', 'Postman', 'Authentication | Authorization']
},
{
_id: '3',
icon: '../../assets/icons/database.png',
title: 'Databases',
techs: ['MongoDB', 'mySQL', 'PostgreSQL']
}
]
export default SkillData
The issue that I am having is that I cannot get the path name to the icons to evaluate and actually render the icon; Instead my component renders the text, listed on the path. All the other attributes render just fine! Any thoughts?
Because you're just rendering the string value to the page:
<div className="icon">{skill.icon}</div>
Did you mean to use an <img> element?:
<div className="icon">
<img src={skill.icon} />
</div>
This worked when I added
const icons = require.context('../assets/icons', true);
in the SKillData.js file and set the paths to:
icons('./iconName.png'),
Thanks a million, David!
This works for me.
Direct require from your local assets folder, so you dont need the complexity to head file import a link from a json file request
{/* line in question */}
<div className="icon">
<img src={require(`${skill.icon}`)} />
</div>

Gatsby: Trying to get image path from front matter but getting this "TypeError: Cannot read property 'image' of undefined"

Im building a blog with Gatsby and I'm trying to display a hero image on each post page with the image path that is defined in each posts front matter. But, I'm getting this error from my hero component:
TypeError: Cannot read property 'image' of undefined
Here is my code:
Post front matter
---
path: /blog-post1
title: Blog Post 1
image: ../../images/blog-post-1.jpg
description: Blog post description
---
Hero.js
import React from 'react'
import Img from "gatsby-image";
const Hero = props => (
<section className="hero is-large">
<Img
fluid={props.frontmatter.image.childImageSharp.resize}
/>
<div className="hero-body">
</div>
</section>
);
export default Hero
Post.js
import React from 'react';
import { graphql } from 'gatsby';
import Layout from '../components/layout';
import Hero from '../components/hero';
const PostTemplate = ({ data }) => {
const { markdownRemark } = data;
const { frontmatter, html } = markdownRemark;
return (
<Layout>
<Hero headerImage={frontmatter.image} />
<section class="section">
<div className="container is-medium">
<div dangerouslySetInnerHTML={{__html: html}} />
</div>
</section>
</Layout>
)
}
export default PostTemplate;
export const pageQuery = graphql`
query($path: String!) {
markdownRemark(frontmatter: { path: { eq: $path } }) {
html
frontmatter {
date
path
title
description
image {
childImageSharp {
resize(width: 1500, height: 1500) {
src
}
fluid(maxWidth: 786) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`;
Any ideas on what's happening? Thanks in advance.
I am assuming you have data in frontmatter variable all the time. If you look at how you are calling Hero Component, where you are passing data as headerImage.
<Hero headerImage={frontmatter.image} />
If you look at Hero component you are reading it as frontmatter, You can do following changes and check.
You can add the condition to Img component to avoid the errors because of missing data.
{
props.headerImage && props.headerImage.image && props.headerImage.image.childImageSharp
<Img
fluid={props.headerImage.image.childImageSharp.resize}
/>
}
I figured out was the issue.
In my hero.js, I was calling the image using {props.frontmatter.image.childImageSharp.resize}
But in my post.js I was passing the data into the hero component like this <Hero headerImage={frontmatter.image} />
So, it was trying to find frontmatter.image.image, which doesn't exist. All I had to do was remove the .image like this <Img fluid={props.headerImage.childImageSharp.resize} />

Categories