Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF How to test file uploads?
I have a simple model, a serializer and a view. I want to upload a file over the view but no method I found worked. Here's my code: def test_api_post(self): lesson = self.Create_lesson() file = SimpleUploadedFile( "file.txt", "".join(random.choices(string.ascii_letters + string.digits, k=1024 * 5)).encode(), "text/plain" ) response = self.client.post( "/api/submission/", { "lesson": lesson.id, "file": file }, format="multipart" ) self.assertStatusOk(response.status_code) # Error I tried it using with open() as file and I also tried using path.read_bytes(). Nothing worked. How can I test binary file uploading with django-rest-framework's test client? doesn't work, https://gist.github.com/guillaumepiot/817a70706587da3bd862835c59ef584e doesn't work and how to unit test file upload in django also doesn't work. -
Get selected value from dropdown menu django displayed with for loop
I am building an upload app using Django where the user uploads a file, I display for the user the headers of the file, and the user has to map the headers of the file to my Django model attributes. I want to have access in the views.display_success_page function to the selection of the user in the drop-down menu mapping.html (approximate html) {% for header in file_headers %} <td>{{ header }}</td> {% for attribute in model_attributes %} <li> <a class="dropdown-item" id="attribute">{{ attribute }}</a> </li> {% endfor %} {% endfor %} <button>Submit</button> views.py def display_success_page(request): if request.method == "POST": selected_value = request.POST.get('attributes') return render(request, 'upload_success.html') I do not manage to find in request dictionary the 'attributes' id. I tried to build something with forms, but I don't know where to put the form. This -> Django:get field values using views.py from html form was not helpful because each user_selection is not unique, it does not have its own name. -
Django - Fetching entities whose many-to-many relationship contains all terms collectively
I am trying to create a Recipe API in django, I have tried to implement a many-to-many relationship between recipes and ingredients like so: models.py class Ingredient(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Recipe(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True) ingredients = models.ManyToManyField(Ingredient) How can I return recipes who's ingredients are a subset of a list of ingredients provided? e.g a recipe that contained only milk, sugar and eggs should be returned when queried with (milk, chocolate, ham, egg, sugar, cheese) along with other recipes who's ingredients are a subset of the list. -
encode base64 image upload is restricted by modsecurity
I started to face a problem of uploading image using encode base64 when I enabled mod-security I tried to change from #SecRequestBodyLimit 13107200 #SecRequestBodyNoFilesLimit 131072 to SecRequestBodyLimit 13107200 SecRequestBodyNoFilesLimit 13107200 the 413 error (HTTP Error: 413 Request Entity Too Large) stopped but still I cannot upload the image. -
Django Private Files - How to hide them
I am trying to add Firebase to Django, which works perfectly. However, I have to save a credentials file with my private keys and such. Currently I just have it saved in the project directory, however, how do I hide this file when uploading to Git for deploying onto something like Heroku? Basically, my question is how do I hide such files. Does it have something to do with Environment variables? -
Customizable Search Query REST API provided via Backend for Frontend [django.python]
I am currently working on some backend API's to service the frontend and return information from a MySQL database. I have http GET methods that can return a JSON object (queryset) based on a primary key(s) passed in the URL by the frontend team. The problem is, the search criteria are numerous (supplier name, price range, labels, service region, delivers or not.. etc). And I have no way of telling which of these filters the front end user will use to filter.. And it seems very redundant and wasteful (and difficult to maintain) to create a GET handler for each and every possible combination of used/unused search filters and return the desired JSON object(s) from the database. My question is - can the frontend pass a JSON object containing the search criteria along with the GET request? If not, what is the "standard" technique used for such scenarios.. I tried google but I have no idea what to look for. Stack Overflow is always a last-option resort since most people here are usually obnoxious and extremely unwelcoming of beginners. I hope this time changes my mind. -
Serializer.data not evaluating queryset in tests
I have such serializer class ActResultSerializer(serializers.Serializer): actions = serializers.SerializerMethodField() def get_actions(self, obj): return Actions.objects.filter(type='solution').values_list('code', flat=True) Here is my test case def test_return_to_provider(self): response = self.client.get('/acts/') self.assertEqual(response.status_code, 200) queryset = Act.objects.filter(deleted=False) self.assertEqual( len(response.data), queryset.count() ) self.assertEqual(response.data, ActResultSerializer(queryset, many=True).data) The problem is, that last assertEqual fails, because serializer data returns ('actions', <QuerySet []>). How can I evaluate that QuerySet to compare response and serializer datas? -
using custom Profile model field as keyword in url to give multiple people access to one account in django app
Here is the scenario I am working on: I have django app that creates records which I call sessions: blog.models.py class Session(models.Model): uid = models.CharField(max_length=50, blank=True) cid = models.CharField(max_length=50, blank=True) action_type = models.CharField(max_length=50, blank=True) action_name = models.CharField(max_length=50, blank=True) action_value = models.CharField(max_length=50, blank=True) session_date = models.DateTimeField(auto_now_add=True) client = models.CharField(max_length=50, blank=True) I have a dashboard page to show charts and a database page to show the records as a table: blog.urls.py path('', auth_views.LoginView.as_view(template_name='users/login.html'), name='blog-home'), path('<str:username>/dashboard/', views.dashboard and DashboardListView.as_view(), name='blog-dashboard'), path('<str:username>/database/', views.database and SessionListView.as_view(), name='blog-database'), So when you log in, my SessionListView.as_view() goes through the whole database and displays only those records where the Session.client == the url's 'username' value. Example: when user: DummyCo logs in (www.website.com/DummyCo/database/) they see only Session records where the Session.client field is 'DummyCo.' This has worked out great so far. But here is the problem: I now need to provide multiple logins to users to see the same dashboard and database page. Example: jim@DummyCo.com and amy@DummyCo.com both need to see the DummyCo records, but if I provided them with their own logins then their username's in the url would not match and thus the DummyCo records would not show. I thought using the built-in django Groups would be … -
Get user data into django channels, with sessions based authentication
I have user authentication based on django's sessions. (I have several reasons why I don't use default implemented User model) So, basically my simplified authentication view looks like: ... cursor = connection.cursor() cursor.execute("SELECT id, email FROM users WHERE ..") results = cursor.fetchall() request.session['user_id'] = results[0][0] request.session['user_email'] = results[0][1] return redirect('/success_page') This works but then I have problem with channels, when I need to access "user_id" value into consumers.py: Because it's impossible (as I understood) to access session data, outside of views and channels self.scope["user"] is also always AnonymousUser Question: is any way, to access user data into channel consumers, when I have authentication like this? -
How to use a field on a foreign key (another model) as part of my model primary key value
I'm new to Django and I feel sometimes it is not clear in which .py of myApp I should write solutions and examples I see. In my models.py I have a model called Project and a model called Order. In admin section (http://127.0.0.1:8000/admin/myApp/), I would like the user to type a project number when creating a new project. Every project can have multiple Orders. I would like the Order primary key to be composed of the Project number it belongs to, plus a consecutive number. The user can only change the consecutive number part of the Oder primary key but not alter the Project number the order belongs to. For instance for Project with project_number(primary key) = 951, Orders primary keys can be 951-1, 951-2, etc Another project with project_number(primary key) = 1015 can also have orders 1,2, etc but they won't conflict with orders of project 951 because they will be labelled 1015-1, 1015-2, etc. Is it possible to achieve this in models.py? How would I have to modify order_number field below? Notice I need the order_number field to fetch its project_number from order_project field and I won't know the order_project exact value until the user is creating the … -
List of correct urls not displayed in browser when in django debug mode
Normally in debug modewith django, if you type a bad url the browser displays an error message with the list of available urls. like it : Request Method: GET Request URL: http://127.0.0.1:8000/blorp Using the URLconf defined in bricole.urls, Django tried these URL patterns, in this order: admin/ accounts/ [name='home'] accounts/ simple/ (etc...) but in one of my projects, by typing a bad url I have the following result: Request Method: GET Request URL: <a href="http://127.0.0.1:8000/phot" target="_blank">http://127.0.0.1:8000/phot</a> Raised by: django.views.static.serve “C:\Users\Lou\PycharmProjects\photoglide\phot” does not exist and it does not display the list of available urls. in debug the list of urls is not displayed in browser I am with venv (django 3.1.2 and python 3.8 with pycharm) I compared the .py settings with that of a project for which the list of available urls is correctly displayed in the event of a url error and the only difference seems to be: the project where the url debug works : STATIC_URL = '/static/' STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))] STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles')) STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] ... and where the list of urls is displayed (the project where the url debug works fine): STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] It seems … -
Template Issue of Views.py
i am new to django.So i am trying to add a html template to the views.py but it is showing an error, it would be great if you would help me. The Error: TemplateDoesNotExist at / platform/home.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.8 Exception Type: TemplateDoesNotExist Exception Value: platform/home.html views.py: from django.shortcuts import render def home(request): return render(request, 'platform/home.html') urls.py: from django.contrib import admin from django.urls import path from django.conf.urls.static import static from django.conf import settings from Platform import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='Home'), ] settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] My HTML template that i am trying to add: <h1>This is my project</h1> -
Django complicated annotation/aggregation
Using Django 3.1 and Postgres, I'm trying to flatten some rows and I'm not exactly sure how to do it without raw sql. Let's say I have the following data in the table: | id | count | location_id | reading_id | |----|-------|-------------|------------| | 1 | 0 | 6 | 4382 | | 2 | 3 | 5 | 4382 | | 3 | 7 | 4 | 4382 | | 4 | 1 | 6 | 4383 | | 5 | 5 | 5 | 4383 | | 6 | 4 | 3 | 4383 | I want the output to be | location_3_count | location_4_count | location_5_count | location_6_count | reading_id | |------------------|------------------|------------------|------------------|------------| | NONE | 7 | 3 | 0 | 4382 | | 4 | NONE | 5 | 1 | 4383 | This is a simplified version, eachid has a Model with a name, etc. For each reading_id there are 0 to many location_ids, so it's a bit of a hassle. Anybody have any ideas? -
Using uwsgi.ini file in Django application
I am running a django app on a remote server. When I ssh into the remote server and try accessing the uwsgi-master logs I get a permission denied error. When I run the log access command with sudo I can access the log. This behavior is due to the default configuration of the uwsgi that I want to change to allow other users to read the logs. Based on https://serverfault.com/questions/602128/python-uwsgi-logs-have-no-read-permissions it seems like I want to create a .ini file with the updated permissions. Is there a way to configure django so that it will use uwsgi.ini file automatically (without running uwsgi --ini uwsgi.ini? I would prefer to not install the uwsgi package on the remote server. -
Using TabularInline showing different errors
I am trying to show the orderitemsadmin in the orderadmin using TabularInline but I keep getting different errors like the following error. AttributeError: 'OrderItemAdmin' object has no attribute 'urls' and django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed This is a Django e-commerce project and I am trying to facilitating the admin viewing the orders and their items. I don't have much experience in using TabularInline that is why I am not able to do it corrrectly or what might be the mistake that I am doing. Here is the admin.py class OrderItemAdmin(admin.TabularInline): list_display = ['item', 'quantity', 'ordered'] model = OrderItem raw_id_fields = ['item'] class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'coupon', 'payment', 'shipping_address', 'status', 'refund_requested', 'refund_granted', 'ref_code'] list_display_links = [ 'user', 'shipping_address', 'payment', 'coupon' ] list_editable = ['status'] list_filter = ['ordered', 'ordered_date', 'refund_requested', 'refund_granted', 'status'] search_fields = [ 'user__username', 'ref_code' ] actions = [make_refund_accepted] inlines = [ OrderItemAdmin, ] admin.site.register(OrderItem, OrderItemAdmin) admin.site.register(Order, OrderAdmin) Here is the models.py class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, ------------------------------------------------------ status = models.CharField(max_length=50, choices=[('pending', 'Pending'), ('ofd', 'Out For Delivery'), ('recieved', 'Recieved')], default='pending') def __str__(self): return self.user.username -
Problem with websocket, urlretrieve and Filefield django
I have one computer which creates a new image, and which sends the url by websocket to another server (with Django). The server can access the image. The problem is that the Django cannot save the image in the system when it is sent by the websocket, a new entry is only created in the database, but with a non-existent file. But the result of the urlretrieve has correct headers. When I execute the same code in the console of the django server, there is no problem. This is the code to save the image: result = urllib.request.urlretrieve(image_url) my_instance_model.my_field.save( os.path.basename(image_url), File(open(result[0], "rb")) ) lg_file.save() Why the server cannot save the content of the image when it is called by the websocket? How to fix the problem? Thank you! -
Does the model, the view or the serializer represent a REST resource in Django Rest Framework?
I am building an API using Django Rest Framework, and I'm trying to make it as RESTful as possible. Following this question (and also this question on SoftwareEngineering), I have described a number of resources that my API endpoints will expose, such as an Invoice that can be seen at the following URL: /api/v1/invoices/<invoicenumber>/ However, I am having trouble relating the RESTful design principles to the concrete workings of Django Rest Framework. It is unclear to me what constitues a resource: the model, the serializer or the view? In particular, I am confused about the correct place to implement my calculate_total() method. In a regular Django application it would certainly live in the the Invoice model: class InvoiceModel(models.Model): def calculate_total(self): # do calculation return total Although the actual calculation could be complex, the "total" is conceptually a part of the representation of the Invoice. In this sense, the resource is more equivalent to the InvoiceSerializer: class InvoiceSerializer(serializers.Serializer): total = serializers.SerializerMethodField() def get_total(self, obj): # do calculation return total Finally, the resource will always be accessed by a view. So you could also argue that the view is actually the resource, while the serializer and the model are simply implementation details: … -
How to modify Django models.DateTimeField type?
I am running an api server using django rest api. I want to change 2020-01-01T00:00:00+09:00 to 2020-01-01 00:00:00 in model. This is my model code.. from django.db import models class Data(models.Model): time = models.DateTimeField(auto_now_add=True) sensor = models.CharField(max_length=30) measure = models.IntegerField() def __str__(self): return self.sensor And my serializer code.. from rest_framework import serializers from .models import Data class MovieSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('id','time','sensor','measure') lastly my view from .models import Data from .serializers import MovieSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class DataList(APIView): def get_object(self, pk): try: return Data.objects.filter(sensor=pk) except Data.DoesNotExist: raise Http404 def get(self, request, format=None): dt = Data.objects.all() serializer = MovieSerializer(dt, many=True) return Response(serializer.data) def post(self, request, format=None): val = request.data.values() if val is not None: for i in val: snippet = self.get_object(i) serializer = MovieSerializer(snippet, many=True) return Response(serializer.data) I think I can't modify the code of view and serialize. I need a way to modify the type in the model. Thank you. -
What does this Django migration error message mean?
When I try to create migrations for the Django models shown below, I'm getting an error message I don't understand. I am trying to model a website member who can add one or more other members as either friends or followers. In addition, a member can block any other member. Here are my models: class Member(models.Model): FRIEND = "friend_of" FOLLOWS = "follows" RELATION_TYPES = ((FRIEND, "friend"), (FOLLOWS, "follower")) user = models.OneToOneField(User, on_delete=models.CASCADE) relations = models.ManyToManyField( "self", choices=RELATION_TYPES, through="MemberRelation" ) blocks = models.ManyToManyField("self", through="MemberBlock") def __str__(self): return self.user.first_name class MemberRelation(models.Model): source = models.ForeignKey( "Member", related_name="source_member", on_delete=models.CASCADE ) target = models.ForeignKey( "Member", related_name="target_member", on_delete=models.CASCADE ) relation = models.CharField(max_length=8) # Contains Member.FRIEND or .FOLLOWER def __str__(self): return "Member {} {} member {}".format(self.source, self.relation, self.target) class MemberBlock(models.Model): source = models.ForeignKey( "Member", related_name="blocker", on_delete=models.CASCADE, ) target = models.ForeignKey( "Member", related_name="blocked", on_delete=models.CASCADE, ) def __str__(self): return "Member {} is blocking Member {}".format(self.source, self.target) I started out with the Member and MemberRelaton classes and my migrations ran without any errors. But after I add the MemberBlock class and a blocks ManyToMany field in my Member model, I'm getting the following error when I run the makemigrations command which I don't understand: You are trying to change the … -
Django sum objects filtering another model
I have this 3 models: class Provider(models.Model): name = models.CharField("Provider",max_length=200) def __str__(self): return self.name class Contract(models.Model): active = models.BooleanField(default=False, verbose_name="Active?") provider = models.ForeignKey(Provider, on_delete=models.CASCADE,verbose_name="Provider") total_to_spent = models.IntegerField(blank=True, null=True, verbose_name="Total to spend") def __str__(self,): return str(self.id) + '- ' + str(self.provider) class Invoice(models.Model): contract = models.ForeignKey(Contract, on_delete=models.CASCADE,verbose_name="Contract",related_name='ContractObject',) value = models.IntegerField(verbose_name="Value") def __str__(self,): return str(self.contract) total_to_spent in Contract.model is the amount of money i can spent in that contract value in Invoice.model is the money related to that invoice that is then associated with the contract My view def ServicoView(request): contract_active = Contract.objects.filter(active=True) contratos_finish = Contract.objects.filter(active=False) context = { 'contract_active': contract_active, 'contratos_finish':contratos_finish, } return render(request, 'dashboard_servico.html', context) In my view i want to do the SUM of all invoices (value) related to one Contract for later compare to the total_to_spent to see if it passes the value or not -
How are arguments passed to view functions
I am reading a book on Django and see this blog example with the following files: views.py def post_share(request, post_id): # Retrieve post by id post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == 'POST': # Form was submitted form = EmailPostForm(request.POST) if form.is_valid(): # Form fields passed validation cd = form.cleaned_data post_url = request.build_absolute_uri(post.get_absolute_url()) subject = f"{cd['name']} recommends you read {post.title}" message = f"Read {post.title} at {post_url}\n\n" \ f"{cd['name']}\'s comments: {cd['comments']}" send_mail(subject, message, 'admin@myblog.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent}) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('<int:post_id>/share/', views.post_share, name='post_share'), ] template {% extends "blog/base.html" %} {% block title %}Share a post{% endblock %} {% block content %} {% if sent %} <h1>E-mail successfully sent</h1> <p> "{{ post.title }}" was successfully sent to {{ form.cleaned_data.to }}. </p> {% else %} <h1>Share "{{ post.title }}" by e-mail</h1> <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Send e-mail"> </form> {% endif %} {% endblock %} I am struggling to understand how the parameter post_id get passed into views.py. I see it appears in the urls.py in the path … -
After login not authenticated in Django
i wanted to create login functionality on my website. I did it with help of one tutorial (i use 'django.contrib.auth' app so i didn't create any own views yet), but when i log in, i get information that user is not logged (only authentication is not working because i see on admin panel i am logged succesfully). What should i change? My code: login.html <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Log In</button> </form> homepage.html {% block content %} {% if user.is_authenticated %} Hi {{ user.username }}! {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> {% endif %} {% endblock %} urls.py from django.contrib import admin from django.urls import include, path from django.contrib.auth import views from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='homepage.html'), name='homepage'), settings.py LOGIN_REDIRECT_URL = 'homepage' Everything is working good, templates etc, but this authentication not, i get information "You are not logged in" which is displayed when user is not authenticated. Could someone help me? I do something wrong probably. -
How to check session.modifed = True in response object in Django test?
[django 1.4, python 2.7] We have a custom session engine that stores session to redis (Pretty much the same as db session engine, just stores in redis). There are some public endpoints that the session middleware stores a session to redis (session.modified is set to True), which is not our intention. I am trying to write unit tests to check which endpoints do generate session. # This endpoint would always save session to redis def test_endpoint(request, **kwargs): request.session['asdfsaf'] = 1 # Or, request.session.modified = True (Both fine) return httplib.OK, "good" Attempt 1: response = self.client.post(reverse('test_endpoint', kwargs=self.kwargs), data={...}) print(response.status_code, response.content) # Ok print('am i modified?', self.client.session.modified) # False for i in range(10): redis = get_redis_instance(db=i) print("redis key", i, redis.keys()) # All return empty redis This unit test is unable to detect a session is saved via django session middleware. probably due to the fact that a new SessionStore is created every time this property is accessed (https://docs.djangoproject.com/en/2.2/topics/testing/tools/#persistent-state) Attempt 2: Taking inspiration from SessionMiddlewareTests: request = RequestFactory().post(reverse('test_endpoint', kwargs=self.kwargs), data={...}) response = HttpResponse('Session test') middleware = SessionMiddleware() middleware.process_request(request) # Handle the response through the middleware response = middleware.process_response(request, response) print('am i modified', request.session.modified) # False for i in range(10): redis = get_redis_instance(db=i) print("redis … -
Getting the value in a field in the json object that comes in tabular form with django
I get the data from the postgresql table as json as follows. But for example in the data coming in json; I want to display the data in the "symbol" field in the "for" loop. How can I do that ? So more than one data is coming and I want to print it on the screen one by one. [ {"model": "cryptoinfo.cryptoinfo", "pk": 4, "fields": {"createdDate": "2020-10-08T20:49:16.622Z", "user": 2, "created_userKey": "25301ba6-1ba9-4b46-801e-32fc51cb0bdc", "customerKey": "61754ecf-39d3-47e0-a089-7109a07aca63", "status": true, "side": "BUY", "type": "1", "symbol": "NEOUSDT", "quantity": "1", "reversePosition": "1", "stopMarketActive": "1", "shortStopPercentage": "1", "longStopPercentage": "1", "takeProfit": "1", "addPosition": "1", "takeProfitPercentage": "1", "longTakeProfitPercentage": "1", "shortTakeProfitPercentage": "1", "groupCode": "1453", "apiKey": "2200", "secretKey": "0022"}}, {"model": "cryptoinfo.cryptoinfo", "pk": 7, "fields": {"createdDate": "2020-10-08T20:51:16.860Z", "user": 1, "created_userKey": "2f35f875-7ef6-4f17-b41e-9c192ff8d5df", "customerKey": "b1c8cee3-c703-4d27-ae74-ad61854f3539", "status": true, "side": "BUY", "type": "1", "symbol": "NEOUSDT", "quantity": "1", "reversePosition": "1", "stopMarketActive": "1", "shortStopPercentage": "1", "longStopPercentage": "1", "takeProfit": "1", "addPosition": "1", "takeProfitPercentage": "1", "longTakeProfitPercentage": "1", "shortTakeProfitPercentage": "1", "groupCode": "1453", "apiKey": "0011", "secretKey": "1100"}} ] def webhook(request): json_body = json.loads(request.body) queryset = CryptoInfo.objects.filter(status=True, symbol=json_body['symbol'], side=json_body['side']) data = serializers.serialize('json', queryset) print(data['symbol']) return HttpResponse(data, content_type='application/json') -
Implement Google Analytic on Website Django
I am looking to integrate Google Analytic in django website in html page or in django admin. I need to show the show data in Graphical format on Separate HTML Page. The Graphical data will be based on number of visitor on page in a month. My Website is purely based on Python Django.