Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PUT or PUSH for modifying the existing data?
I have viewset, class CompanyViewSet(viewsets.ModelViewSet): serializer_class = s.CompanySerializer queryset = m.Company.objects.all() Which shows the view on /api/companys There is a button for POST I can add the new data from this form. Now I want to modify the existing data. I have basic questions. PUSH can modify the data? or PUT should be implemented? How PUT can be implemented for ModelViewSet? -
Custom django permissions for group chats?
I have a custom group model like this: class MyGroup(models.Model): name = models.CharField(max_length=200,null=True,blank=False,default="Group name") members = models.ManyToManyField(get_user_model(), blank=True, related_name="grpmembers") created_by = models.ForeignKey(get_user_model(), on_delete=models.DO_NOTHING, null=True, blank=False, related_name="createdby+") created_at = models.DateTimeField(editable=False) It works, it's fine, I override the save method in django admin so the created_by will point to the logged in user on save. Problem #1 Even if you are the creator of the group, you can select yourself to either be in- or be removed from the group which kinda looks silly. I'm thinking of solving this by saying the user can view the group if they're in members or created_by. Problem #2 Custom permission. I want to have some permissions, like: Can view the group: which means the user is either the creator or is in the members list Can edit the group: which means the user is the creator(can edit their own) or is staff(can edit anyone's stuff) or is superuser(root) I can write it down and imagine how it would work, but I have no idea how to implement these. I've found some ways, like creating a Meta and defining permissions there and also making the permissions as def(/functions), but how could I access the currently logged … -
How to do right model for tree-based view?
I need to make tree of employees fro database. If i have this model: class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) hired_at = models.DateField(auto_now=True) salary = models.DecimalField(max_digits = 9, decimal_places= 2) boss = models.ForeignKey('self', null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return f'<{self.pk}> {self.name} - {self.position}' Can I iterate in template and make tree-based structure or I need another configuration of my Model? -
Django join fields in queryset
Is it possible to join common fields in different queryset. I have day_name = Monday in two queryset. I want to combine it into one. The reason i wanted to do it because when mapping it on frontend react. I want to see only one Monday , not two mondays. [ { "day__day_name": "Monday", "subject_name__subject_name": "Maths" }, { "day__day_name": "Monday", "subject_name__subject_name": "English" } ] I want to join these both "Monday" so that i can only return it as one "Monday" instead of two or more -
How to save a field from another model to a variable NOT A FIELD
I have a model called Actual: # Actual parts table class Actual(models.Model): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, verbose_name="Vendor name", related_name="actualvendor") number = models.CharField("External part number", max_length=32, unique=True, blank=True, null=True) description = models.CharField(max_length=64, blank=True) pq = models.DecimalField(max_digits=7, decimal_places=2, default=1) mrrp = models.DecimalField(max_digits=10, decimal_places=2) # Model metadata class Meta: unique_together = ["vendor", "number"] verbose_name_plural = "actual external parts" # Display below in admin def __str__(self): return f"{self.number}" I also have another model called Offer: class Offer(models.Model): sync_id = models.ForeignKey(Sync, on_delete=models.CASCADE, verbose_name="Internal part number", related_name="part") discount = models.DecimalField(max_digits=3, decimal_places=2, default=0) moq = models.DecimalField(max_digits=4, decimal_places=2, default=1) status = models.CharField(max_length=20, choices=OFFERSTATUS_CHOICES, default=1) actual = models.OneToOneField(Actual, on_delete=models.CASCADE) # Display something in admin def __str__(self): return f"Offer {self.id} for {self.sync_id}" # Calculate the price def price(self): return self.actual.mrrp * (1-self.discount) I am trying to calculate the 'price' using 'mrp' But 'mrrp' is from another model. I am able to do so with the code I've attached but as you can see in the django admin, the 'actual' shows up as a field. First, I do not need it to be a field. I only need 'Actual' to be a variable that stores the value of 'mrrp'. Second, I want it to auto-select the corresponding value based on the … -
Get mime type of InMemoryUploadedFile without extention in Python
I'm trying to get the mime type of for example a InMemoryUploadedFile JavaScript file without knowing the file extention in Python Currently i check my InMemoryUploadedFile with in_memory_file.content_type which returns application/octet-stream for a JavaScript file after that i use the Magic lib magic.Magic(mime=True).from_buffer(in_memory_file.read()) Which returns text/plain. When uploading a file that contains the .js extention i'm getting the right mime type "text/javascript" -
How to refer a html file in templates subdirectory in <a href='url' tag in Django html template
I am quite new to django, the below is my project templates folder structure templates index.html about.html contact.html \student index.html \Attendance attendance.html .... \Exams results.html exam1.html ..... \Misc \teachers index.html \hrms adminlogin.html payslip.html principallogin.html .... .... urs.py: urlpatterns = [ path('admin/', admin.site.urls), path("",home,name="home"), views.py: def home(request): return render(request, 'index.html') till now this is working fine, if I index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="u-custom-menu u-nav-container"> <ul class="u-nav u-spacing-30 u-unstyled u-nav-1"><li class="u-nav-item"><a class="u-border-0 u-border-no-bottom u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-text-active-palette-1-base u-text-grey-90 u-text-hover-palette-1-base" href="{% url 'home' %}" style="padding: 20px 5px;">Home</a> </li><li class="u-nav-item"><a class="u-border-0 u-border-no-bottom u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-text-active-palette-1-base u-text-grey-90 u-text-hover-palette-1-base" href="about.html" style="padding: 20px 5px;">About</a> </li><li class="u-nav-item"><a class="u-border-0 u-border-no-bottom u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-text-active-palette-1-base u-text-grey-90 u-text-hover-palette-1-base" href="contact.html" style="padding: 20px 5px;">Contact</a> </li><li class="u-nav-item"><a class="u-border-0 u-border-no-bottom u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-text-active-palette-1-base u-text-grey-90 u-text-hover-palette-1-base" href="" style="padding: 20px 5px;">Login</a> <div class="level-2 u-nav-popup u-white u-nav-popup-1"> <ul class="u-h-spacing-20 u-nav u-popupmenu-items u-unstyled u-v-spacing-10 u-nav-2"> <li class="u-nav-item"><a class="u-button-style u-nav-link" href="/hrms/adminlogin.html">Administrator</a></li> <li class="u-nav-item"><a class="u-button-style u-nav-link" href="/hrms/mangementlogin.html">Management</a></li> <li class="u-nav-item"><a class="u-button-style u-nav-link" href="/hrms/principallogin.html">Principal</a></li> <li class="u-nav-item"><a class="u-button-style u-nav-link" href="/teacher/index.html">Teacher</a></li> <li class="u-nav-item"><a class="u-button-style u-nav-link" href="/student/index.html">Student</a></li> </ul> </div> </li> </ul> </div> </body> </html> We are getting the following error message when we run the project, need help … -
POST request works or not depending on user login, Django REST framework
Django and django REST framework. From template javascript, I make new database entry with this post. axios.post(`http://localhost:8000/api/companys/`,{}) It works well at first, just using REST Framework default CRUD system. class CompanyViewSet(viewsets.ModelViewSet): serializer_class = s.CompanySerializer queryset = m.Company.objects.all() However, when user log-in django, It returns the 403 permission. After log-out it works successfully. It is quite mysterious, anonymous user successs, but login user doesn't. How can I solve this? My REST_FRAMEWORK setting is like this below. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( ), 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } -
How to create in secondary database using Django
dbrouter.py class DbRouter(object): mhris = [HrUserMstr] profocus_db = [VendorEntry, ApVendorMt, ApVendorDt, ApVendorCertificateDt] apps_ppl = [] def db_for_read(self, model, **hints): if model in self.profocus_db: return 'PROFOCUS_DB' elif model in self.apps_ppl: return 'APPS_PPPL' elif model in self.mhris: return 'MHRIS' else: return 'default' def db_for_write(self, model, **hints): if model in self.profocus_db: return 'PROFOCUS_DB' elif model in self.apps_ppl: return 'APPS_PPPL' elif model in self.mhris: return 'MHRIS' else: return 'default' def allow_migrate(self, db, app_label, model_name=None, **hints): if model_name in self.profocus_db: return 'PROFOCUS_DB' elif model_name in self.apps_ppl: return 'APPS_PPPL' elif model_name in self.mhris: return 'MHRIS' else: return 'default' models.py class ApVendorDt(models.Model): certificate = models.ForeignKey(ApVendorCertificateDt, on_delete=models.CASCADE) vendor_code = models.CharField(max_length=30, default='') vendor_doc = models.FileField(upload_to='vendor_doc/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.vendor_id class Meta: db_table = 'APVENDOR_DT' db_for_write and db_for_read functions are working fine but allow_migrate is not working. I'm trying to create a new table using django model it is creating table in default database But I want to create table in only profocus_db which is my secondary database. django 4.0.1 -
Is there a way to remove email from being displayed in JWT dajngo?
I have this simple example in Django to create JWT using djangorestframework-jwt this is my code: user_payload = TbaleUsers.objects.get(email="test@gmail.com") encoded_payload = jwt_payload_handler(user_payload) access_token = jwt.encode(encoded_payload, SECRET_KEY, ALGORITHM) When I get the access token and I go to this website https://jwt.io/ and place it there it shows me the user id, username and email I want to remove the email from being shown Is there a way to do that? -
Query Local serial ports using the Hosted Django Website in IIS
I have a code for querying and listing serial ports on my local machine.Now my problem is when I host the app in the IIS because it now only lists the serial ports in that server machine. Is there a way I can twerk this to list the ports that are in my local machine too? Or am I doing the wrong thing? here is the code. def retrieve_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/tty[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/tty.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass print("available ports===",result) return result -
How to find if two XML files are same and if not will I be able to Identify the mismatched fields using python?
The given below is my current code from lxml import etree tree1 = etree.parse('sample1.xml') tree2 = etree.parse('sample2.xml') set1 = set(etree.tostring(i, method='c14n') for i in tree1.getroot()) set2 = set(etree.tostring(i, method='c14n') for i in tree2.getroot()) print(set1 == set2) Here it just prints "True" if the xml files are same and "False" if they are not equal. What I am trying to do is to find the fields or places where the data is showing mismatch. both the files will be equal eventually. But if the files have any difference in the data's, I need to know where all there is differences. -
Integrate Laravel Spark with Auth0 and Django
We are planning to use Laravel Spark to manage payments and subscriptions for our Sass service though our django project secured by Auth0. Could you kindly assist me to figure out the best way to connect Laravel Sparks with Django and Auth0? -
How the request.data can used for switching the django class view?
I am trying to use single API to call the different class based view. Actually planning to solve this by using another function. Is this pythonic way? My Urls.py from django.urls import path from masterdata import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('AAA/', views.AAAList.as_view()), path('AAA/<str:pk>/', views.AAADetails.as_view()), path('BBB/<str:pk>/', views.BBBList.as_view()), path('BBB/<str:pk>/', views.BBBDetails.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) my Views.py class AAAList(APIView): "some operation" class AAADetails(APIView): "some operation" class BBBList(APIView): "some operation" class BBBDetails(APIView): "some operation" My actual need is I want to switch these class using single Url with passing the body data in the method. url looks like, path("",views."somefunction or class") How can I achieve this? i try to solve this by an creating function in views.py def switcher(request): if request.GET.get("body param")==AAA: return AAA.as_view()(request) elif request.GET.get("body param")==AAA: return BBB.as_view()(request) -
how to use 1 master(page or model.Model) for many catigories(page)?
i wanna get somethink like this but i have no idea how 2 do it in wagtail(1 child cant have more then 1 parent), how 2 fix it? I dont wanna have 3 master pages in admin panel well, im newbie in wagtail, i know about snippets, but i need master page. I know how 2 do it in django, but have no idea when using wagtail. class Master(Page): name = models.CharField(max_length=200) contacts = RichTextField( blank=True, null=True, ) image = models.ForeignKey('wagtailimages.Image', blank=True, null=True, on_delete=models.SET_NULL, related_name='+', verbose_name=) content_panels = Page.content_panels + [ FieldPanel('name'), FieldPanel('contacts'), FieldPanel('image'), ] class ProductsIndexPage(Page): intro = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full"), MultiFieldPanel([ InlinePanel('products_sell', label="Product")], heading="Products",), MultiFieldPanel([ InlinePanel('training', label="Training")], heading="Training", ), ] class Training(AbstractProducts): product = ParentalKey( 'ProductsIndexPage', on_delete=models.CASCADE, related_name='training' ) -
Getting 'Cannot use MongoClient' exception when refreshing django API request
I currently have an AWS EC2 instance running that is running a web server using Apache (httpd) to deploy the server in the instance. The project uses the Django, Djongo, and Django Rest Framework python libraries. It works initially as it gives back an API response via JSON. However, when making another API call, it comes out with the following exception: DatabaseError at /profile/7/ No exception message supplied Environment: Request Method: GET Request URL: https://[redacted]/profile/7/?format=json Django Version: 3.2.16 Python Version: 3.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api'] Installed 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'] Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 808, in __iter__ yield from iter(self._query) File "/usr/local/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 166, in __iter__ for doc in cursor: File "/usr/local/lib64/python3.7/site-packages/pymongo/cursor.py", line 1248, in next if len(self.__data) or self._refresh(): File "/usr/local/lib64/python3.7/site-packages/pymongo/cursor.py", line 1165, in _refresh self.__send_message(q) File "/usr/local/lib64/python3.7/site-packages/pymongo/cursor.py", line 1053, in __send_message operation, self._unpack_response, address=self.__address File "/usr/local/lib64/python3.7/site-packages/pymongo/_csot.py", line 105, in csot_wrapper return func(self, *args, **kwargs) File "/usr/local/lib64/python3.7/site-packages/pymongo/mongo_client.py", line 1335, in _run_operation retryable=isinstance(operation, message._Query), File "/usr/local/lib64/python3.7/site-packages/pymongo/_csot.py", line 105, in csot_wrapper return func(self, *args, **kwargs) File "/usr/local/lib64/python3.7/site-packages/pymongo/mongo_client.py", line 1441, in _retryable_read server = self._select_server(read_pref, session, address=address) File "/usr/local/lib64/python3.7/site-packages/pymongo/mongo_client.py", line 1247, in _select_server topology = self._get_topology() File "/usr/local/lib64/python3.7/site-packages/pymongo/mongo_client.py", … -
How can I add social signup, Email verification in my existing django user signup system?
So I am using default django authentication where its taking username and a password for signup. And I have 5 users registered right now. Now I need 2 features in my user model Facebook/gmail login Email verification The problem is I dont wanna loose my existing users and their records. The tutorials and methods I can find on internet all starts from scratch. Any idea how can I approach this? in my views.py from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy class UserRegistrationView(generic.CreateView): form_class = UserCreationForm template_name = 'registration/registration.html' success_url = reverse_lazy('login') urls.py from django.urls import path from .views import UserRegistrationView urlpatterns = [ path('register/',UserRegistrationView.as_view(),name='register'), ] -
Django simple jwt authentication returning an weird error even if with default settings in settings.py file
Hello django simple jwt users, while implementing django simple jwt authentication token generation I've encountered with an issue - the default project configurations returning errors and asking from jwt import InvalidAlgorithmError, InvalidTokenError, algorithms ImportError: cannot import name 'InvalidAlgorithmError' from 'jwt' To be exact this issue ad Request: /api/user/r/ [01/Nov/2022 06:31:45] "POST /api/user/r/ HTTP/1.1" 400 62 Internal Server Error: /api/user/r/ Traceback (most recent call last): File "....../env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "....../env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "....../env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "....../env/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "....../env/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "....../env/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "....../env/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "....../env/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "....../account/views.py", line 33, in post token = get_tokens_for_user(user) File "....../account/views.py", line 16, in get_tokens_for_user 'refresh': str(refresh), File "....../env/lib/python3.10/site-packages/rest_framework_simplejwt/tokens.py", line 81, in __str__ return self.get_token_backend().encode(self.payload) File "....../env/lib/python3.10/site-packages/rest_framework_simplejwt/tokens.py", line 204, in get_token_backend return self.token_backend File "....../env/lib/python3.10/site-packages/rest_framework_simplejwt/tokens.py", line 197, in token_backend self._token_backend = import_string( File "....../env/lib/python3.10/site-packages/django/utils/module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "....../env/lib/python3.10/site-packages/django/utils/module_loading.py", line 15, in cached_import module = import_module(module_path) File "/usr/lib/python3.10/importlib/__init__.py", … -
Changing hyperlink text using django urlize template tag
In order to make the text inside static pages dynamic, I created a model with a key and a value method that can be populated from admin panel. Then I filter the data using their keys and show them in appropriate places in the template. Now the goal is to include a hyperlink inside this Textarea field. I did some digging and came across django urlize template tag, which works fine (docs here), but it sets link text to the actual link. for example if you include https://google.com inside your text, the rendered text in your template would look like this: https://google.com; but I'd like to change this text to something like click here. How can I change this text and set it dynamically from inside the text in admin panel? -
Django heroku app successfully deployed but still showing an internal server error, Log files show the build is successful
I am trying to deploy my Django application on Heroku but although the logs show that the build is successful and despite successful deployment the application still shows an internal server error; and this is true with debug set to either true or false. Here are the files that I think are important( also I am using the cloudinary api for this project and I am not sure if that would be the problem; anyway I still decided to include my configuration of the same herein): My Procfile: web gunicorn MkusdaRegister.wsgi --log-file - My last build log -----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt ! ! A Python security update is available! Upgrade as soon as possible to: python-3.10.8 ! See: https://devcenter.heroku.com/articles/python-runtimes ! -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.10.7 -----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput 185 static files copied to '/tmp/build_f409c0b9/static'. -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 44.4M -----> Launching... Released v16 https://mkusda-events.herokuapp.com/ deployed … -
when I want to see my admin penal in django it give me error not only admin in some ursl it give me in some not this happen when I put to live db
this is my admin.py admin.site.register(models.User) admin.site.register(models.Teacher) admin.site.register(models.Student) admin.site.register(models.CourseCategory) admin.site.register(models.Course) admin.site.register(models.Chapter) admin.site.register(models.Section) admin.site.register(models.StudentCourseEnrollment) admin.site.register(models.CourseRating) this is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'LMSAPI', 'USER':'admin', 'PASSWORD':'12341234', 'HOST':'mydb.cvijitliru7b.ap-northeast-1.rds.amazonaws.com', 'PORT':'3306', 'CHARSET': 'utf8', } and this is the error enter image description here -
Git ignores all files
My gitignore file looks straighforward: env/ .idea *.pyc __pycache__ *.env /environment db.sqlite3 *.log When I do git add . from my root project folder and then check status - I see there is no files tracked. When I do git status --ignored, I see that all folders are ignored: .flake8 .gitignore .idea/ Procfile env/ requirements.txt runtime.txt src/ So it somehow ignores all the folders and files. I tried to comment everything in gitignore - and the result is the same. I tried to reinitialize the git by: rm -rf .git git init And the result is the same. How can I add my files, without git add --force? I want files that are added in gitignore to be ignored, but still to commit other files. -
django-friendship API
I Think there's nothing much to explain over here of what I am trying to achieve using Django-Friendship API. but it doesnt work and always shows the Unfollow btn. {% if user.id not in request.user.following %} <a class='btn btn-success' href="{% url 'addFollowing' user.id %}">Follow @{{user.username}} </a> {% else %} <a class='btn btn-danger' href="{% url 'removeFollowing' user.id %}">Unfollow</a> {% endif %} -
Django ORM Group By with Foreign Keys
user is a foreign key on tournament. select u.id, u.display_name, count(t.id) from tournament t join "user" u on t.user_id = u.id where date(t.start_date)> '2022-07-01' group by u.display_name, u.id How can I make the above SQL query work with django's ORM? -
Can't Get Image from Django Api To React Native
Hello Friends I Can't Get Image From Django To React Native Here My Code Fetch APi const [add, setStudents] = useState([{}]) async function getAllStudent() { try { const add = await axios.get('http://192.168.1.77:19000/api/add/') method:'GET', setStudents(add.data) } catch (error) { console.log(error) } } getAllStudent(); FlatList : <FlatList data={add} renderItem={({item})=> <Image style={{width:200,height:200, backgroundColor:'green',}} source={{uri:item.image}} /> } /> Django Code Is Here Views class addpost(viewsets.ViewSet): def list(self,request): postadd1 = postadd.objects.all() postaddserial1 = postaddserial(postadd1,many=True) return Response(postaddserial1.data) def create(self,request): postaddserial1 = postaddserial(data=request.data) if postaddserial1.is_valid(): postaddserial1.save() return Response(postaddserial1.data, status=status.HTTP_201_CREATED) return Response(postaddserial1.errors, status=status.HTTP_400_BAD_REQUEST ) def retrieve(self,request,pk=None): queryset = postadd.objects.all() contact = get_object_or_404(queryset,pk=pk) postaddserial1 = postaddserial(contact) return Response(postaddserial1.data) def update(self,request,pk=None): contact = postadd.objects.get(pk=pk) postaddserial1 = postaddserial(contact,data=request.data) if postaddserial1.is_valid(): postaddserial1.save() return Response(postaddserial1.data,status=status.HTTP_201_CREATED) return Response(postaddserial1.errors,status=status.HTTP_400_BAD_REQUEST) def destroy(self, request, pk=None): postadd1 = postadd.objects.get(pk=pk) postadd1.delete() return Response(status=status.HTTP_204_NO_CONTENT) Serializer class postaddserial(serializers.ModelSerializer): class Meta: model = postadd fields ='__all__' Model class postadd(models.Model): city=models.CharField(max_length=122) carinfo=models.CharField(max_length=122) milage=models.CharField(max_length=122) price=models.CharField(max_length=122) company=models.CharField(max_length=122) image = models.ImageField(upload_to ='static/Images', height_field=None, width_field=None, max_length=100,) engine=models.CharField(max_length=122) contact=models.CharField(max_length=122) I make django Api to add product in react native. i show image from post man . but cant get image in react native from api i am making application where i can add product from django rest framework and show it on react native through api i get …