Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError when using Enums (Python 3.5) in Django Model
I'm trying to use Enums on Python 3.5 in my Django model. Why am I getting this when trying to migrate? field=models.CharField(choices=[('RE', 'Red'), ('GR', 'Green'), ('BL', 'Blue'), ('OR', 'Orange'), ('YE', 'Yellow'), ('PU', 'Purple')], default=users.models.COLOR('BL'), max_length=2), AttributeError: module 'users.models' has no attribute 'COLOR' - class User(AbstractBaseUser): class COLOR(enum.Enum): RED = 'RE' GREEN = 'GR' BLUE = 'BL' ORANGE = 'OR' YELLOW = 'YE' PURPLE = 'PU' //... color = models.CharField(max_length=2, choices=((x.value, x.name.title()) for x in COLOR), default=COLOR.BLUE) -
Django - Determining how to split into apps based on functionality
Completely new to Django. I'm building a website where users can make profiles, search for other profiles, and view basic information. I'm unsure about how to organize the apps. I want to following things on the navigation bar: "About Us", "How it Works", "Join", "Login" I know that users (join + login) will be its own app, but how would I bundle all of the information that will show up on the navigation bar? Will that just be one main app because it doesn't really do anything complex and really just presents text? -
Web framework and/or CMS for web-mapping application
We are building a web-mapping application and are having trouble deciding on a web framework and/or CMS. We are comfortable programming in Java or Python. There is no real preference here beyond wanting the language and associated web framework and/or CMS that we use to accomplish the outcomes we want. Our technology stack so far is: Ubuntu 16.04 Postgresql/postgis Geoserver (we would use Mapnik, but it doesn’t allow for a time element) leaflet.js jquery.js OpenLDAP (we are flexible here) Features we already have at least partially developed: Leaflet web mapping pulling through WMS and WFS layers from Geoserver (this needs nested into our selected CMS/framework). Features we would like to incorporate in the future: User handling including website and direct database access from inside and outside our company (asap). Basic filtering of data points on the map based on data attributes. The ability for the user to custom query our databases including spatial queries to create a dataset that is either sent to them and/or displayed on the map. A workspace for users to share map views and specific data points. The ability for users to upload and view their own mappable data. Server clustering. Options we are considering: Django … -
Django retrieve the correct primary key for url
I am trying to pass primary keys via url in Django. I have the following pages with urls as follows: Page A: url(r'^A/$') Page B: url(r'^(?P<class_id>[\w\-]+)/B/$') Page C: url(r'^(?P<test_id>[\w\-]+)/C/$') The flow of the application is: 1) Page A pass <class_id> to page B 2) Page B pass <test_id> to page C (Current pk: class_id) 3) Page C reverts back to page B, unable to display page B (Current pk: test_id) The problem is because when I tried to retrieve 'class_id' in page B (since page B needs class_id in its url), the value of 'class_id' becomes the value of 'test_id': self.kwargs['class_id'] Is there a proper way to pass primary key or any way to pass class_id to page B? -
How to return an object along with a sub object in Django
I am trying to display a camera object along with its most recent state. I am able to display camera and the most recent timestamp, but am struggling to access the corresponding state field. I have the following Django models. class Camera(models.Model): name = models.CharField(max_length=32) class TimeStamp(models.Model): camera = models.ForeignKey(Camera, on_delete=models.CASCADE) state = models.BooleanField(default=False) timeStamp = models.DateTimeField(db_index=True, auto_now_add=True, blank=True) And I have the following view. def index(request): context = { 'cameras': Camera.objects.all().annotate(latest_timestamp=Max('timestamp__timeStamp')), 'functional': Camera.objects.annotate(latest_timestamp=Max('timestamp__timeStamp')).filter(latest_timestamp=F('timestamp__timeStamp'), timestamp__state=True), 'faulty': Camera.objects.annotate(latest_timestamp=Max('timestamp__timeStamp')).filter(latest_timestamp=F('timestamp__timeStamp'), timestamp__state=False), } return render(request, 'index.html', context) And in my index.html I have <table class="table table-hover"> <thead class="text-info"> <th>ID</th> <th>Name</th> <th>Current State</th> <th></th> </thead> <tbody> {% for camera in cameras %} <tr> <td>{{ camera.id }}</td> <td>{{ camera.name }}</td> <td>{{ camera.latest_timestamp }}</td> </tr> {% endfor %} </tbody> Instead of camera.latest_timestamp, I would like to show the corresponding state field. -
NoReverseMatch when trying to use get_absolute_url with custom template tag
I am making a calendar app which has a custom template tag that takes the python HTMLtemplate function and overlays objects from the Events model on the correct days. I am trying to get the displayed objects to have a link directly to an object detail/edit view and am trying to use get_absolute_url and to reverse render this view. This is necessary as the custom template tag doesn't load correctly if I try to hardcode {% url %} template tags into it for each event via a for loop. I have spent some hours looking through the other stack overflow questions with no luck and have even changed my reverse to the object ID rather than the title of the event. I am hoping this is just a small thing that I have overlooked but no sure. view: def home(request, month=None, year=None): if month == None: _date = datetime.now() else: _date = date(int(year), int(month), 1) title = "%s, %s" % (_date.strftime("%B"), _date.strftime("%Y")) return render(request, 'calendar.html', calendar(_date, title)) urls: app_name = 'cal' urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^newevent/$', views.newEvent, name='newevent'), url(r'^(?P<title>\d+)$/', views.viewEvent, name='viewevent'), url(r'^(?P<month>\d+)/(?P<year>\d+)$', views.home, name='another-month') ] HTML: <body> <div> <h1 class="welcome">{{ title }}</h1> </div> <div class="calendar"> <div class="navigation"> <form … -
How to get data from database inside DataTables upon custom filtering?
I am using DataTables for my tables in my Django project. Now, Its like the following: There are Organizations (a separate Organization model) Each organization has a project (Project model with a foreign key to organization model) The organization model has a ManytoMany relationship with the user model, i.e, a user can be a member of mutiple organizations simultaneously. My DataTables look like so currently: Now, what I want is the following: Add another dropdown filter in my DataTable header having options "All Organizations" and "My Organizations" that would filter the table to give the corresponding result (that is display all Organizations, a user is a member of): Similarly include a dropdown to display all the projects a user has access to: All I know right now is, using python, I can get all the user's organizations using current_user.organizations.all() because the models.py has related_name attribute set to 'organizations' and the organization is connected with the user model through ManytoMany field like so: #models.py class Organization(SlugModel, RandomIDModel): users = models.ManyToManyField('accounts.User', through='OrganizationRole', related_name='organizations') But I don't know how to accomplish this inside the DataTables. How to proceed? Please help. -
Getting Multiple Objects using Django rest_framework RetrieveAPIView
currently I have this class inside my shop's view.py class ShopDetailAPIView(RetrieveAPIView): queryset = Shop.objects.all() serializer_class = ShopDetailSerializer lookup_field = 'Suburb' permission_classes = [IsAuthenticated] and my shop's urls.py which display this specific api. urlpatterns = [ url(r'^$', ShopListAPIView.as_view(), name = 'list' ), url(r'^(?P<Suburb>\w+)/$', ShopDetailAPIView.as_view(), name = 'detail'), ] The aim of ShopDetailAPIView class is to display a filtered version of the data stored inside the database. So that if user enters http://example.com/shop/locationname The link will display Django rest_framework api according to the location. The problem i am facing is that when there are more than one objects, the page returned get() returned more than one Shop -- it returned 3! I think my solution is to change my queryset to queryset = Shop.Objects.filter(Suburb = suburb) However I have no idea how to implement this using RetreiveAPIView. I know there are alternatives such as django-filter which would work perfectly in this situation. However is there any way to implement my code above to show more than 3 objects. Thank you -
Pycharm does not display database tables
After updating PyCharm (version 2017.1), PyCharm does not display sqlite3 database tables anymore. I've tested the connection and it's working. In sqlite client I can list all tables and make queries. Someone else has get this problem? And in this case could solve anyway? -
How to resolve cannot import name pages (django/wagtail)
Recently I have been trying to get wagtail to work with my existing Django application. I was experiencing an error: - ImportError: No module named wagtail unable to load app 0 (mountpoint='') (callable not found or import error) After much troubleshooting I managed to fix this, by copying the folder wagtail from: /usr/local/lib/python2.7/dist-packages/ into here /opt/django/src/ Having resolved this error, I received another about a different module, and another... each time I copied the folder from /usr/local/lib/python2.7/dist-packages/ into /opt/django/src/ and it eventually resolved the issues I was having and uWSGI started. Now when I access the homepage of my app, I receive this error ImportError at / cannot import name pages Request Method: GET Request URL: http://example.com Django Version: 1.9 Exception Type: ImportError Exception Value: cannot import name pages Exception Location: ./wagtail/wagtailadmin/urls/__init__.py in <module>, line 4 Python Executable: /usr/local/bin/uwsgi Python Version: 2.7.3 Python Path: ['.', '', '/opt/django/src', '/root/.python', '/opt/django/env/lib/python2.7', '/opt/django/env/lib/python2.7/plat-linux2', '/opt/django/env/lib/python2.7/lib-tk', '/opt/django/env/lib/python2.7/lib-old', '/opt/django/env/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/opt/django/env/local/lib/python2.7/site-packages', '/opt/django/env/lib/python2.7/site-packages'] I have checked the file referenced (./wagtail/wagtailadmin/urls/__init__.py) and it looks like this: from django.conf.urls import url, include from django.views.decorators.cache import cache_control from wagtail.wagtailadmin.urls import pages as wagtailadmin_pages_urls from wagtail.wagtailadmin.urls import collections as wagtailadmin_collections_urls from wagtail.wagtailadmin.urls import password_reset as wagtailadmin_password_reset_urls from wagtail.wagtailadmin.views import … -
Looping over a model object fields in a view
I have a model like below. I would like to loop over all the fields inside a view to get field name and value of the field in the corresponding object. class Company(models.Model): name = models.CharField(max_length=1000) website = models.CharField(max_length=1000) email = models.CharField(max_length=200) phone_number = models.CharField(max_length=100) city = models.CharField(max_length=1000) -
Wagtail CMS email form submission stored in db but not being sent
I've been following this: http://docs.wagtail.io/en/v1.9/reference/contrib/forms/index.html The form does get submitted to the landing page. I see that the data gets populated into wagtailforms_formsubmission. I tried putting this in base.py based on what I saw somewhere else. # EMAIL SETTINGS EMAIL_HOST = 'smtp.example.de' EMAIL_INBOX = 'in...@example.com EMAIL_PORT = 587 EMAIL_HOST_USER = 'in...@example.com' EMAIL_HOST_PASSWORD = 'secret' EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' Is there something I'm missing? Does this work for all email providers? -
How do I add form validation in django admin for Django Treebeard?
I'm following the django-treebeard tutorial here: http://django-treebeard.readthedocs.io/en/latest/admin.html and I would like to add form validation to the admin part. Basically I want to say that if the name does not start with a letter, error out. I looked at django-admin form validation, but it requires me to define a custom form and then add validation logic there, but for tree-beard, the form comes with it and I don't know how to modify it. The documentation does not mention anything about this. Can anyone help? This is my code so far: Models.py: from treebeard.mp_tree import MP_Node class Category(MP_Node): name = models.CharField(max_length=30) node_order_by = ['name'] def __unicode__(self): return 'Category: %s' % self.name Admin.py: from django.contrib import admin from treebeard.admin import TreeAdmin from treebeard.forms import movenodeform_factory from myproject.models import MyNode class MyAdmin(TreeAdmin): form = movenodeform_factory(MyNode) #This is the form from which I need to intercept data and validate. admin.site.register(MyNode, MyAdmin) -
Django Apps aren't loaded yet
I have a django application with the error Apps aren't loaded yet. I'm using a postgres db. Problem started happening after I added a model. I tried adding the model into installed apps, changing django setup to below the models, adding a name into my model class, adding a meta into my model class. I'm not sure if there is an issue with using django.db import models. Here is the full error raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps arne't loaded yet. settings.py import os SECRET_KEY = 'secret_key' # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'django.contrib.sites', 'myapps.modelapp' ] modelapp.py from django.db import models from django.contrib.postgres.fields import ArrayField class AppClass(models.Model): name = 'modelapp' verbose_name = 'modelapp' # Regular Django fields corresponding to the attributes in the # world borders shapefile. data_1 = models.CharField('data_1', max_length=30) # Returns the string representation of the model. def … -
How can I fix ImportError: No module named wagtail` when I try to launch my django app
This is driving me insane. I have spent 5 days now simply trying to install wagtail and get the basic functionality working with my existing Django project. The latest hurdle which is what this question is about I have spent 13 hours trying to solve. I have a Django Application, it is working fine. I am trying to add wagtail to it as per these instructions: http://docs.wagtail.io/en/v1.9/getting_started/integrating_into_django.html Steps taken to generate error Entered the virtualenv of the working project. Installed wagtail with pip install wagtail Made changes to setting.py and urls.py as described in above docs. When I try to start the django app (using uWSGI) with the following command line: uwsgi --chdir=/opt/djangov2/src --module=core.wsgi:application --env DJANGO_SETTINGS_MODULE=core.settings --master --pidfile=/tmp/v2.pid --socket=/opt/djangov2/core.sock --processes=5 --uid=www-data --gid=www-data --harakiri=20 --max-requests=5000 --vacuum --home=/opt/djangov2/env --daemonize=/var/log/uwsgi/v2.log I receive the following error *** Operational MODE: preforking *** Traceback (most recent call last): File "./core/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/django/env/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup() File "/opt/django/env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/django/env/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/opt/django/env/lib/python2.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named wagtail unable to load app 0 … -
django-wkhtmltopdf returning error -6 running on ubuntu server
im getting this error when trying to render a html page into pdf. Command '['wkhtmltopdf', '--encoding', 'utf8', '--margin-top', '10', '--quiet', '/tmp/wkhtmltopdfe21in3lz.html', '-']' returned non-zero exit status -6 It runs normally locally. im only having this problem when it runs on the server. Full traceback [2017-03-28 15:43:00 +0000] [4817] [DEBUG] GET /invoice/1/pdf QXcbConnection: Could not connect to display Internal Server Error: /invoice/1/pdf Traceback (most recent call last): File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/home/instantuser/app/lib/python3.5/site-packages/django/template/response.py", line 109, in render self.content = self.rendered_content File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/views.py", line 78, in rendered_content cmd_options=cmd_options File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 186, in render_pdf_from_template cmd_options=cmd_options) File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 124, in convert_to_pdf return wkhtmltopdf(pages=filename, **cmd_options) File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 110, in wkhtmltopdf return check_output(ck_args, **ck_kwargs) File "/usr/lib/python3.5/subprocess.py", line 626, in check_output **kwargs).stdout File "/usr/lib/python3.5/subprocess.py", line 708, in run output=stdout, stderr=stderr) subprocess.CalledProcessError: Command '['wkhtmltopdf', '--encoding', 'utf8', '--margin-top', '10', '--quiet', '/tmp/wkhtmltopdf4t2k67u5.html', '-']' returned non-zero exit status -6 Cant find the solution yet. -
Django display json data table
Hi I need some help from the friendly community for django. I'm currently unable to display json data from solr that crawls twitter API tweets. I would like to display them in a table form so that it would be easier to view and add additional UI stuff later. Here's my code: my views.py def my_view(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): gotName = form.cleaned_data['your_name'] gotEmotion = form.cleaned_data['emotion'] gotWords = form.cleaned_data['words'] url = 'http://localhost:8983/solr/gettingstarted/query?q=id:' + gotName r = requests.post(url, data={'id': gotName}) return render(request, 'index.html', {"table_data" : ??? }) #return render(request, 'index.html', {"mydata": mydata}) else: not_working = "not working" return render(request, 'index.html', {'text2': not_working }) my index.html table part <table> # insert table formatting here </table> full index.html body <body> {% load static %} <img src="{% static "/templates/happybird.jpg" %}"/> <h1 style="text-align:center;">Emotional Tweets</h1> <div class="container"> <div class="row"> <div class="col-md-12" > <div class="input-group" id="adv-search"> <form action="/search/my_view/" method="POST"> {% csrf_token %} {{ form }} <div> <input id="your_name" type="text" class="form-control" name="your_name" placeholder="Search for Tweets" value="{{ current_name }}" /> <br> </div> <div class="form-group"> <label for="filter">Filter by</label> <select class="form-control"> <option value="0" selected>All Tweets</option> <option value="1">Excited</option> <option value="2">Happy</option> <option value="3">Neutral</option> <option value="4">Sad</option> <option value="5">Angry</option> </select> </div> <div class="form-group"> <label for="contain">Contains the words</label> <input id="words" class="form-control" … -
Use method of django class based view as rest_framework api view
I have a generic DetailView, and I'd like to add a post method to it that exposes n api endpoint using django-restframework. Can I somehow use drf's api_view decorator on a single method of a class based view, or is there any other way to have a normal django view and a drf api view share the same url? -
Struggling to upload images using django formsets
Good day the reason why I make this entry is because I am struggling to upload images using django's formsets, when creating a new product two forms appear to upload two more images, the problem is that when uploading all the forms if they are created in the Database these records but without the images that must be uploaded. Thanks in advance! models.py class Etiqueta(models.Model): nombre = models.CharField(max_length = 20) def __str__(self): return self.nombre class Meta: verbose_name = 'Etiqueta' verbose_name_plural = 'Etiquetas' class Producto(models.Model): nombre = models.CharField(max_length = 70) descripcionCorta = models.CharField(max_length = 150) descripcionDetallada = models.TextField() imagenPrincipal = models.ImageField(upload_to = 'imagenesProductos/', null=True, blank=True) precioOriginal = models.PositiveIntegerField() precioDescuento = models.PositiveIntegerField(null=True, default= None, blank=True) cantidad = models.PositiveSmallIntegerField(null=True, blank=True) especificaciones = models.TextField(null=True, blank=True) calificacion = models.PositiveSmallIntegerField(null=True, blank=True) categoria = models.CharField(max_length = 30) fechaCreacion = models.DateField(auto_now_add=True) etiqueta = models.ManyToManyField(Etiqueta) def __str__(self): return self.nombre class Meta: verbose_name = 'Producto' verbose_name_plural = 'Productos' class FotografiaProducto(models.Model): producto = models.ForeignKey(Producto, null=True, blank=True, on_delete=models.CASCADE) fotografia = models.ImageField(upload_to = 'imagenesProductos/', null=True, blank=True) def __str__(self): return str(self.id) views.py @login_required() def addProducto(request): data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', } FotoProductoFormSet = formset_factory(FotoProductoForm, extra=2) if request.method == 'POST': formaFoto = FotoProductoForm(request.POST, request.FILES, prefix='fotografia') productoForm = ProductoForm(request.POST, request.FILES) formset = … -
How to add homepage link on django administration login page?
I created a project in Django framework. When I open the link http://127.0.0.1:8000/admin ,my django administration login page will open. The django admin page I would like to add a "back to homepage" link on below the login button. How can I add this link to this page? -
Advice on a framework stack for a Python-ReactJS service
I am looking for an advice on choosing web frameworks for a new web app with Python used on a backed and ReactJS to be used for presentation. I am not asking for an advice based on your experience if you made similar choices for your own projects. All data aggregation and mining logic are written in Python with MongoDB used to store the data. Based on my research I am thinking of using Flask to run the logic serving user requests from the Web UI, but I am open to revising it. For the Web UI I am going to join the trend and use ReactJS. However, I am not sure where to server the ReactJS logic from. One choice would be to run it in a separate NodeJS container like Express, another one is to configure Flask itself to serve ReactJS and work with Webpack (https://github.com/nickjj/manifest-revision-webpack-plugin). How would you integrate ReactJS with Python (Flask)? ReactJS will be used to build a full-featured website with user registration and subscriptions, so availability of extensions/plugins for typical website tasks is also desired. -
wsgi user permissions on elastic beanstalk
I'm using elastic beanstalk and django. One of my dependencies in my requirements.txt file has some setup the it performs when it's initially imported. Part of the setup is to check whether a dir exists else it create it. I'm getting permissions errors because the user ( I assume it's wsgi) does not have the permissions to create the dir. OSError: [Errno 13] Permission denied: '/home/wsgi/.newspaper_scraper/memoized' How can I setup permissions to allow for these dirs to be created in a way that will be persistent across instances I create in the future? -
Django Rest Framework and BackBoneJS Integration
I have searched alot about it but I am not able to find any working answer in my case, that is why posting the question again. I have made a DRF application that exposes two APIs http://127.0.0.1:8000/contactList/ http://127.0.0.1:8000/contact/ Also I have made a demo backboneJS application that is just client-side and it fetches data from 3 fields(name, phone, address) and saves it using backbone-localstorage.js. Now I want to integrate the front-end backbone app with DRF REST APIs so that data goes to and is fetched from django models. Is it possible without using NodeJS with backbone app? What changes are required to make it happen? Where to specify urls of APIs in the backbone app? -
how to show ticks on bootstrap select box
I am trying to show the ticks when a property is selected, I am using django. def __init__(self, *args, **kwargs): self.buildings = kwargs.pop('buildings',None) super(CreateInvestigationForm, self).__init__(*args, **kwargs) self.fields["building"] = forms.ModelMultipleChoiceField( queryset=self.buildings, required=False, widget=SelectMultiple(attrs={ 'class':'form-control selectpicker', 'multiple data-actions-box':'true', 'data-live-search':'true', 'multiple title':'--- Please select ---', 'multiple data-selected-text-format':'count > 2' }), label="Property:", ) -
How can i Get foreign key's value instead of id , in django rest framework
Sorry for my bad English hope u can understand what i mean. OUT PUT IM GETTING NOW: [ { "MainCatName": 1, "Name": "harry potter", "Image": "/media/101029496--sites-default-files-images-101029496-3176173-1748009911-hp.jp-1_MoxqrLp.jpg" }, { "MainCatName": 2, "Name": "Princes Girl", "Image": "/media/character_princess_rapunzel_8320d57a.jpeg" }, { "MainCatName": 3, "Name": "sex in the city", "Image": "/media/250px-SATC_Title.jpg" }, { "MainCatName": 4, "Name": "who is dragon", "Image": "/media/Reggio_calabria_museo_nazionale_mosaico_da_kaulon.jpg" }, { "MainCatName": 2, "Name": "drama queen", "Image": "/media/15241421_170761763390015_7913498865987146084_n.jpg" } ] WHAT I WANT : I WANT TO TO RETURN THE FORIGN KEY'S (MainCatName) VALUE WHICH IS IN TABLE INSTEAD OF ID. ie value in the [CategoryName = models.CharField(max_length=50)] in my models.py LIKE [ { "MainCatName": Story Books, "Name": "harry potter", "Image": "/media/101029496--sites-default-files-images-101029496-3176173-1748009911-hp.jp-1_MoxqrLp.jpg" }, { "MainCatName": Darama, "Name": "Princes Girl", "Image": "/media/character_princess_rapunzel_8320d57a.jpeg" }, { "MainCatName": Roamance, "Name": "sex in the city", "Image": "/media/250px-SATC_Title.jpg" }, { "MainCatName": sex, "Name": "who is dragon", "Image": "/media/Reggio_calabria_museo_nazionale_mosaico_da_kaulon.jpg" }, { "MainCatName": darama, "Name": "drama queen", "Image": "/media/15241421_170761763390015_7913498865987146084_n.jpg" } ] Here is my code : veiws.py : class GETCATVeiw(APIView): def get(self, request): data = Products.objects.only('MainCatName','Name','Image') serializer = GETCAT(data, many=True) return Response(serializer.data) def post(self): pass models.py : class Category(models.Model): CategoryName = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.CategoryName class Products(models.Model): MainCatName = models.ForeignKey(Category, on_delete=models.CASCADE) Name = models.CharField(max_length=50) Image …