Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF verification failed request aborted in Django
I have a problem where when trying to log in or creating an account it shows a csrf token error. Everything works fine when I run my django project locally from my pc via manage.py runserver I uploaded my project to pythonanywhere and I get "CSRF verification failed request aborted" in django. Here's my: login html file {% load crispy_forms_tags %} {% block content %} <div class="w-50 mx-auto"> <h1 class="mt-5 text-center">Login</h1> {% if description %} <p class="lead">Login to your account/p> {% endif %} <form method="post"> {% csrf_token %} {{ form|crispy }} <div class="text-center"> <input type="submit" class="btn btn-warning btn-lg"> <p></p> <a class="btn btn-warning btn-lg" href={% url "password-reset" %}>Password reset</a> </div> </form> </div> {% endblock %} Middleware in settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] forms.py file class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') class Meta: model = CustomUser fields = ('username', 'email', 'password1', 'password2') class CustomUserChangeForm(UserChangeForm): def __init__(self, *args, **kwargs): super(CustomUserChangeForm, self).__init__(*args, **kwargs) del self.fields['password'] class Meta: model = CustomUser fields = ('username', 'email') class PasswordForm(ModelForm): class Meta: model = StoredPasswords fields = ['account'] and views.py file def home(request): return render(request, 'home.html', context={'title': 'Welcome to KPM'}) def about(request): return render(request, 'about.html', context={'title': 'about'}) def login(request): return render(request, … -
django-paypal IPN being received but signal not activating
I have a strange problem! Whenever I make a payment, everything goes through fine and paypal sends back the IPN signal like it should, and the IPN signal is added to the database. However this function valid_ipn_received.connect() does not receive the signal as my function doesn't run and nothing in the function prints. This is weird because I have pretty much used the same code from another project and everything worked fine there. Can anyone at least suggest a way to troubleshoot the valid_ipn_received.connect() function? def paypal_payment_received(sender, **kwargs): print("signal received") ipn_obj = sender order_number = ipn_obj.custom order = Order.objects.get(id=order_number) if ipn_obj.payment_status == ST_PP_COMPLETED: print("Paypal payment status: Completed") if ipn_obj.receiver_email != settings.PAYPAL_RECEIVER_EMAIL: return print("ipn_gross", float(ipn_obj.mc_gross)) print("cart total", float(order.get_total)) if ipn_obj.mc_gross == order.get_total: print("ipn amount is same as cart total") order.transaction_id = ipn_obj.invoice order.complete = True order.date_complete = timezone.now() order.save() print("transaction completed on db") try: send_order_emails(order) print("email sent") except: pass else: print('Paypal payment status not completed: %s' % ipn_obj.payment_status) valid_ipn_received.connect(paypal_payment_received) urls.py url('paypal/', include('paypal.standard.ipn.urls')), path('paypal-return/', views.paypal_return, name='paypal-return'), path('paypal-cancel/', views.paypal_cancel, name='paypal-cancel'), settings.py INSTALLED_APPS = [ ... 'paypal.standard.ipn', ... ] -
Django's SessionAuthentication don't working
I want to use SessionAuthentication but enough documentation or clear explanation is absent. I know about this but it no has answer for my question, so i need help. urls.py from rest_framework import routers from accounts.views.user import AuthViewSet router = routers.DefaultRouter(trailing_slash=False) router.register('', AuthViewSet, basename='auth') account_urlpatterns = router.urls part of views/user.py User = get_user_model() class AuthViewSet(viewsets.GenericViewSet): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = [AllowAny, ] serializer_class = (EmptySerializer, ) serializer_classes = { 'login': UserLoginSerializer, 'registration': UserRegisterSerializer, 'passwd_change': PasswordChangeSerializer } queryset = User.objects.all() @action(methods=['POST', ], detail=False) def login(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = get_and_authenticate_user(**serializer.validated_data) data = AuthUserSerializer(user).data login(request, user, 'rest_framework.authentication.SessionAuthentication') return Response(data=data, status=status.HTTP_200_OK) @action(methods=['POST', ], detail=False) def registration(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = create_user_account(**serializer.validated_data) data = AuthUserSerializer(user).data login(request, user, 'rest_framework.authentication.SessionAuthentication') return Response(data=data, status=status.HTTP_200_OK) @action(methods=['POST', ], detail=False, permission_classes=[IsAuthenticated, ]) def logout(self, request): logout(request) data = {'success': 'Sucessfully logged out'} return Response(data=data, status=status.HTTP_200_OK) @action(methods=['POST'], detail=False, permission_classes=[IsAuthenticated, ]) def passwd_change(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) request.user.set_password(serializer.validated_data['new_password']) request.user.save() return Response(status=status.HTTP_204_NO_CONTENT) serializers/login.py from rest_framework import serializers class UserLoginSerializer(serializers.Serializer): username = None email = serializers.CharField(max_length=150, required=True) password = serializers.CharField(required=True, write_only=True) serializers/password.py from rest_framework import serializers from django.contrib.auth import password_validation class PasswordChangeSerializer(serializers.Serializer): current_password = serializers.CharField(required=True, max_length=128) new_password = serializers.CharField(required=True, max_length=128) i open http://127.0.0.1:8000/api/accounts/login enter login and … -
django form.is_valid() is always false even when correct information has been fed
This is my ModelForm: class registerForm(forms.ModelForm): class Meta: model = User fields = ['branch', 'year'] These two are the fields i have added in my model User(I have given them with choices): class User(AbstractBaseUser): #other fields YEAR_CHOICES = ( ('1', 1), ('2', 2), ('3', 3), ('4', 4) ) year = models.IntegerField(choices=YEAR_CHOICES, default=1) Branch_CHOICES = ( ('1', 'CSE'), ('2', 'ECE'), ('3', 'IT') ) branch = models.CharField(max_length=3, choices=Branch_CHOICES, default="CSE") but in my views: form = registerForm(request.POST) if form.is_valid(): branch = form.cleaned_data['branch'] year = form.cleaned_data['year'] else: return render(request, "events/register.html", { "message": "You didn't provide all the fields", "form": registerForm() }) it always returns the error message. Can someone please help me understand what's going wrong here? -
Django occasionally returning empty querysets
Here’s a problem that I’ve been trying to fix for a few days now: I have Django application that exposes data through a REST API, using a Postgres database. In production, the API sometimes returns empty data. To narrow down the problem, I added some logging. As it turns out, Django returns empty querysets (even though there is data), a minute later, the data is returned properly. Some hints on what may go wrong: I haven’t been able to reproduce the issue in my development setup Some (but not all) of the failing queries use queryset.union() Postgres doesn’t report any errors/warnings With Django set to debug SQL queries, the queries look fine Both Django app and Postgres DB are “dockerized”, running on Ubuntu hosts The issue occurs on all production hosts There are no special database settings Can you spot anything susceptible? Has anyone experienced a similar situation? Thanks! Any help is appreciated. PS: Here‘s an example query: FILTER_KWARGS_PUBLIC = { 'status': APPROVED, 'visibility': PUBLIC, } def collect_pieces(self, public_only=False) -> QuerySet: """ Collect pieces that have been added directly or through relation """ filter_kwargs = {} if public_only: filter_kwargs = self.FILTER_KWARGS_PUBLIC piece_ids = self.performances_relation.filter(**filter_kwargs).values_list('piece__pk', flat=True) q1 = Piece.objects.filter(pk__in=piece_ids, **filter_kwargs) queryset … -
When I try to run migrations this error comes please help me guys
actually when I[this is the error![settings.py (installed appsauth user models settings try to run migrations this error comes I don't know why this is happening please help me guys -
Table not displaying for Django when debugging
I have defined models and views and I would like to display a table existing from database. However the script is not displaying any content. Where's the problem? Please take a look into definition of model, views and my home html file trying to display table from database. model from django.db import models class Patient(models.Model): Last_name=models.CharField(max_length=200) First_name=models.CharField(max_length=200) Contact=models.IntegerField() Street=models.CharField(max_length=200) House=models.IntegerField() City=models.CharField(max_length=200) Age=models.IntegerField() DoB=models.CharField(max_length=10) Vaccine=models.CharField(max_length=100) def __str__(self): return self.Last_name views from django.shortcuts import render from .models import Patient def home(request): patient = Patient.objects.all() return render(request, 'vaccinated/home.html', {'patient': patient,}) home.html {% extends 'vaccinated/base.html' %} {% block content %} <div class="table-responsive"> <table class="table table-striped table-hover"> <thead> <tr> <th>Last Name</th> <th>First Name</th> <th>Contact No.</th> <th>Street</th> <th>House No.</th> <th>City</th> <th>Age</th> <th>Date of Birth</th> <th>Vaccine Name</th> </tr> </thead> <tbody> {% for patient in patients %} <tr> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.Last_name}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.First_name}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.Contact}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.Street}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.House}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.City}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.Age}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.DoB}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" … -
Django Rest Framework API , calling get_queryset twice
I am working on an API, where on receiving a request, I will create a few records and then return the result. All this is working as expected but get_queryset is being called twice and the object gets created twice. The statment print("create quiz") is executed twice. What am I doing wrong? Any help please. class CreateQuiz(generics.ListCreateAPIView): serializer_class = QuizSerializer def get_queryset(self): classId = self.kwargs.get('classId',None) subject = self.kwargs.get('subject',None) category = Category.objects.filter(class_id=classId,category=subject).values_list('id',flat=True)[0] subcategory=self.kwargs.get('chapter',None) total_marks = 30 questionIDs = Question.objects.raw('''somesql''',params=[category,subcategory,total_marks,category,subcategory,total_marks]) questions= MCQuestion.objects.filter(question_ptr_id__in=questionIDs).prefetch_related('answer_set__question') essayquestions= Essay_Question.objects.filter(question_ptr_id__in=questionIDs) user = User.objects.get(id=1) if MCQuestion.objects.filter(question_ptr_id__in=questionIDs).prefetch_related('answer_set__question').exists(): print("create quiz") quiztitle ="Practice" quiz = Quiz() quiz.category_id = category quiz.title = quiztitle quiz.owner= user quiz.single_attempt = False quiz.durationtest="10:00" quiz.random_order=True subcatdescr = SubCategory.objects.filter(id=subcategory).values_list('sub_category',flat=True)[0] subcatprint=" " if subcatprint==" ": subcatprint = subcatdescr else: subcatprint = subcatprint+" , "+subcatdescr quiz.title = "Practice Exam : "+ quiz.category.class_id.classVal +" "+quiz.category.category +" ("+subcatprint+") " quiz.save() quizid = Quiz.objects.filter(id=quiz.id).values_list('id',flat=True)[0] try: with connection.cursor() as cursor: cursor.execute("INSERT INTO quiz_subcategory_quiz(subcategory_id,quiz_id) VALUES (%s,%s)",(subcategory,quiz.id,)) except Exception: print("Did not create quiz subcategory") category_description = Category.objects.filter(id=category) for obj in questionIDs: print(quiz.id) with connection.cursor() as questioncursor: questioncursor.execute("INSERT INTO quiz_question_quiz(question_id,quiz_id) VALUES (%s,%s)",(obj.id,quiz.id,)) else: response = JsonResponse({"error": "there was an error"}) response.status_code = 403 # To announce that the user isn't allowed to publish return Quiz.objects.filter(id=quizid) -
TypeError at ecommerceapp NoneType object is not iterable
This is the code can you help me? enter image description here -
how to restrict a user to a page conditionally in Django
I wanna ask u about pages with Django and JavaScipt. Imagine that the web app has two pages page1.html y page2.html, so ... the thing that I want is to denied/restrict to the user to access directly from the URL to the page2.html. This page have to be accessed just with a button and not with another way. The page is not a child page. I wanna do it with JavaScript, but I don't know if it's possible. Please someone can help me? -
Sorting dictionary in django model using json field
I am trying to store a dictionary in my Django project as a model. The model is present but it wont update the values. any ideas? model.py: class MyModel(models.Model): jsonM = JSONField() Main.py: myList = [1,2,3,4,5,6,7,8,9] print("this is my model") MyModel.objects.all().update(jsonM=myList) When i do: print(MyModel.objects.all()) print(type(MyModel.objects.all())) I get the following: <QuerySet []> <class 'django.db.models.query.QuerySet'> -
How to decrease the lenght of the token in django_rest_passwordreset
settings.py Putting these does not work, it keeps on sending 50 digit code,Do i have to put somthing in this code, please help "CLASS": "django_rest_passwordreset.tokens.RandomNumberTokenGenerator", "OPTIONS": { "min_number": 4, "max_number": 5, } }``` ### models.py ### Do i have to put somthing in this code, please help ```@receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): email_plaintext_message ="Your-One-Time-OTP is {}".format(reset_password_token.key) # "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key) send_mail( # title: "Password Reset for {title}".format(title="Tag On Account"), # message: email_plaintext_message, # from: "noreply@somehost.local", # to: [reset_password_token.user.email] ) }``` -
Django - how to manage variables inside a translation block?
I have the following paragraph at my django template I want to translate: <p>Hello and welcome to {{ settings.SITE_NAME }}, nice to meet you</p> How can I process the SITE_NAME variable at my .po file? -
Uncaught TypeError: $.ajax is not a function | Updating dropdowns based on Django model
I have a problem when trying to update my dropdown (<select> element) based on Django model triggered by another dropdown (let's call it A) change. I followed this tutorial: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html When I change the dropdown A, I get the following error: Uncaught TypeError: $.ajax is not a function Based on similar questions I made sure that I include this line before my script: <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script> and I'm not using the slim version of jquery. Here is the part of my HTML code of my dropdown A and JS that is responsible for updating the second dropdown. <select id="my-selection" dropdown-data-url="{% url 'ajax_get_data' %}"> <option value="1">First Option</option> <option value="2">Second Option</option> </select> <script> $(document).ready(function() { $("#my-selection").change(function () { var url = $("#my-selection").attr("dropdown-data-url"); // get the url of the proper view var my_selection = $(this).val(); // get the selected input from dropdown $.ajax({ url: url, data: { 'selection': my_selection // add selected option to the GET parameters }, success: function (data) { $("#second-dropdown-selection").html(data); } }); }); }); </script> I will be grateful for any suggestions. -
How to sync postgres database with neo4j in realtime while using Django-admin?
So currently I am working on a Django project where I have two different databases. one is PostgreSQL and the second is Neo4j. what I want is real-time sync between both databases. I am using the Django-admin panel for crud operation in the Postgres database. now I want every crud operation update in the neo4j database also. but I don't know how to do it. -
How to access foreign key of child table in Django views and if there is no relation than store 0 in foreign key
1] I want access foreign key of child table how to access it inside view for example in models.py class Test(models.Model): answer = models.ForeignKey(Answers,on_delete=models.PROTECT) class Answers(models.Model): chapter_name = models.ForeignKey(Chapter,on_delete=models.PROTECT) class Chapter(models.Model): lesson_name = models.CharField(max_length=200) in my views.py def test(request): test_data = Test() chapter_name = #How to access chapter name 2] How to store 0 if user selects other option in form if user selects test-1 than id will be 1 or any number but if user will select other option than it should store 0 in foreign key field how to do that -
djnago-admine startproject pyshop doen't work whith me
django-admin : Le terme «django-admin» n'est pas reconnu comme nom d'applet de commande, fonction, fichier de script ou programme exécutable. Vérifiez l'orthographe du nom, ou si un chemin d'accès existe, vérifiez que le chemin d'accès est correct et réessayez. Au caractère Ligne:1 : 1 django-admin startproject pyshop everytime i use djnago-admin startproject i get this msg -
Django: complex order by query with nested models
I have following 3 models from django.db.models import Max from django.utils import timezone class Product(models.Model): name = models.CharField( blank=False, max_length=256 ) class TaskGroup(models.Model): name = models.CharField( blank=False, max_length=256 ) product = models.ForeignKey( Product, on_delete=models.CASCADE, null=False, blank=True ) class Task(models.Model): name = models.CharField( blank=False, max_length=256 ) task_group = models.ForeignKey( TaskGroup, on_delete=models.CASCADE, null=False, blank=True ) execute_at = models.DateField( blank=True null=True, ) I can order the products by Task execute_at date. Products.objects.annotate( last_task=Max('taskgroup__task__execute_at') ).order_by('-last_task') However, I need to consider only the first date that is greater than today i.e I need something like Products.objects.annotate( last_task=('taskgroup__task__execute_at' >= timezone.now()).first() ).order_by('last_task') How can I do this? It would be nice to do it in a single query. -
How do i integrate Django - Tenant with Django Haystack
I'm currently using Django-tenant package that provides the Multi-Tenancy based on different Schemas, I'm also using django-haystack with ElasticSearch in BackEnd for Searching, I need some help to figure how to index records for different schemas with ElasticSearch, what approach should I follow, and is it even possible by using django-haystack. -
hi i am avik , i am working with some django project but i am facing problems in uploading files to a particular directory, i am stuck with it
i am using a html template to upload a file but i don't know how to process that file in django views file i also have a model which is connected with the database here is my html file {% extends 'base.html' %} {% block body %} <form action="file" method="post" enctype="multipart/form-data" > {% csrf_token %} <input type="text" name="userName" placeholder="username"> <input name="file" type="file"> <input type="submit" value="submit"> </form> {% for message in messages %} {{ message }} {%endfor%} {% endblock %} and here is my views.py function def File(request): if request.user.is_authenticated: if request.method == 'POST': user = request.POST['userName'] file = request.FILES print(file) # file = request.POST.copy() # file.update(request.FILES) # content_type = copied_data['file'].get('content-type') # path = os.path.join(r'C:\Users\harsh\PycharmProjects\swatchBharat\SwatchBharat\media\files\\',file) if User.objects.filter(username=user).exists(): file2 = points() file_obj1 = DjangoFile(open(file, mode='rb'), name=file) file_obj = File.objects.create(title=file, file=file_obj1, content_object=file, author=file.client) file2.file =file2.save(ContentFile(file_obj)) file2.user = user file2.save() return HttpResponse('sucess bale bale!!!!!!!') else: messages.info(request,'the username you entered is incorrect') return redirect("file") return render(request, 'file.html') else: return HttpResponse('sorry this is restricted, login to continue') my model.py file from django.db import models # Create your models here. class points(models.Model): user = models.TextField(max_length=50,default=None) file = models.FileField(upload_to='files/') point_3 = models.BooleanField(default=False) point_5 = models.BooleanField(default=False) point_9 = models.BooleanField(default=False) i am stuck with it pls someone help me out -
How to get the db id/pk of the returned querysets?
I have a model query that returns the max value for each day in the database, but it only returns the date and the count. I'm in need of the id/pk in the database, but i'm not sure how to gather it. from django.db import connection from datetime import datetime, timedelta, date def query(request): test = NetworkStats.objects.extra(select={'day': connection.ops.date_trunc_sql( 'day', 'date')}).values('day').annotate(online=Max('online')) for obj in test: print(obj) The above code prints out the following: {'day': datetime.datetime(2021, 4, 22, 0, 0, tzinfo=), 'online': 485} {'day': datetime.datetime(2021, 4, 23, 0, 0, tzinfo=), 'online': 466} But I specifically need the id/pk of these values returned. How can I achieve this? -
line 20, in init eng = _activeEngines[driverName]
--I'm doing a voice assistant in python but when I run the program, this wrong appears --this is my code, I have pyttsx3 and pyaudio import pyttsx3 engine = pyttsx3.init() engine.setProperty("rate", 150) text ="Hola a todos" engine.say(text) -
Typeahead returning object count instead of selectable strings in Django
I am trying to implement typeahead.js for my application. I followed through with some of the following examples stackoverflow and Twitter typeahead official doc. I created a Django Rest API which works perfectly well, I have also been able to get the typeahead to pop up suggestions. After all these, I am faced with two difficulties that I have been unable to resolve on my own. The first is that instead of showing string results, the script is returning total object count , while the second problem is that the pop-up suggestion is not selectable. Is there a way to solve these issues? main.js //live search $(document).ready(function(){ var recruitmentLeadsSearchResults = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('lead'), queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: '../auth/api/data/', remote: { url: "/auth/api/data/", wildcard: '%QUERY', } }); $('.typeahead').typeahead(null, { name: 'leads-display', display: 'lead', source: recruitmentLeadsSearchResults, templates: { empty: [ '<div class="empty-message">', 'No user found', '</div>' ].join('\n'), suggestion: function(data){ return '<div class="live-search-results">' + '<strong>' + data + '</strong>' + '</div>'; } } } ); }); views.py @require_http_methods(['GET']) def search_team_lead_ajax(request): lead = request.GET.get('lead') data = {} if lead: leads = Board.objects.filter(lead__first_name__icontains=lead) data = [{'lead': lead} for lead in leads] return JsonResponse(data, safe=False) -
Django Rest Framework using custom mixin with ApiView not working
I have a Class Based View that inherits from ApiView with a get and post function. I wrote a custom mixin to add the functionality for the post request to accept both a list of objects and also a single object. When I make the class inherit the mixin nothing happens class CreateListModelMixin: def get_serializer(self, *args, **kwargs): """ if an array is passed, set serializer to many """ if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super(CreateListModelMixin, self).get_serializer(*args, **kwargs) class User_ListView(APIView, CreateListModelMixin): permission_classes = [DjangoCustomModelPermissions] queryset = User.objects.none() # TO define a dummy queryset for the purpose of the above permission class def get(self): db_data = User.objects.all().prefetch_related("installation_mast") serializer = User_Serializer(db_data, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = User_Serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The get_serializer method of the mixin is not being called. Any help will be appreciated -
react js axios not showing images from django rest api
i have build the api and fetching. all the data are stored in database ,everything except image is showing and fetching but images are not. pls see the code models class Category2_products(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(default=0) image = models.ImageField(upload_to='products') description = models.TextField() delivery = models.CharField(max_length=30) key_point1 = models.CharField(max_length=70,blank=True) key_point2 = models.CharField(max_length=70,blank=True) key_point3 = models.CharField(max_length=70,blank=True) key_point4 = models.CharField(max_length=70,blank=True) key_point5 = models.CharField(max_length=70,blank=True) key_point6 = models.CharField(max_length=70,blank=True) key_point7 = models.CharField(max_length=70,blank=True) key_point8 = models.CharField(max_length=70,blank=True) key_point9 = models.CharField(max_length=70,blank=True) def __str__(self): return f'{self.name}' serializers class Category1_Api(serializers.ModelSerializer): class Meta: model = Category1_products fields = '__all__' views.py class Category1_data(APIView): def get(self,request): model_data = Category1_products.objects.all() serializers = Category1_Api(model_data, many=True) return Response(serializers.data) Cat1.js function Cat1() { const [Cat1,setCat1] = useState([]) useEffect(() => { axios.get('http://127.0.0.1:8000/category/1/api').then(e => { console.log(e.data) setCat1(e.data) }) }, []) const Cat1_map = Cat1.map(e => { return( <div> <div className="object_cat1"> <img src={e.image.urls} alt="" id='cat1_product_img'/> <div className="cat1_text"> <p className="cat1_product_name">{e.name}</p> <Link id='cat1_product_link'>View</Link> </div> </div> </div> ) }) i hope you can help me