Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django_admin_log is not getting created in Oracle and giving ORA-00955
i have been trying to do below steps and all the migrations except my custom apps are getting failed with ORA-00955 error saying name is already used by an existing object. When i search in oracle dba_tables i don't find DJANGO_ADMIN_LOG table i have executed below steps which is failing: python manage.py makemigrations python maange.py migrate admin django.db.utils.databaseerror ora-00955 name is already used by an existing object ***************************** while i am able to perform python manage.py migrate myapp same happening for other objects like auth and session. Any help is appreciated?? -
mongoengine update listed's embeddedfield, just update the first
mongo collection as follow: { "_id" : ObjectId("5eedb36d6cd00ed8e8748cc7"), "user" : "5", "search" : [ { "name" : "first", "status" : 1 }, { "name" : "second", "status" : 0 }, { "name" : "third", "status" : 0 } ] } and models: class HistoryItem(models.EmbeddedDocument): name = models.StringField() status = models.IntField() class History(models.Document): user = models.StringField(unique=True) search = models.EmbeddedDocumentListField(HistoryItem, default=[]) I want to update all status to 1, I try this: mongo_models.History.objects(user="5", search__status=0).update(set__search__S__status=1) but just update the first element which status is 0, what should I change my code update all element's status to 0 ? thanks. -
How to fetch image from temporary storage in Django
I am new at Django. I am uploading images in temporary storage using tempfile but i am now confused how to fetch that image and show on html side. views.py temp = tempfile.mkdtemp() predictable_filename = 'myfile' temporary_location = os.path.join(temp,predictable_filename) def upload_multiple_image(request): if request.method == 'POST': form = UploadFaceImageForm(request.POST,request.FILES) if form.is_valid(): request.session['name'] = file_name request.session['image'] = request.FILES['image'].name with open(temporary_location + file_name, "w") as tmp: tmp.write(file_name) return redirect("show_image") else: return render(request, 'camera/upload_knowface_images.html') def show_image(request): pass How to fetch image in show_image function -
Cannot load DetailView template . URL is generated incorrectly
I am a beginner in Django and I am learning CBV's. I used Django' built in User class to create several users on my website and then i created the following views below . The url generated for my user_list view is http://127.0.0.1:8000/basicapp/user_list/ and works. It shows the users The url generated my user_detail view is http://127.0.0.1:8000/basicapp/1/ (2,3...and so one) and works when manually entered. It shows the user detail The problem is this: In the user_list.html, i add : <a href="{{person.id}}"and In the url.py I add: url(r'^(?P<pk>[-\w]+)/$',views.UserDetailView.as_view(),name='detail') So, when the user list page loads with my users as links , when i hover over the links i get a path like: http://127.0.0.1:8000/basicapp/user_list/1 - this link does not work. I click on it and does not do anything I should be geting : http://127.0.0.1:8000/basicapp/1 . This link does work because i tested it manually. I think I am doing womething wrong in the urls.py but i am not sure. The regex i took was from a training video and have only a general idea about it does. basicapp/views.py: from django.contrib.auth.models import User from django.views.generic import View,TemplateView,ListView,DetailView class UserView(ListView): context_object_name='users' model=models.User template_name='basicapp/user_list.html' class UserDetailView(DetailView): context_object_name='user_detail' model=models.User template_name='basicapp/user_detail.html' basicapp/urls.py: from django.conf.urls import … -
Django OneToOneField not creating table
Thanks in advance, that.s my users/models.py file : from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return "{} profile".format(self.user.username) Then I run python manage.py makemigrations + python manage.py migrate, everything seems to works fine but it doesn't create a table users_profile : 1146, "Table 'polls_db.users_profile' doesn't exist") in the admin section + same when i try to manipulate profile threw the shell. I checked my mariadb database and there is indeed no users_profile table. I'm still learning django and it worked fine in a previous project with an sqlite database, is there a solution ? -
How to add pagination to a filtered table?
Below is the sample code I have for a page that shows a data table with crud options to edit, update, delete entries. I added django filters and it is filtering the data and displaying the queryset however I am unable to add pagination to the page. Can you please help advice how to add it. Also I am showing filters as a form however is it possible to add them individually so that I can format them.. Template: <div> <form action="" method="GET"> {{ mytablefilters.form }} *# Is it possible to show the elements separately so that they can be arranged and formatted easily* <button type="submit">FILTER DATA</button> <Table> <thead> <tr> <th> Employee Name </th> <th> Employee Email </th> <th> Employee Status </th> </tr> </thead> </tbody> {% for entry in tablefilters.qs %} <tr> <td>{{entry.employeename}}</td> <td>{{entry.employeeemail}}</td> <td>{{entry.employeestatus}}</td> </tr> </tbody> Views.py from .filters import mytablefilters from django.views.generic.list import ListView class tablenameview(ListView): model = tablename template_name = 'Index.html' def get_context_data(self, **kwargs): context=super().get_context_data(**kwargs) context['mytablefilters'] = mytabelfilters(self.request.GET,queryset=self.get_queryset()) return context Thank you so much! -
Django - Font sizes in saved form fields on initial page load are small until click / keystroke
I've noticed some strange behavior with my login page. On initial page load, the form fields with pre-populated saved values have smaller text than normal. Once you click on the page or push any key, the text pops back to its normal font size. login.html (simplified) {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container-fluid"> {% crispy form %} </div> {% endblock %} base.html (simplified) {% load static %} <!doctype html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- IE support --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content=""> <meta name="author" content=""> <!-- Allow web app on Chrome --> <meta name="mobile-web-app-capable" content="yes"> <!-- Import Jquery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Backup local file --> <script> window.jQuery || document.write('<script src="{% static 'js/jquery-3.5.1.min.js' %}"><\/script>'); </script> <!-- Import Bootstrap core files --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <!-- Import confirmation / alert box JS files --> <script src="{% static 'js/bootbox.min.js' %}"></script> <script src="{% static 'js/bootbox_common.js' %}"></script> <!-- Font Awesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- Custom CSS --> <link href="{% static 'css/base.css' %}" rel="stylesheet"> <!-- Page-specific imports --> {% block headimport %}{% endblock %} <!-- Allow styling of unknown HTML elements … -
Django refusing to serve NEWLY ADDED static files
The problem Django is acting weird. I built a website a month ago. I have a static/img folder in my app, with a bunch of logos and images in it. I refer to them with <img src="{% static 'img/logo-elephant.png' %}"> And it works. However, I added a new file to the very same folder, and when I refer to it, <img src="{% static 'img/white-logo.png' %}"> it gives me a 404 error. I am completely stumped. Its like newly added files are invisible to Django. Even if I copy an existing file and rename it to something, it raises a 404 error. Stuff I already tried Printing the STATIC_ROOT to make sure it's pointing to the static folder of my app. It is. Running collectstatic. Though it shouldn't make a difference, this is a development server, but I ran it just for good measure. -
when i request Django URL i got this error (module 'json' has no attribute 'JSONDecoder')
AttributeError at / module 'json' has no attribute 'JSONDecoder' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.7 Exception Type: AttributeError Exception Value: module 'json' has no attribute 'JSONDecoder' Exception Location: E:\Blogs\ll_env\lib\site-packages\django\contrib\messages\storage\cookie.py in , line 27 Python Executable: E:\Blogs\ll_env\Scripts\python.exe Python Version: 3.8.3 Python Path: ['E:\Blogs', 'C:\Python\python38.zip', 'C:\Python\DLLs', 'C:\Python\lib', 'C:\Python', 'E:\Blogs\ll_env', 'E:\Blogs\ll_env\lib\site-packages'] Server time: Sat, 20 Jun 2020 07:35:39 +000 -
Python Django edit record function not working with Jquery Ajax
Context: I have a table in HTML with some data for a specific user. Next to each row there is a delete and an edit button. I want the buttons to do what they are supposed to the certain row. Currently the delete button is working, and I tried a similar approach for the edit button, but when clicked nothing happens. This is part of the HTML: {% for work_entry in work_entries %} {% if work_entry.date == date.date %} <form method="POST" id="{{ work_entry.id }}"> {% csrf_token %} <tr> {% if work_entry.is_paid == False %} <td> <button class="delete-button" id="{{ work_entry.id }}" style="background-color: #bb1a1a;" onclick="return confirm('Please confirm you wish to delete the selected record.')">Delete </button> </td> <td> <button class="edit-button" id="{{ work_entry.id }}" style="background-color: #5dbb1a;" onclick="return confirm('Please confirm you wish to edit the selected record.')">Update </button> </td> <td>{{ work_entry.project }}</td> <td><input style="border: none" class="table-input" type="text" id="description-{{ work_entry.id }}" value="{{ work_entry.description }}"></td> <td><input type="number" class="table-input" step="0.01" id="hours-{{ work_entry.id }}" value="{{ work_entry.num_hours }}"></td> This is the js: (Sorry its a little long but should be straight forward) $(document).ready(function () { $(".delete-button").click(function (e) { var id = $(this).attr('id') e.preventDefault(); $.ajax({ type:'POST', url:'{% url 'work_entries:object_delete' %}', data:{ id: id, action: 'post' }, beforeSend: function(xhr) { xhr.setRequestHeader("X-CSRFToken", "{{ … -
How to compare two specific values of different table in Django
Please guide me how I can compare show.city with form.city which the user enter now Is it possible using javascript on frontend if not then please tell me how its possible. {% extends 'base.html' %} {%load crispy_forms_tags %} {% block title %} | Courier {% endblock %} {% block content %} <!-- Breadcrumb --> <section id="bc" class="mt-3"> <div class="container"> <nav> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="{% url 'home' %}">Home</a> </li> <li class="breadcrumb-item active">Courier Payment</li> </ol> </nav> </div> </section> <section id="register" class="bg-light py-5"> <div class="container"> <div class="row"> <div class="col-md-6 mx-auto"> <div class="card"> <div class="card-header bg-primary text-white"> <h4> <i class="fas fa-user-plus"></i> Post User Info</h4> </div> <div class="card-body"> <!-- Alert --> <form method="POST" enctype="multipart/form-data" > {% csrf_token %} <div class="form-group"> Title : {{ show.title}} </div> <div class="form-group"> City : {{ show.city}} </div> <div class="form-group"> Area : {{ show.area}} </div> </form> </div> </div> </div> </div> </div> </section> <div class="row"> <div class="col-sm-5"> <p><input type="text" id="first_input" onkeyup="compare_input();" class="form-control" placeholder="Write First Text" /></p> </div> </div> <section id="showcase"> <div class="container"> <div class="home-search p-5"> <div class="overlay p-5"> <h1 class="display-4 mb-4"> Add your Location </h1> <div> <form method="post" enctype="multipart/form-data" id="personForm" data-cities-url="{% url 'ajax_load_areas_products' %}" novalidate > {% csrf_token %} <div class="row"> <div class="col-md-6"> {{ form.city | as_crispy_field }} </div> <div … -
How to handle nested foriegn keys in django rest
I am working on a API that has several models, each having a foreign key to its parent. I have figured out how to write the models as well as the serializers file. But I can not figure out how to work around the views file, where I can POST as well as GET data at any level. The tutorials for DRF are quite tricky with only one/two models. Here is my models.py: class Plant(models.Model): plant_name = models.CharField(max_length=200) start_date = models.DateTimeField() end_date = models.DateTimeField() def __str__(self): return(self.plant_name) class Unit(models.Model): plant = models.ForeignKey(Plant, related_name='Units', on_delete=models.CASCADE) unit_name = models.CharField(max_length=200) unit_location = models.CharField(max_length=200) start_date = models.DateTimeField() end_date = models.DateTimeField() def __str__(self): return(self.unit_name) class EquipmentCategories(models.Model): unit = models.ForeignKey(Unit,related_name='Categories',on_delete=models.CASCADE) category_name = models.CharField(max_length=200) def __str__(self): return(self.category_name) class Equipment(models.Model): category = models.ForeignKey(EquipmentCategories,related_name='Equipments', on_delete=models.CASCADE) equipment_name = models.CharField(max_length=200) def __str__(self): return(self.equipment_name) I want to write views file such that I can add/view data at any level. Thanks in advance for all the answers. -
AttributeError at /updateprofile 'ReverseOneToOneDescriptor' object has no attribute '_meta'
i have one model userprofile which is connected to User by onetoone relationship. i am trying to create combined form for both user and userprofile form but it is showing onetoonedescripter has no attribute _meta. views.py ''' def UpdateProfile(request): if request.method =='POST': EUF_form = EditUserForm(request.POST, instance=request.user ) EPF_form = EditProfileForm(request.POST, instance=request.user.Profile ) if EUF_form.is_valid() and EPF_form.i_valid(): EUF_form.save() EPF_form.save() return HttpResponse("Profile updated succesfully.") return render(request, 'profile_page.html') else: EUF_form = EditUserForm(instance=request.user) EPF_form = EditProfileForm() return render(request, 'edit_profile.html', {'EUF_form':EUF_form, 'EPF_form':EPF_form}) ''' models.py ''' class User_Profile(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) mobile = models.CharField(max_length=20, blank=True) bio = models.CharField(max_length=300, default='') avatar = models.ImageField(upload_to='avatars', blank=True) birthday = models.DateField(blank=True, default='1990-12-01') website = models.CharField(blank=True, max_length=256) gender = models.CharField(blank=True, max_length=20, choices=[('M','Male'), ('F','Female'),('O','Other')]) def __str__(self): return self.user.username ''' forms.py ''' class EditUserForm(ModelForm): first_name = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'first_name'}), label="First Name") last_name = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'last_name'}), label="Last Name") username = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'username'}), label="Username") email = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'email'}), label="Email") class Meta: model = User fields = ['first_name','last_name','username','email'] class EditProfileForm(ModelForm): mobile = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control','type':'tel','name': 'mobile'}), label="Phone number") bio = forms.CharField(widget=forms.Textarea, label="Bio") birthday = forms.DateField(widget=forms.DateInput( attrs={'class': 'form-control','type':'date','name': 'birthday'}), label="Username") website = forms.URLField(widget=forms.URLInput( attrs={'class': 'form-control','type':'url','name': 'website'}), label="website") gender = forms.ChoiceField(choices=[('M','Male'), ('F','Female'),('O','Other')], widget=forms.Select , label="gender") class Meta: model = User_Profile … -
Django: Get size of JSONField?
I'm using Django + Postgres. I have a JSONField and I'd like to actually sort the JSONField by size of character count from largest to smallest. Is there a django native way to do this? -
Nginx 502 Bad gateway - gcp
I am trying to deploy my Django website on google cloud using tutorial (https://cloud.google.com/python/django/appengine#cloud-console) My website is working smoothly on local host as well on Heroku (Free). But when i try to deploy my website on GCP, deployment finishes without any error. But access to website using the link provided by GCP gives mei 'nginx 502 Bad Gateway' error. I assume, error is because its listening to 'http://0.0.0.0:8081'. Can anyone please help. Below are my logs: Traceback from GCP website. 2020-06-20 12:02:57.759 IST Traceback (most recent call last): File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 92, in init_process super().init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/env/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/opt/python3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'main' Expand all | Collapse all{ insertId: "5eedad99000b96b31054c1f8" labels: { clone_id: "00c61b117ceed98b6a28aa8b70411a0a5acbb82696fd9c6894b1680eeaf75adfbafe66" } … -
Not able to load static files in DJANGO app using AWS EC2
I successfully deployed the Django App on AWS EC2 using gunicorn and NGINX server. But the static files even after configuring the django.conf file in /etc/nginx/sites-available/ are not getting loaded into the templates. django.conf file: server{ listen 80; server_name my_server_name; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/learning-aws/app.sock; } location /static/ { autoindex on; alias /home/ubuntu/learning-aws/myprofile/core/static/; } } settings.py file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'core/static/') Template Tags used(eg. base.html): {% static 'plugins/bootstrap/bootstrap.min.css' %} -
Downloaded bootstrap runs in firefox but not in chrome in django project
When i kept cdn links for bootstrap it ran just fine but when I downloaded bootstrap and kept in my project it works fine in firefox but does not work properly in chrome like some functionality are there like when I resize the browser the links goes and can be opened from navigation button. <!doctype HTML> {% load static %} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Portfolio</title> </head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> </div> <div class="nav-header"> <a class="navbar-brand" href="#">Navbar</a> </div> <div class="collapse navbar-collapse" id="navbarSupportedContent1"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#"><i class="fab fa-twitter-square"></i></a> </li> <li class="nav-item"> <a class="nav-link" href="#"><i class="fab fa-facebook"></i></a> </li> <li class="nav-item"> <a class="nav-link" href="#"><i class="fab fa-linkedin"></i></a> </li> <li class="nav-item"> <a class="nav-link" href="#"><i class="fab fa-github"></i></a> </li> </ul> … -
Best Way To Serve Images in Django 3.0?
So I 'm working on a project in django - it's like a variation of a blog. There will be 4 mini blogs within the website and the admin for each can create new posts - so they can also add an image to their post. Now that django has recently been update (django 3.0 is here), I was wondering, what is the best way to store and serve these images in production? Could someone maybe link to a part in the documentation? I don't think this will come under staticfiles will it? I searched the documentation with keywords like "Media", "Serving images" etc but didn't really find much. -
Add extra field in manytomany relationship in django
I am try to create Model of my application but confused in the layout class Product(models.Model): name = models.CharField(max_length=500, default=0) short_code = models.CharField(max_length=500, default=0,unique=True) class Kit(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) kit_name = models.CharField(max_length=500, default=0) product = models.ManyToManyField(Product) Now a person can add multiple products in the app and a Kit can have multiple products, the problem starts here.. I want to add quantity field to the Kit model such that a person can add a particular item and its quantity in a kit. How do I do that ? -
AJAX how to call $ajax() error: function from django
I am a beginner in web development. I am trying to make a website that has like a comment module where the user can like the comment and updating total upvotes using ajax. But somehow ajax error function is not getting called even when error. only the success function is getting called no matter what. I don't know how to make it work here is ajax code: function upvotecomment(postid, commentid, votes_total){ $('#upvotingcmt').one('submit', function(event){ event.preventDefault(); console.log(event) console.log("form submitted!") // sanity check upvotingcomment(postid, commentid, votes_total); }); } function upvotingcomment(postid, commentid, votes_total) { $.ajax({ url : "upvotecomment/"+postid+"/"+commentid, // the endpoint type : "POST", // http method // handle a successful response success : function(json) { votes_total += 1; console.log(json); // log the returned json to the console $('#totalupvotes').text(votes_total); console.log("success"); // another sanity check }, // handle a non-successful response error : function(xhr,errmsg,err) { console.log('error'); console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }); }; here is Django view function: @login_required(login_url="/accounts/signup") def upvotecomment(request, post_id, comment_id): if request.method == 'POST': post = get_object_or_404(Post, pk = post_id) comment = get_object_or_404(Comment, pk = comment_id) response_data = {} if comment.user.username == request.user.username: messages.error(request, "Commenter can't upvote their … -
Convert PNG to SVG in Python
How do I convert a .PNG to .SVG in Python? Should I use the pyCairo library? Please help me write the code. -
Module not found,
I am learning Django and I am facing difficulties as i am not able to import the functions from other python files.enter image description here -
Does iterator provide improvement when used together with values_list?
Recently I saw code which used together iterator() and values_list(). Does it make sence to use them both together? Will it improve speed or memory usage? Sample code: Customer.objects.values_list("pk", flat=True).iterator() -
How do I implement Google Sign in for my app which has an android frontend and a Django back end?
The backend is on Django on a server, which has all the user profile data. The front end is the android application which will run on the user's phone. I want to implement google sign in (using Google OAuth2), so that the user signs in and can now be considered by the server to be authenticated. As far as I understand, the Google OAuth2.0 flow will happen like this: 1) The user clicks on "Sign in with Google". This sends the client_id (will this be the client ID of my backend application which I registered on google dev console?) and the redirect url (will this be a url to a view on my backend app?) to the google oauth site. 2) The front-end now gets the auth_code which it sends to the backend server 3) The backend uses the client_secret, client_id, auth_code and sends it to google oauth site. 4) The backend now has the access_token, which it sends to the front-end. The front-end now has the access_token. 5) How is the front-end authenticated when it sends an API request for data to the backend? What can I use for Django and Android to implement this specifically? -
TypeError 'Purchase' object has no attribute '__getitem__'
views.py def vendor(request,pk): current_shop = get_current_shop(request) instance =get_object_or_404(Vendor.objects.filter(pk=pk,shop=current_shop,is_deleted=False)) vendor = instance.pk purchases = Purchase.objects.filter(vendor=instance,is_deleted=False,shop=current_shop) vendor_return = VendorReturn.objects.filter(vendor__pk=pk,shop=current_shop).values('id','return_date','total','date_added') transaction = Transaction.objects.filter(shop=current_shop,is_deleted=False,vendor=instance).values('transaction_category__name','time','amount','date_added','vendor') product_schemes = ProductScheme.objects.filter(vendor=instance,is_deleted=False,from_purchase=False).values('date_added','total_amount') price_drops = VendorProductPriceDrop.objects.filter(vendor=instance).values('date_added','drop_amount') result_list = sorted(chain(transaction, purchases, product_schemes, price_drops, vendor_return),key=itemgetter('date_added'),reverse=True) context = { "instance" : instance, "purchases": purchases, "vendor_return": vendor_return, 'product_schemes': product_schemes, "price_drops": price_drops, "transaction": transaction, 'result_list': result_list, "title" : "Vendor : " + instance.name, "single_page" : True, } return render(request,'vendors/vendor.html',context)