Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
integrate skrill in django project
I want to integrate Skrill in my Django project. The thing is that, I am new to PaymentGetWays and in general and I don't have enough knowledge to do it, and there is a django-skrill package which i think it doesn't support python3. Can anyone suggest a guide which is beginner friendly or at least easy to understand, so that I could integrate it? -
How can display products coming from ajax search result in django?
Problem The search feature is working and the values are retrieved from the Django views search function but now I'm not getting how to display those values in my Django project. Can anyone here can help me through this. The code is attached below. JS $('#searchsubmit').on('click', function(e){ e.preventDefault(); q = $('#search').val(); console.log(q); updateContentBySearch(q); }); function updateContentBySearch(q) { var data = {}; data['search_by'] = q // data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val(); $.ajax({ url: "{% url 'main:Search' %}", data: { 'search_by': q }, success: function (data) { // do your thing } }); } VIEW def search(request): q = request.GET.get('search_by') print(q) product = Products.objects.all() cart_product_form = CartAddProductForm() transaction = transactions.objects.filter(productID__name__icontains=q,status='Enable').order_by('productID') print(transaction) return HttpResponseRedirect(reverse('main:home'),{'products':product, 'transaction': transaction , 'cart_product_form':cart_product_form}) # return redirect(request, 'main/home.html',{'products':product, 'transaction': transaction , 'cart_product_form':cart_product_form}) HTML FORM form class="d-flex col-md-6" id="searchform"> <div class="input-group mb-3" style="text-align:center"> <input name="q" type="text" class="form-control" placeholder="Search" id="search"> <button class="btn btn-primary shadow px-5 py-2" type="submit" id="searchsubmit">Search</button> </div> </form> HTML PRODUCT DISPLAY {% regroup transaction by productID as ProductList %} {% for productID in ProductList %} <div class="col-sm-3 productID" > <div class="product"> <a href="{% url 'main:product-detail' productID.grouper.id %}" class="img-prod"><img class="img-fluid" src={{productID.grouper.product_image.url}} alt="" height="200px"> <span class="status id_discount">%</span> <div class="overlay"></div> </a> <div class="text py-3 pb-4 px-3 text-center"> <h3><a href="#">{{productID.grouper}}</a></h3> <div class="d-flex text-center"> <div … -
How to change a model after creating a ModelViewset?
I am creating an API with django rest framework. But I have a problem every time I want to modify a model when I have already created an associated ModelViewset. For example, I have this model: class Machine(models.Model): name = models.CharField(_('Name'), max_length=150, unique=True) provider = models.CharField(_("provider"),max_length=150) build_date = models.DateField(_('build date')) category = models.ForeignKey("machine.CategoryMachine", related_name="machine_category", verbose_name=_('category'), on_delete=models.CASCADE ) site = models.ForeignKey( "client.Site", verbose_name=_("site"), related_name="machine_site", on_delete=models.CASCADE ) class Meta: verbose_name = _("Machine") verbose_name_plural = _("Machines") def __str__(self): return self.name def get_absolute_url(self): return reverse("Fridge_detail", kwargs={"pk": self.pk}) And this viewset: class MachineViewSet(viewsets.ModelViewSet): """ A simple ViewSet for listing or retrieving machine. """ permission_classes = [permissions.IsAuthenticated] serializer_class = MachineSerializer queryset = cache.get_or_set( 'machine_machines_list', Machine.objects.all(), 60*60*24*7 ) @swagger_auto_schema(responses={200: MachineSerializer}) def list(self, request): serializer_context = { 'request': request, } queryset = cache.get_or_set( 'machine_machines_list', Machine.objects.all(), 60*60*24*7 ) serializer = MachineSerializer(queryset, many=True, context=serializer_context) return Response(serializer.data) @swagger_auto_schema(responses={404: 'data not found', 200: MachineSerializer}) def retrieve(self, request, pk=None): serializer_context = { 'request': request, } queryset = Machine.objects.all() machine = get_object_or_404(queryset, pk=pk) serializer = MachineSerializer(machine, context=serializer_context) return Response(serializer.data) If I want to add a field to my model, like for example a description. When I run the command python manage.py makemigrations I get the error : django.db.utils.ProgrammingError: column machine_machine.description does not exist I … -
django signals can't passing sender id
I am trying to create an notification system which will be notify author if any new comment posted in his Blog post. I am trying to pass sender id through Django signals but I am getting this error: NOT NULL constraint failed: notifications_notifications.sender_id here is my code: notifications models.py class Notifications(models.Model): blog = models.ForeignKey('blog.Blog',on_delete=models.CASCADE) NOTIFICATION_TYPES = ((1,'Like'),(2,'Comment'), (3,'Follow')) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.IntegerField(choices=NOTIFICATION_TYPES) comment models.py class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_comment',blank=True,null=True) def user_comment(sender, instance, *args, **kwargs): comment= instance blog = comment.blog sender = comment.user notify = Notifications(blog=blog, sender=sender, user=blog.author, notification_type=2) notify.save() post_save.connect(BlogComment.user_comment, sender=BlogComment) if I use pass author id sender = comment.blog.author as a sender then it worked. But I need to pass commenter id as comment will be sent from user not author. -
'how to solve QuerySet' object has no attribute '_meta'
iam,new to django iam getting QuerySet object has no attribute _meta error while login. [[1]: https://i.stack.imgur.com/0zuJu.png][1] [[1]: https://i.stack.imgur.com/AQtOQ.png][1] [[1]: https://i.stack.imgur.com/5OfJs.png[\]\[1\]][1] [[1]: https://i.stack.imgur.com/YnfTb.png] -
Heroku with django session (status 500)
I get status=500 when working with session. I call the following from Ajax to update session. def update_session(request): request.session['test']= request.GET.get('test') return JsonResponse({"success": True}) It works fine when running on local machine, but when deployed to Heroku it say 'Server Error (500)' Thank you. -
exporting the data to an excel sheet after being filtered on the admin panel?
so, after i filter information, is there a way I can export that filtered list as an excel sheet? I would prefer to have a button that you can click in the admin page to just export all the info as an excel sheet that is visible currently in the panel. If this is too confusing please ask more question, I would be happy to help you help me! my list filters : list_filter = ('Class','Age',) -
Unable to verify webhooks from PayPal in Python
I am trying to verify webhooks for subscriptions in paypal using django python. I am receiving the webhooks but when i send them to get verified i get this error: {'name': 'VALIDATION_ERROR', 'message': 'Invalid request - see details', 'debug_id': 'ccc873865982', 'details': [{'field': '/', 'location': 'body', 'issue': 'MALFORMED_REQUEST_JSON'}], 'links': []}. I have checked what the status code is for the response which gives a 400 response. By looking at the API Docs i see that invalid request + 400 response is either a validation error (which is to do with the Json format, so most likely a syntax error) or an authorization error (which says i need to change the scope). I think it is the validation error because the error points to the body. Here is the relevant code: header_params = { "Accept": "application/json", "Accept-Language": "en_US", } param = { "grant_type": "client_credentials", } cid = settings.PAYPAL_CLIENT_ID secret = settings.PAYPAL_CLIENT_SECRET token_i = requests.post('https://api-m.sandbox.paypal.com/v1/oauth2/token', auth=(cid, secret), headers=header_params, data=param).json() token = token_i["access_token"] bearer_token = "Bearer x".replace('x', token) headers = { "Content-Type": "application/json", "Authorization": bearer_token, } print(request.body) webhook_event = request.body.decode("utf-8") data = { "transmission_id": request.headers["PAYPAL-TRANSMISSION-ID"], "transmission_time": request.headers["PAYPAL-TRANSMISSION-TIME"], "cert_url": request.headers["PAYPAL-CERT-URL"], "auth_algo": request.headers["PAYPAL-AUTH-ALGO"], "transmission_sig": request.headers["PAYPAL-TRANSMISSION-SIG"], "webhook_id": "3AJ143072C221060T", "webhook_event": webhook_event, } print(json.dumps(data)) response = requests.post('https://api-m.sandbox.paypal.com/v1/notifications/verify-webhook-signature', headers=headers, json=json.dumps(data)).json() … -
Button to be able to display list of recipients from a specified group in Opencart
I'm trying to allow my 'Check' button to be able to display the list of customers based on the checkbox that I clicked, and display the list of customers in a table. I did all I could and researched for awhile but unable to understand on how to do so. If anyone is able to help me with this, it would be much appreciated! enter image description here -
Why it shows Unknown command: 'collectstatic', when I try to collect-static while deploying on Digital Ocean
I am trying to deploy my Django project on Digital Ocean. I created my droplet and spaces on Digital Ocean and created a static folder to store my static files. I pulled my code from my github-repo. then I installed all requirements and tried to collect static files with command python3 manage.py collectstatic but it shows Unknown command: 'collectstatic' Type 'manage.py help' for usage. what should I do here? I checked my manage.py helper but it has no command as collectstatic check, compilemessages, createcachetable, dbshell, diffsettings, dumpdata, flush, inspectdb, loaddata, makemessages, makemigrations, migrate, runserver, sendtestemail, shell, showmigrations, sqlflush, sqlmigrate, sqlsequencereset, squashmigrations, startapp, startproject, test, testserver, these are the commands in manage.py helper. And my settings.py is the following import os from pathlib import Path from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = config('DEBUG', default=False, cast=bool) SECRET_KEY = config("SECRET_KEY") ALLOWED_HOSTS = ["134.209.153.105",] ROOT_URLCONF = f'{config("PROJECT_NAME")}.urls' WSGI_APPLICATION = f'{config("PROJECT_NAME")}.wsgi.application' ASGI_APPLICATION = f'{config("PROJECT_NAME")}.routing.application' # =================================================================== # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_forms', 'accounts', 'adminn', 'student', 'union', 'chat', 'channels', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] AUTH_USER_MODEL = 'accounts.User' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': … -
how can i search products using ajax in django?
I'm trying to search the products using ajax in my Django project but can't get any value from the views function. can anyone help me out with this issue. The code is attached below. JS function initSearchForm(){ $('#searchsubmit').on('click', function(e){ e.preventDefault(); q = $('#search').val(); updateContentBySearch(q); }); } function updateContentBySearch(q) { var data = {}; data['search_by'] = q // data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val(); $.ajax({ url: '/search-products/', data: { 'search_by': q }, dataType: 'json', success: function (data) { // do your thing } }); } HTML FORM <form class="d-flex col-md-6" id="searchform"> <div class="input-group mb-3" style="text-align:center"> <input name="q" type="text" class="form-control" placeholder="Search" id="search"> <button class="btn btn-primary shadow px-5 py-2" type="submit" id="button-addon2 searchsubmit">Search</button> </div> </form> VIEW def search(request): q = request.GET.get('search_by') print(q) product = Products.objects.all() cart_product_form = CartAddProductForm() transaction = transactions.objects.filter(productID__name__icontains=q,status='Enable').order_by('productID') print(transaction) # return HttpResponseRedirect(reverse('main/home.html'),{'products':product, 'transaction': transaction , 'cart_product_form':cart_product_form}) return redirect(request, 'main/home.html',{'products':product, 'transaction': transaction , 'cart_product_form':cart_product_form}) URL path('',views.search,name='Search'), -
What is the purpose of level in logger and handler in django setting?
I am in confusion about django logger. I can not identify difference and purpose of "level" in logger and handler. I have configured a logger- "loggers": { "django": { "handlers": ["fileerror","filewarning","fileinfo"], "level": "DEBUG", "propagate": True }, }, "handlers": { "fileerror": { "level": "ERROR", "class": "logging.FileHandler", "filename": "C:/Users/samrat/Desktop/Development/uttaran/uttaran new/org_manager/static/logs/uttaran-error.log", "formatter": "app", }, "filewarning": { "level": "WARNING", "class": "logging.FileHandler", "filename": "C:/Users/samrat/Desktop/Development/uttaran/uttaran new/org_manager/static/logs/uttaran-warning.log", "formatter": "app", }, "fileinfo": { "level": "INFO", "class": "logging.FileHandler", "filename": "C:/Users/samrat/Desktop/Development/uttaran/uttaran new/org_manager/static/logs/uttaran-info.log", "formatter": "app", }, }, I want to know the difference of level in loggers and handlers. Regards, Samrat -
Django with Apache upload file to project get SuspiciousFileOperation Exception
I want to upload file to project/static/uploads get an error. SuspiciousFileOperation at /admin/myvideo/videomodel/add/ The joined path (D:\Web\pyproject\xxm_hrproject_video\src\static\uploads\2499be8ca837405aa440a4a56065bbb0.mp4) is located outside of the base path component (D:\Web\Apache24) If upload to apache path will not get any error. Django project path is D:\Web\pyproject\xxm_hrproject_video\src Apache path is D:\Web\Apache24 models.py from uuid import uuid4 from django.conf import settings class VideoModel(models.Model): def wrapper(instance, filename): # return r'D:\Web\Apache24\static\uploads\123.mp4' will not get any error return r'D:\Web\pyproject\xxm_hrproject_video\src\static\uploads\123.mp4' file = models.FileField(upload_to=wrapper) -
Django: How to calculate total hour in django model [duplicate]
I have an Overtime model. I want to calculate between start_time & end_time. and set result in total_hour field. class Overtime(models.Model): employee = models.ForeignKey(Employee,on_delete=models.CASCADE) start_time = models.DateTimeField() end_time = models.DateTimeField() total_hour = models.IntegerField(editable=False) How can I do that ? -
How to assign the specific path to store the Django Group migration file
There is currently an existing Django system, I want to add some fields to its Group, but other tables were relation Group already, so I use add_to_class that's success to add field. But I have the problem about migration file, the Group's new migration file was stored in {package path}/djano/contrib/auth/migrations, But I want to manage those files from our self, Is possibility assign the new path to store those migration files? Because we need these files for deployment. -
Django templates: block tag
listTemp.html {% extends "base_generic.html" %} {% block content %} <h1>{% block h1 %}{% endblock %}</h1> <style type="text/css"> a:link {color: black;} /* unvisited link */ a:visited {color: black;} /* visited link */ a:hover {color: black;} /* mouse over link */ a:active {color: black;} /* selected link */ </style> {% if list_list %} {% for x in list_list %} <a href="{% url '{% block modelName %}{% endblock %}-detail' {% block modelName %}{% endblock %}.pk %}" style="border:1px solid black;padding:5px;margin-left:40px;margin-bottom:20px"><strong>Name:</strong> {% block modelName %}{% endblock %}.firstName } </a> {% endfor %} {% else %} <p>{% block modelName %}{% endblock %} database is empty.</p> {% endif %} {% endblock %} client_list.html {% extends "listTemp.html" %} {% block h1 %}Clients{% endblock %} {% block modelName %}client{% endblock %} This is my first Django project and my first time working with HTML so my bad if it is obvious. I know what I have above is incorrect but how can I implement it? I have listviews and detail views for many models and they all have the exact same layout and the only difference in the files is the model name such as client.firstName and url 'client-detail' vs contractor.firstName and url 'contractor-detail' -
How can I store a complaint made by a user in my admin panel by django
what do I write in my views.py and forms.py to store the complaints by a user: This is how my site looks and this is where the users can input complaints. How can i save those complaints to later display, edit or delete them accordingly. How can I save those complaints in form of list in the admin panel. models.py: class Complaints(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.BooleanField(default=False) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title What do I write in my views.py and forms.py to do this. Please help me. The basic function is to accept complaints so that associated people can receive it and resolve the comlpaints accordingly. How do I make the views and forms so that we can accept these complaints and store them somewhere accordingly? -
How to add user roles on Signup?
my models.py ROLES = ( (1, 'student'), (2, 'creator'), (3, 'mentor') ) class User(AbstractUser): role = models.PositiveSmallIntegerField(choices=ROLES, default=1) forms.py ** class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) views.py def user_register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('login') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) I want to assign a role to every user which signs up, to make some permissions to restrict some type of users, i want t know how to add that role field in the signup so that a role can be given when a user registers and then permissions can be made accordingly, or if there is some better way to do it -
Why getting PostForm' object has no attribute 'user?
I am working on a small project containing two models User and Post.And a user can have multiple posts. I have created a custom form PostForm. When ever i am submitting the form it showing me the following error:- 'PostForm' object has no attribute 'user' views.py:- def add_post(request): print("addpost runn") if request.method == 'POST': post_form = PostForm(request.POST) print(request.POST) print("if part") if post_form.is_valid(): print(post_form) post_form.save(commit=False) post_form.user = request.user post_form.save() else: print("else part") post_form = PostForm() return render(request, "addpost.html", {"form": post_form}) forms.py:- class PostForm(forms.ModelForm): text = forms.CharField(label="Write Your Text Here", max_length=200, widget=forms.Textarea(attrs={'rows': 3})) created_at = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M:%S'], widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M:%S')) updated_at = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M:%S'], widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M:%S')) class Meta: model = Post fields = ['text'] def save(self, commit=True): print(self.cleaned_data) post = Post.objects.create_post( self.cleaned_data['text'], datetime.datetime.now(), datetime.datetime.now(), self.user, ) return post manager.py:- class PostManager(BaseUserManager): def create_post(self, text, created_at, updated_at, user, **otherfields): print(created_at) print(updated_at) print(text) post = self.model(text=text, created_at=created_at, updated_at=updated_at, user=user) post.save(using=self._db) return post -
Django elastic search consuming lot of memory
I have an EC2 instance having 32 GB RAM and I am using Django Elasticsearch DSL to use elastic search in Django for searching in Model objects. I have containerized the elastic search server. Below is the code from the docker YAML file to build the image. elasticsearch: image: elasticsearch:7.12.1 container_name: zinia-backend-elasticsearch ports: - "9300:9300" - "9200:9200" environment: discovery.type: "single-node" restart: unless-stopped networks: - backend But currently, I am facing the issue of high memory consumption by elastic search it is taking up to 16.5 GB of memory, and when other containers need more ram the system runs out of memory and stops responding and this becomes a critical issue for our team and project. Please, someone, guide the way to control it. Thanks in advance. -
how to get bytea images from postgresql database and display them in django?
This is how I created a table: sql_create_table = ''' CREATE TABLE IF NOT EXISTS images ( image_id text PRIMARY KEY, image bytea, name text )''' I have images and text data store in excel. I used openpyxl python library to read the excel data and insert them in the Postgres database. I looked at the database table and saw the image store as binary data. Now, How should I get bytea data and display them using HTML. Store.html <div class="w3-container w3-center"> {% load static %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <label>Image</label> <input type="file" name="image" value="{{image.0}}" class="file-upload"> <label>Name:</label> <input type="text" name="name" value="{{image_id.1}}"><br> <label>url:</label> <input type="text" name="url" value="{{name.2}}"><br> <button type="submit" value="update" name="update" class="file-upload-btn">Upload</button> </form> </div> Python libraries I used: import os from django.shortcuts import render, redirect import psycopg2 from openpyxl import load_workbook from openpyxl_image_loader import SheetImageLoader import PIL.Image as Image import base64 I connect to Postgres and get the table data from python. Look at my code, I convert binary to base64 since HTML doesn't support binary data. views.py def images_display(request): connection = connect_to_db() cursor = connection.cursor() sql = 'SELECT * FROM images;' cursor.execute(sql) results = cursor.fetchall() one_row = [] data = [] for value in results: for i … -
wanna join all tables in django
yet I'm a noob on Django. but I want to join every table in Django models. Here is some example on models.py (use inspectdb from MySQL ... cuz unable to add column(field) in Model) class Title(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(db_column='__title__', max_length=255) pages = models.IntegerField(db_column='__pages__') type = models.CharField(db_column='__type__', max_length=10) url = models.URLField(db_column='__url__', max_length=800) class Meta: managed = False db_table = 'title_' def __str__(self): return self.title class Author(models.Model): author_id = models.BigAutoField(db_column='artist_id', help_text='artist guestbook', primary_key=True) title_id = models.ForeignKey("Title", on_delete=models.CASCADE, db_column='Title_id', related_name="author_index") author = models.CharField(db_column='__author__', max_length=60) class Meta: managed = False db_table = 'author_' def __str__(self): return self.author and Series, Categories, etc.. has a foreign key to Title like Artist. I want to execute Django like SQL select t.id, t.__title__, group_concat(distinct ta.__author__ separator ', ') as __author__, (omitted) group_concat(distinct t2.category separator ', ') as __category__, from title_ t join artist_ ta on t.id = ta.Title_id (omitted) join (select title_id, concat(__prefix__, ': ', __name__) as category from category_) t2 on t.id = t2.title_id group by t.id order by t.id desc; but it's hard for Django.. plz help me. if title and artist like id title 1 python 2 java and title_id author 1 A 1 B 2 C Joined table on Django Models … -
Djangoissue with angular
I am trying to deploy my application using below tech stack. angular ( frontend ) and django ( backend ). When i am trying to access over https my app the backend is giving following error Not Found: / [05/Jul/2021 00:57:08] "GET / HTTP/1.1" 404 2356 [05/Jul/2021 02:42:50] code 400, message Bad request version ('À\x14À') [05/Jul/2021 02:42:50] You're accessing the development server over HTTPS, but it only supports HTTP. -
Dependent drop down on filter
Previously I implemented a dependent drop down on my model form (car manufacture to manufactures models) based on this blog post. Now I have a section on my site for users to view the cars with a filter for the manufacture to model. The only issue is that if you select a manufacture you have a list of every model not just the ones that are linked to that manufacture. If you could please point me in the right direction on how I would go about creating a dependent drop down on a filter. filter class carFilter(django_filters.FilterSet): class Meta: model = Post fields = 'manufacture', 'model' -
Django Foreign Key ["Incorrect type. Expected pk value, received str."]
The Company table has the basic contact information of the company, and the Address contains the address and geolocation of the company. These two tables are connected with a foreign key named "company_name," which is neither a primary key of both tables. I inserted some mock data of a company named "FF2" into the company table, it went great. However, when I attempted to insert "FF2" with its mock address into the Address table, I failed and received this: company_name: ["Incorrect type. Expected pk value, received str."] I tried every solution I found online, but none of them worked. Please help and be specific as possible, thank you so much!! model.py: class Address(models.Model): city = models.CharField(max_length=200) state = models.CharField(max_length=200) zip = models.CharField(max_length=20) address1 = models.CharField(max_length=200) address2 = models.CharField(max_length=200, blank=True, null=True) company_name = models.ForeignKey('Company', models.DO_NOTHING, db_column='company_name') lat = models.DecimalField(max_digits=50, decimal_places=6) long = models.DecimalField(max_digits=50, decimal_places=6) class Meta: managed = False db_table = 'address' class Company(models.Model): company_name = models.CharField(unique=True, max_length=200) contact_name = models.CharField(max_length=100) phone = models.CharField(max_length=100) email = models.CharField(max_length=100) website = models.TextField() class Meta: managed = False db_table = 'company' views.py: class AddressView(APIView): serializer_class = AddressSerializer def get(self, request): address = [ {"city": address.city, "state": address.state, "zip": address.zip, "address1": address.address1, "address2": address.address2, "company_name": …