I am new to Django and Django Rest Framework so I need some help.
I want to receive time data from my model in Django. If there is no time stored for a particular user, it should create it, save it in my model and return that time data. I am also using Simple-JWT for token authentication which means that no one can access the database without a valid token.
This is my code so far:
models.py:
class Mymodel(models.Model):
emp= models.ForeignKey(User, on_delete = models.CASCADE)
time = models.DateTimeField()
views.py:
def get_time(request):
if (request.method == 'GET'):
tk = request.GET.get('token') #token stored in LocalStorage
headers = {'Authorization': 'Bearer ' + tk}
url = 'http://127.0.0.1:8000/my_api/'
response = requests.get(url, headers)
if response:
user_id = User.objects.get(username=request.GET.get('username')).pk
user = User.objects.get(id = user_id)
if not Mymodel.objects.filter(emp=user).exists():
current_time = timezone.now()
create_time = Mymodel.objects.create(emp=user, time=current_time)
data = create_time.time
return HttpResponse(data)
class MyAPI(generics.ListAPIView):
permission_classes = [IsAuthenticated] #need to pass in JWT token in order to access the model.
serializer = MySerializer
def get_queryset(self):
user_id = User.objects.get(username=request.GET.get('username')).pk
user = User.objects.get(id = user_id)
user_data = Mymodel.objects.all()
queryset = user_data.filter(id=user_id)
return queryset
serializers.py:
class MySerializer(serializers.ModelSerializer):
class Meta:
model = Mymodel
fields = ('time')
I just want to read from my table and check whether if time is present for a user. If not, it should create time within the model. But, where am I going wrong? Did I pass in the Bearer token right and isn't the API structure correct? Thank you in advance!