Trouble retrieving data from REST endpoint using Angular -- URL keeps showing static/ - angularjs

I'm currently having an issue that has been driving me crazy for the past 30-40 mins. I've successfully created a products api using Django/Django REST framework. But when I call the endpoint to try and consume it with angular, I get a 404 error. When I open the console I am greeted with an error that states GET http://localhost:8000/static/api/products/ 404 (Not Found). However, when I navigate to the URL manually in browser I get the browsable api menu.
I'm not exactly sure what's going on here...but I'm thinking it could be because of my angular static URLs/roots.
Here is the current code for the main area URLs of the app:
from django.conf.urls import url,include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('customerreview_rest.urls', namespace='api')),
url(r'^api/',include ('products_rest.urls', namespace='api')),
url(r'^', include('GemStore_App.urls',namespace='frontend')),
] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)
Here is the products URL/root for the endpoint:
from django.conf.urls import url,include
from rest_framework import routers
from products_rest.viewsets import ProductsViewsets
router = routers.DefaultRouter()
router.register('products',ProductsViewsets,'products')
urlpatterns = [
url(r'^', include(router.urls)) #base router
]
Lastly, here is the code for the static angular files:
from django.conf.urls import url, include
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^$', RedirectView.as_view(url='static/index.html', permanent=False), name='index')
]
Here also, is the code I planed to use to consume the api using Angular:
myStore.controller("myStoreController",function($scope,$http){
$scope.gems = $http.get("api/products/").then(
function(response){
$scope.gems = response.data
}, function(error){
$scope.error = error
});
})
Any light that can be shed on this topic, or maybe a point in the right direction would be greatly appreciated.
Thanks

Turns out that the issue was that I needed to include a another / in my call in order for it to be accepted.
So in summary, the code for the angular portian looks like this now:
myStore.controller("myStoreController",function($scope,$http){
$scope.gems = $http.get("/api/products/").then(
function(response){
$scope.gems = response.data
}, function(error){
$scope.error = error
});
})
#Sayse Thanks for helping.

Related

I have problem in django's dynamic urls system

I have been following this other tutorial on youtube on build a project of some sort.its been days trying to find the solution to the problem
I tried using the 'str' and the 'int'
from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
path('products/', views.products),
path('customer/<int:my_id>/', views.customer),
]
this is my code in the views.py
def customer(request, my_id):
customer = Customer.objects.get(id=my_id)
orders = customer.order_set.all()
context = {'customer': customer, 'orders': orders}
return render(request, 'accounts/customer.htm', context)
please HELP

How to force Gatsby to redirect a specific URL path to an external site?

I have a Gatsby site and due to some specific requirements, I need to redirect anyone who attempts to hit a specific URL path, for which there is no page, to an external site. This URL path is not a page within the site, but it's something that a user may be inclined to type due to documentation that is out of my control.
Here's an example: Let's say the site is located at https://www.example.com. A user may visit https://www.example.com/puppies, which does not exist. My file structure does not contain a src/pages/puppies.js file. However, when that URL is entered, I need to redirect the user to another site altogether, such as https://www.stackoverflow.com.
I haven't used Gatsby to that extent to know it has a configuration for this, so someone else may correct me. The way I would handle this is through the hosting provider where your app is.
For example, if you are using Netlify:
Create a _redirects file with the following content:
/* /index.html 200
Or
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
This will cause all https://yourwebsite.com/IDontHaveThisRoute to fallback to /index.html where your .js is loaded.
I provided the Netlify example only to give you the basic idea of how it can be done through the hosting provider of your choice. I would look into configurations I can put into redirects where my domain is deployed.
Thanks to Paul Scanlon he mentioned using onRouteUpdate in Gatsby and it works like a charm
import { navigate } from 'gatsby';
export const onRouteUpdate = ({ location }) => {
if (location.pathname === '/dashboard') {
navigate('/dashboard/reports');
}
};
This question helped point me in the right direction. I was able to get it to work using Gatsby's componentDidMount() to force a redirect as shown below, using a new file called puppies.js to "catch" the path typed by the user:
// puppies.js
import React, { Component } from 'react'
class Puppies extends Component {
componentDidMount() {
window.location.replace("https://www.stackoverflow.com");
}
render() {
return <div />
}
}
export default Puppies

SharePoint SPFX: Unable to get property 'Context'

I'm working on a custom SPFX commandset. It opens a dialog with an iframe to an 3rth party platform. I'm able to receive a json through a postmessage. From this json, I convert it's data to a file, with it's proper metadata. All of this works like a charm... Except...
Now I want to upload this file to a document library, and it drives me crazy.
I'm referencing:
import "#pnp/polyfill-ie11";
import { ConsoleListener, Logger, LogLevel } from "#pnp/logging";
import { sp } from "#pnp/sp";
import { Web } from "#pnp/sp/webs";
import "#pnp/sp/webs";
import "#pnp/sp/files";
import "#pnp/sp/folders";
import { Base64 } from 'js-base64';
In my dialog component, I try to upload the file with web.getFolderByServerRelativeUrl. But this method is failing, and I really don't understand why.... Looking at the pnp reference (https://pnp.github.io/pnpjs/sp/files/), It seems like the right way.
var file = Base64.atob(response.Data);
console.log("File length : " + file.length);
let web = Web("https://MyTenant.sharepoint.com/sites/Customer"); // this is successful
await web.getFolderByServerRelativeUrl("/sites/Customer/Shared%20Documents/")
.files.add(response.fileName, file, true); // this fails
The context is set on the CommandSet onInit()
#override
public onInit(): Promise<void> {
Log.info(LOG_SOURCE, 'Initialized myCommandSet');
pnpSetup({
spfxContext: this.context
});
return Promise.resolve();
}
Hope you guys and girls can point me in the right direction...
EDIT:
Error:
HTTP400: INVALID REQUEST - The request could not be processed by the server
due to an invalid syntax
POST - https://MyDevTenant.sharepoint.com/sites/customer/
_api/web/getFolderByServerRelativeUrl
('%2Fsites%2Customer%2FShared%2520Documents%2F')
/files/add(overwrite=true,url='')
Is it the url from the documentlibrary that messes things up?
Thanks to Willman for giving me a right direction.
This did the trick:
import { sp, Web, IWeb } from "#pnp/sp/presets/all";
import "#pnp/sp/webs";
import "#pnp/sp/lists";
import "#pnp/sp/files";
import "#pnp/sp/folders";
const web = await sp.web();
const list = sp.web.getList("Documents");
const listId = await list.select("Id")();
await sp.web.lists.getById(listId.Id).rootFolder.files.add(docname, file, true);

Django adding letters and numbers to imageField url

I have an ImageField in a django model
image = models.ImageField(upload_to='images')
My media root is set like so in settings.py
MEDIA_ROOT = '/art/'
But when I upload select a gif url for the Imagefield, the url does not save as /art/images
I get this error message in Django Admin when I upload the url for the gif "Barnie.gif", which is stored at art/images/Barnie.gif
Art with ID "1/change/images/Barnie_L2fAl.gif" doesn't exist. Perhaps it was deleted?
I had the same problem. I solved it by adding the following imports:
from django.conf import settings
from django.conf.urls.static import static
I also added the following urlpatterns:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I wanted to try to get away with not doing all the config stuff, but you do have to do that.
In my base app urls.py I added:
from django.conf import settings
from django.conf.urls.static import static
and at the end of the urls list I added:
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then in my settings.py I added:
MEDIA_ROOT = os.path.join(BASE_DIR, '/art/images')
MEDIA_URL = '/images/'

403 Forbidden when trying to access API via DRF

I am trying to access a django server using django-rest-framework from angular using the following service:
myapp.factory("GetData", ["$resource",function($resource) {
return $resource(
"http://local/path/**/users/:username/",
{},
{
"query": {
method: "GET",
isArray: true,
headers:{
"Content-Type":"application/json"
}
}
},
{
stripTrailingSlashes:false
}
);
}]);
When I put the URL in the browser, I get the desired output, but the problem is that when I try to access via Angular, in my console I am getting a 403 forbidden error. Can anyone explain to me whats causing this. and how I can possibly fix this issue.
My url.py looks as follows:
from rest_framework.routers import DefaultRouter
from .views import UserViewSet
router = DefaultRouter()
router.register(prefix='users', viewset=UserViewSet)
urlpatterns = router.urls
My views.py file is as follows:
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework import viewsets
from .models import users
from .serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = users.objects.all()
serializer_class = UserSerializer
I think the 403 forbidden is coming to browser block cross origin requests.
You need to enable allow CORS at your API server by setting appropriate headers.
You can lookup https://github.com/ottoyiu/django-cors-headers
For this you need to add in your installed apps.
'corsheaders'
And just set to test it out. Check for fine tuned settings in the docs.
CORS_ORIGIN_ALLOW_ALL = True
Edit
Also you need to add this in your middlewares.
'corsheaders.middleware.CorsMiddleware',
I managed to fix the problem by combining what #Bipul Jain suggested https://stackoverflow.com/a/42044910/7210105 (above) and also altering this link in my $resource
"http://local/path/**/users/:username/"
I removed http://local/path from the link and the 403 forbidden error went away.

Resources