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

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

Related

nuxt content link using slug not found

I am trying nuxt content module. I created a directory called "articles" inside content folder cotaining 2 md files with some dummy data. then, inside pages I have a folder called "tutorials" which contains "_slug.vue" and index.vue
the index page shows only the title of the articles and it works fine. every title links to
the actual article using path/slug. the problem is that I get page not found. here is my code:
index.vue:
<template>
<div>
<article v-for="article of articles" :key="article.id">
<nuxt-link :to="`/tutorials/${article.slug}`">
{{ article.slug }}
</nuxt-link>
</article>
</div>
</template>
<script>
export default {
async asyncData({ $content, params }) {
const articles = await $content('articles', params.slug)
.only(['title', 'slug'])
.sortBy('createdAt', 'asc')
.fetch()
return {
articles,
}
},
}
</script>
_slug.vue:
<template>
<div>
<nuxt-content :document="article" />
</div>
</template>
<script>
export default {
async asyncData({ $content, params }) {
const article = await $content('articles', params.slug).fetch()
return {
article,
}
},
}
</script>
<style></style>
thank you.

Can't upload multiple images in Django from react

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.

VueJS - V-for doesn't re-render after data is updated and needs page refresh to see the change

So this code does adds or delete an entry, But whenever I add or delete, it does not show the changes or rather re-render. I need to refresh the page in order to see what changes had.
note: I am using ME(Vue)N stack.
I have this code:
<script>
import postService from '../../postService';
export default {
name: 'postComponent',
data() {
return {
posts: [],
error: '',
text: ''
}
},
async created() {
try {
this.posts = await postService.getPosts();
}catch(e) {
this.error = e.message;
}
},
methods: {
async createPost() {
await postService.insertPost(this.text)
this.post = await postService.getPosts();
// alert(this.post,"---")
},
async deletePost(id) {
await postService.deletePost(id)
this.post = await postService.getPosts();
// alert(this.post)
}
}
}
</script>
<template>
<div class="container">
<h1>Latest Posts</h1>
<div class="create-post">
<label for="create-post">input...</label>
<input type="text" id="create-post" v-model="text" placeholder="Create a post">
<button v-on:click="createPost">Post</button>
</div>
<!-- CREATE POST HERE -->
<hr>
<p class="error" v-if="error">{{error}}</p>
<div class="posts-container">
<div class="post"
v-for="(post) in posts"
v-bind:key="post._id"
v-on:dblclick="deletePost(post._id)"
>
{{ `${post.createdAt.getDate()}/${post.createdAt.getMonth()}/${post.createdAt.getFullYear()}`}}
<p class="text">{{ post.username }}</p>
</div>
</div>
</div>
</template>
sorry if there's an error in the snippet. I just needed to show the code and I cant make the script work on the code sample {}.
Any help would be appreciate. Vuejs beginner here.
This code is copied and typed through a youtube tutorial.
Your component has a data property posts, but you're assigning to this.post in several places in the code.
I suspect a typo, but it's also worth remembering that if this additional property (this.post) isn't available when the component is instantiated, it won't be (magically) converted into a reactive property when you create/assign to it.

How to get data from firebase when page loading using vuejs?

I have been trying to get current user data from firebase to display details in profile page.
Here i am trying get data from firestore, when page loading. My table structure : users => Current user UID => email, firstname, lastname, businessname, etc.
I have added functionality to get data from firebase when profile page loading but does not work. error showing in console product.data().firstname is not function.
And also i did not get any console output firebase data retrieved or not?
here is my code:
<template>
<section class="what-we-do">
<div class="container-2" style="padding-top: 150px;">
<div class="row">
<div class="col-md-12">
<div class="saving-process-crd">
<div class="saving-process-inner">
<avatar :fullname="currentUser.email" size="96" >
</avatar>
<h4>Siva NSN</h4>
<h6 style="color:grey;">{{currentUser.email}}</h6><br><br>
<div class="card-columns" >
<div class="card" style="border: none; text-align: justify;">
<div class="card-body">
<h5 class="card-title">First Name:</h5><br>
<h5 class="card-title">Last Name:</h5><br>
<h5 class="card-title">Email ID:</h5><br>
</div>
</div>
<div class="card" style="border: none;">
<div class="card-body" style="float: left; text-align: left;" >
<h5 class="card-title">{{product.data().firstname}}</h5><br>
<h5 class="card-title">Mobility</h5><br>
<h5 class="card-title">{{currentUser.email}}</h5><br>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</template>
<script>
import Avatar from 'vue-avatar-component'
import database from '#/database'
import firebase from 'firebase/app'
export default {
name: 'Profile',
computed:{
currentUser (){
return this.$store.state.currentUser
}
},
components: {
Avatar
},
data () {
return {
profileData:{
email:null,
firstname:null,
lastname:null,
secondaryEmail:null,
businessName:null
}
}
},
methods:{
readData(){
const firestore = database.firestore();
firestore.collection('users').doc(firebase.auth().currentUser.uid).
onSnapshot(function(doc){
console.log('current data:', doc.data())
var newData = doc.data()
this.profileData.push(newData)
})
}
}
}
</script>
main.js code:
here i am i have user authstatechanges of current user.
import Vue from 'vue'
import App from './App.vue'
import router from './router';
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import './assets/styles//base-style.css';
import store from '#/store'
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
Vue.config.productionTip = false
let app
const initialize = () => {
if (!app) {
app = new Vue({
el: '#app',
router,
store,
render: h => h(App),
})
}
}
firebase.auth().onAuthStateChanged(user => {
if(user) {
store.commit('setCurrentUser', user)
} else {
store.commit('setCurrentUser', null)
}
initialize()
})
console output:
How to get data when page loading from firebase database. any help much appreicated pls..
There are number of things you have to adjust,
instead of fetching data using a method, try to add the code to a life cycle hook method, which will fire before you mount the data to dom, more precisely saying, use created lifecycle hook
https://vuejsexamples.net/vuejs-created/
Then you are populating the data to the template using currentUser which is taken from the vuex store,
return this.$store.state.currentUser, but in your firebase function you are setting the data you fetch to a data property which is profileData which is not used in the template.
You are pushing to profileData, but it's not an array it is a object and you cant push to an object.
So better flow is, fetch data using created lifecycle hook, then
either
store(mutate) the received data to the store.state.currentUser then it might work.
else update the profileData and replace the template with profileData instead of currentUser
Try this one,
Create a created lifecycle hook and move the firebase code to that. and assign the profileData object to the fetched Data.
created() {
const firestore = database.firestore();
firestore.collection('users').doc(firebase.auth().currentUser.uid).
onSnapshot(function(doc){
console.log('current data:', doc.data())
var newData = doc.data()
this.profileData = newData;
})
}
Then replace the currentUser in template to profileData.
ex : <h6 style="color:grey;">{{profileData.email}}</h6><br><br>

NoReverseMatch from url tag inside include tag

I am trying to render a link inside an include html template with the url tag.
I have done this before and usually it works, but for some reason this time I can't make it.
I get a NoReverseMatch Error and suspect its because Django tries to load the url tag first but my object isn't ready, so the pk is empty. I believe that because it takes a moment until the dynamic data loads, while the static is already loaded.
The url works if I set pk to a fixed number, but I would like it to change dynamically.
Error:
Reverse for 'transaction' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['en/budget/account\\/(?P<pk>[0-9]+)\\/$']
Relevant urls:
from django.urls import path
from django.contrib import admin
from django.contrib.auth import views as auth_views
from . import views
app_name='budgetapp'
urlpatterns = [
path('', views.index, name='index'),
path('account/<int:pk>/', views.transaction, name='transaction'),
path('account/', views.account, name='account'),
]
Relevant views:
from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.auth.models import Group
from django.contrib.auth.decorators import login_required, user_passes_test
from .models import *
from .forms import *
def index(request):
context = {}
context['accounts'] = Account.objects.filter(author=request.user)
return render(request, 'budgetapp/index.html', context)
def account(request):
context = {}
context['account'] = get_object_or_404(Account, pk = request.POST['accountPk'])
return render(request, 'budgetapp/account.html', context)
def transaction(request, pk):
context = {}
context['account'] = get_object_or_404(Account, pk = pk)
return render(request, 'budgetapp/addTransaction.html', context)
index.html:
{% csrf_token %}
<h1>Personal Budget</h1>
<br />
<p>
<label for="accountSelector">Account:</label>
<select required = "" id="accountSelector">
{% for account in accounts %}
<option value="{{account.pk}}">{{account}}</option>
{% endfor %}
</select>
</p>
<hr />
{% include 'budgetapp/account.html' %}
<script>
$(document).ready(function () {
reload();
});
$("#accountSelector").change(function () {
reload();
});
function reload() {
var dictionary = {}
dictionary['csrfmiddlewaretoken'] = $('input[name="csrfmiddlewaretoken"]').val();
dictionary['accountPk'] = $('#accountSelector').val();
$('#accountDiv').load("account/", dictionary);
console.log('Changed account');
}
</script>
account.html:
<div id="accountDiv">
<p>
Name: {{account.name}} Account balance: {{account.balance}} Add a transaction
</p>
</div>
If I change {% url 'budgetapp:transaction' pk=account.pk %} to /budget/account/{{account.pk}} it works, but that feels wrong.
I tried to provide all necessary code, but please let me know if it is to much or something is missing.
If you want to use {% url 'budgetapp:transaction' pk=account.pk %} then account must be in the template context. This has nothing to do with your browser dynamically loading data. The entire template is rendered by the server before the response is sent to the browser.
Using /budget/account/{{account.pk}} won't give an error, but if you look at the rendered HTML you'll see /budget/account/ since {{ account.pk }} will evaluate as ''.

Categories