Home > OS >  How to create an public endpoint (no authentication) where I just want to visualize the data in a ma
How to create an public endpoint (no authentication) where I just want to visualize the data in a ma

Time:06-24

May be an basic question about a creation of a new endpoint in DRF. I'm newbie in DRF and got stuck in a creation of an new endpoint that unauthenticated users could just GET the data, visualize.

My Django project is organized in three apps: core, user, and markers.

The app "markers" enable the authenticated users to create (POST...) geolocations and other information associated to the coordinates (name, coordinates, images...).

My challenge now is to create a new public endpoint to just visualize the data (in a map), created by the autheticated users.

I've created the map, inside "markers" folder and didn't have success in data visualization because of the authentication. Any clue or example how to enable the visualization? Thanks

GitHub repo https://github.com/silveiratcl/sun_coral_report_app

user model models.py:

class UserManager(BaseUserManager):

def create_user(self, email, password=None, **extra_fields):
    """Creates and saves a new User"""
    if not email:
        raise ValueError('User must have an email address')
    user = self.model(email=self.normalize_email(email), **extra_fields)
    user.set_password(password)
    user.save(using=self._db)

    return user

def create_superuser(self, email, password):
    """Creates and saves a new super user"""
    user = self.create_user(email, password)
    user.is_staff = True
    user.is_superuser = True
    user.save(using=self._db)

    return user

marker model models.py:

class Marker(models.Model):
"""A marker object."""
user = models.ForeignKey(
    settings.AUTH_USER_MODEL,
    on_delete = models.CASCADE,
)
name = models.CharField(max_length=255)
location = models.PointField()
image = models.ImageField(null=True, upload_to=marker_image_file_path) #image function

def __str__(self):
    """Return string representation."""
    return self.name

marker urls.py

from django.urls import(
    path,
    include,
)
from rest_framework.routers import DefaultRouter

from markers import views
from markers.views import MarkersMapView

router = DefaultRouter()
router.register('markers', views.MarkerViewSet)

app_name = 'markers'

urlpatterns = [
    path('', include(router.urls)),
    path('map/', MarkersMapView.as_view()),
] ```

project urls.py

from drf_spectacular.views import (
    SpectacularAPIView,
    SpectacularSwaggerView,
)
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'),
    path(
        'api/docs/',
        SpectacularSwaggerView.as_view(url_name='api-schema'),
        name='api-docs',
    ),
    path('api/user/', include('user.urls')),
    path('api/markers/', include('markers.urls')),
]

if settings.DEBUG:
    urlpatterns  = static(
        settings.MEDIA_URL,
        document_root=settings.MEDIA_ROOT,
    ) ```
**markers views.py**

markers views.py

    class MarkerViewSet(viewsets.ModelViewSet):
    """Marker view set."""

    bbox_filter_field = 'location'
    filter_backends = (filters.InBBoxFilter,)
    queryset = Marker.objects.all()
    serializer_class = MarkerSerializer
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """Retrieve markers for authenticated user"""
        return self.queryset.filter(user=self.request.user).order_by('-id')

    def get_serializer_class(self):
        """Return the serializer class for request"""
        if self.action == 'list':
            return serializers.MarkerSerializer
        elif self.action == 'upload_image':
            return serializers.MarkerImageSerializer #########

        return self.serializer_class

    def perform_create(self, serializer):
        """Create a new marker"""
        serializer.save(user=self.request.user)

    @action(methods=['POST'], detail=True, url_path='upload_image')
    def upload_image(self, request, pk=None):
        marker = self.get_object()
        serializer = self.get_serializer(marker, data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Reponse(serializer.data, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class MarkersMapView(TemplateView):
    """Markers map view."""

    template_name = 'map.html'

CodePudding user response:

Create a new view and do the following

if request.user != "AnonymousUser":
   #dosomething
else:
  Model.objects.all()

if it's an API view use self.request.user

it will respond with AnonymousUser or with user id

and pass it to the frontend

Hope this helps

CodePudding user response:

I'm not sure if I understand your question correctly, but this is what I'm hearing: You want unauthenticated users to be able to create Marker objects

If that's the case Make the end-point public, make the user attribute of your Marker class Nullible and whoever has access can create a marker

make end points public: https://techstream.org/Bits/Public-Endpoint-Django-Rest-Framework

  • Related