Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with passing dynamic data to Chart.js in Django
i want to use data that i get from an API (numbers) and generate a bar chart with it. This is my views.py : import requests import os import json from django.http import JsonResponse, HttpResponse from django.shortcuts import render def btc(request): query_url = [ 'https://api.blockchair.com/bitcoin/stats', 'https://api.blockchair.com/ethereum/stats', 'https://api.blockchair.com/litecoin/stats' ] headers = { } result = list(requests.get(u, headers=headers) for u in query_url) json_data1 = result[0].json() json_data2 = result[1].json() json_data3 = result[2].json() labels = ["Bitcoin", "Ethereum", "Litecoin"] data = [json_data1['data']['transactions'], json_data2['data']['transactions'], json_data2['data']['transactions']] context = { "labels": labels, "data": data, } return render(request, "index.html", context) and this is in my index.html : <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script><script> var config = { type: 'pie', data: { datasets: [{ data: {{ data|safe }}, backgroundColor: [ '#ff0000', '#0000ff', '#ff0080', '#73ffff', '#5c26ff', '#002db3', '#ffff26', '#4cff4c', '#ff00ff' ], label: 'Population' }], labels: ["Bitcoin", "Ethereum", "Litecoin"] }, options: { responsive: true } }; window.onload = function() { var ctx = document.getElementById('pie-chart').getContext('2d'); window.myPie = new Chart(ctx, config); }; </script> the problem is in {{ data|safe }} it works perfectly if i use Hardcoded data but when i try calling the data from the views.py i have an error. -
How to authenticate ngrok password automatically using Django and or Python?
I am using ngrok to expose my localhost on a raspberry pi, and ngrok is password protected. I am using Django on another computer outside my network to access a webpage(simple server) on this raspberry pi. I don't want to manually type in the username and password to ngrok. How can I automatically fill in the ngrok user/password? What I've tried: I first tried using JS in my template, just using a fetch request: https://user:password@myngrokdomain.ngrok.io but chrome threw an error in the console saying I can't pass in credentials in plain text like this, rightfully so... I then tried to use my Django view, and python requests: @login_required def cameraTest(request): UN= "myuser" PWD = "mypassword" loginURL = "https://myngrokdomain.ngrok.io" client = requests.session() client.get(loginURL) login_data = dict(username=UN, password=PWD,) header_data = dict(referer = loginURL) r = client.post(loginURL, data=login_data, headers = header_data) return TemplateResponse(request, 'cameraTest.html',) This didn't give an error, but it returned a 401 access denied from ngrok. Is there a simpler way to do this? I feel like javascript is probably the answer but I also can't seem to figure out a way to do it that doesn't involve passwords in plain text in the script. -
Install tailwindcss + svelte with webpack in django
How do we add Tailwindcss with webpack while I have Svelte (or any other js framework) already install with webpack in Django? Note: I want to install with Webpack not with any Django libs. -
Django reverse foreign key values aggregate
I have two models, class UploadedMedia(models.Model): owner = models.ForeignKey(Account, on_delete=models.CASCADE) media_url = models.URLField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField( blank=False, unique=True, db_index=True, max_length=255, help_text="Designates the email address and user name of the account.", ) name = models.CharField( blank=True, unique=False, db_index=False, max_length=255, help_text="Designates the full name of the account.", ) I need to show max(created_at) for each record in Account model. Since it is a reverse foreign key I don't understand how can I achieve it. Please advise. -
Unable To Install Simple JWT in my Django Project
Here's my setup right now: Pip Freeze: asgiref==3.3.1 Django==3.0 djangorestframework==3.10.0 djangorestframework-simplejwt==4.6.0 PyJWT==2.0.1 pytz==2021.1 sqlparse==0.4.1 Settings.py from pathlib import Path INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'snippets.apps.SnippetsConfig', ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework_simplejwt.authentication.JWTAuthentication',], 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny','rest_framework.permissions.IsAuthenticatedOrReadOnly',) } When I run $ python manage.py runserver I get this error ImportError: Could not import 'rest_framework_simplejwt.authentication.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'rest_framework_simplejwt'. I have tried importing it at the top of settings.py like this import rest_framework_simplejwt and have tried adding it to my installed_apps. Nothing is working. Any help here would be greatly appreciated. Also, I'm following this guide: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html -
Can I add a search box to a Django Admin Add page?
In a Django 3.0 app, I have a Donor Model with a foreign key to the donor's congressional district: # models.py class Donor(models.Model): """A class to represent an individual donor""" name = models.CharField( help_text = "Donor's name" ) district = models.ForeignKey( District, help_text = "Donor's congressional district" ) class District(models.Model): """A class to represent a U.S. congressional district""" dist_name = models.CharField( help_text = "District name" ) In the Admin Add page for Donor, there's a drop-down selection menu for District. The problem is that there are 435 congressional districts in the U.S. That's an awful lot to scroll through each time I add a Donor, so I'd like to add a search box. Django has the ability to define search fields. I tried to do so: # admin.py @admin.register(Donor) class DonorAdmin(admin.ModelAdmin): search_fields = ['district'] This did not affect the Donor Add page. 'District' still shows up as an enormous drop-down, and there are no search features anywhere on the page. The search_fields documentation says specifically Set search_fields to enable a search box on the admin change list page. Emphasis mine: search_fields seems to apply to only the Change List page, not the Add page. I assume this is why my … -
Django Unit Testing: AssertEqual Does not compare PermissionDenied with 403 and Terminates Prematuraly inside get_object()
I'm really hoping you may shed some light on a puzzling situation I am in with my unit testing of my post views. I am basically trying to test different post permissions depending on the user, ex: guest (anonymous), member (registered), and member who are mutually following each other (friends) When I run the unit test, it is erroring on the function that tests if a member (registered user) can view a post that is only meant to be visible to friends (mutually following each other): ====================================================================== ERROR: test_member_user_post_detail_friends_permission (journal.tests.test_views.TestPostDetailView) ---------------------------------------------------------------------- When I follow the line where the exception is taken place, it leads me to my get_object() of PostDetailView class where the testing seems to end prematurely (line marked below): def get_object(self, queryset=None): obj = super(PostDetailView, self).get_object(queryset=queryset) # Logged in user's friends ids (Users who they are following) my_friends = Follower.objects.filter(user_id=self.request.user.id).values( "follow_to" ) # Post owner's friends id (Users who the post owner is following) their_friends = Follower.objects.filter(user_id=obj.user.id).values("follow_to") if obj.permission == "friend": # viewable only by friends or staff/moderators if self.request.user.is_authenticated: if self.request.user.is_staff or self.request.user.is_moderator: return obj if self.request.user.id == obj.user.id: return obj # Check if they are following each other if self.request.user.id in [ i["follow_to"] for i in … -
Sizing Thumbnail using variable height and width in Cloudinary through Django
I have jpegs of paintings. The paintings have certain dimensions: Painting 1: 52cm x 40cm Painting 2: 30cm x 50cm The jpeg of these images may with various widths in pixels in similar dimensions and I have uploaded them into Cloudinary using CloudinaryField in Django. Jpeg of painting 1: 104px x 80px Jpeg of painting 2: 90px x 150px I want to display the thumbnails of these images by translating cm -> px, meaning I was to show the thumbnail in 52px x 40px. How can I use template tags to display them in the new sizes by passing a height and width as a variable, like height = variable height (=52). -
How do I serialize specific field in Django ManyToMany field?
So, I'm trying to use Django Rest Framework for my project. I have two models Category and Content to be serialized, as below: views.py class Category(models.Model): category_name = models.CharField(max_length = 20) def __str__(self): return self.category class Content(models.Model): category = models.ManyToManyField(Category) body = models.TextField(blank=True, null=True) created_at = models.DateField(auto_now_add=True, null=True) def __str__(self): return self.created_at serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['category_name'] class ContentSerializer(serializers.ModelSerializer): class Meta: model = Content fields = [ 'category', 'body', 'created_at', ] Now the problem is, the JSON object returned has the id of each object in Category, NOT the category_name. So when I console.log in my front-end, I get (for example) [1, 4, 8] but what I need is (for example) ['Wine', 'Beer', 'Whiskey']. How do I make that possible? Thanks in advance :) -
Django keeps using the wrong project settings file
Django keeps trying to use the settings file of a previously deleted project (project-x) when I run python3 manage.py runserver for any newly created project resulting in the error ModuleNotFoundError: No module named 'project-x' when the settings module is initiating. The files/settings in my new project does not reference project-x at all so i'm not sure why this is happening... The error also occurs across different virtual environments. When I manually set the settings module environment variable using export DJANGO_SETTINGS_MODULE=newproject.settings everything works however I would like to find the root problem and fix it. Error File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python@3.9/3.9.1_6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'project-x' -
Sock file is not creating in my django project with gunicorn
I'm trying to deploy my django project properly with gunicorn. But i'm unable to do that. I'm doing the following process again and again... /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/dotescrow_main ExecStart=/home/ubuntu/dotescrow_main/dotescrow_env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/dotescro> [Install] WantedBy=multi-user.target then i run following commands in a sequence. sudo systemctl start gunicorn sudo systemctl enable gunicorn sudo systemctl status gunicorn it returns : ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2021-03-13 22:21:36 UTC; 15min ago Main PID: 563946 (gunicorn) Tasks: 4 (limit: 2372) Memory: 100.1M CGroup: /system.slice/gunicorn.service ├─563946 /home/ubuntu/dotescrow_main/dotescrow_env/bin/python /home/ubuntu/dotescrow_main/dotescrow_env/bin/gunicorn> after that when i check sock like in myproject by ls /home/ubuntu/dotescrow_main I dont get any sock file there. after that when i run sudo journalctl -u gunicorn i get following output: Jan 26 18:30:55 ip-172-31-11-244 systemd[1]: Started gunicorn daemon. Jan 26 18:30:55 ip-172-31-11-244 systemd[92397]: gunicorn.service: Failed to determine user credentials: No such process Jan 26 18:30:55 ip-172-31-11-244 systemd[92397]: gunicorn.service: Failed at step USER spawning /home/ubuntu/dotescrow/myprojecte> Jan 26 18:30:55 ip-172-31-11-244 systemd[1]: gunicorn.service: Main process exited, code=exited, status=217/USER Jan 26 18:30:55 ip-172-31-11-244 systemd[1]: gunicorn.service: Failed with result 'exit-code'. -
Django: Reverse for 'login' not found. 'login' is not a valid view function or pattern name
I'm working on my project for a course and I'm totally stuck right now. Login doesn't work. I using class-based views. When I`m logged in, everything works.The Logout View works too. The error is as follows: NoReverseMatch at / Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Exception Location: /home/aleo/#HOME/.virtualenvs/znajdki/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix Python Executable: /home/aleo/#HOME/.virtualenvs/znajdki/bin/python3 Python Version: 3.8.6 My files: poszukiwania/urls.py from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name = 'poszukiwania' urlpatterns=[ path('<slug:kategoria_slug>/', views.rzeczy_list, name='rzeczy_list_by_category'), path('<int:year>/<int:month>/<int:day>/<slug:rzecz_slug>/<int:id>', views.rzecz_detail, name='rzecz_detail'), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('', views.rzeczy_list, name='rzeczy_list'), ] znajdki/urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('poszukiwania.urls', namespace='poszukiwania')) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL) settings.py LOGIN_REDIRECT_URL = 'poszukiwania:rzeczy_list' LOGIN_URL = 'login' LOGOUT_URL = 'logout' templates/registration/login.html {% extends "poszukiwania/base.html" %} {% load static %} {% block title %}Logowanie{% endblock %} {% block content %} <h1>Logowanie</h1> {% if form.errors %} <p> … -
Unable to see verify value in DB from template
I'm a newbie at extracting values from the DB via views and templates but all of my attempts have failed so far. I've been looking at this for several hours now. I have the below model in my users app at models.py. This is an additional model to the "main one" with the regular name, email and password for my users. class WorkEmail(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) work_email = models.EmailField(unique=False, null=True, blank=True) work_email_verified = models.BooleanField(default=False) work_email_active = models.BooleanField(default=False) verified_company_name = models.CharField(max_length=100, null=True, blank=True) company_url = models.URLField(max_length=100, null=True, blank=True) request_datetime = models.DateTimeField(blank=True, null=True, auto_now_add=True, auto_now=False) def __str__(self): return self.work_email I have this UpdateView in views.py that works perfectly (with the exception of being able to see whether the work email has been verified or not, i.e. from the line with work_is_verified, till the end. class UpdateProfileView(UpdateView): form_class = CustomUserChangeForm success_url = reverse_lazy('home') template_name = 'update_profile.html' def get_object(self, queryset=None): return self.request.user def work_is_verified(self, request): if request.work_email_verified==True and request.work_email_active==True: return True else: return False And I have the below, in my update profile template at update_profile.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Home{% endblock title %} {% block content %} {% if user.is_authenticated %} <h2>Profile</h2> <form method="post"> … -
What is the most simple way to generate dynamic charts using django?
beginner here ! can you answer my question please ? (my project consists on grabing 3 numeric values from an api (number of cryptocurrencies transactions) and generate a bar/pie chart, each bar to a a cryptocurrency). So, what is the most simple way to generate dynamic charts using django ? -
DRF serializer data input format (json instead of request.data)
I created an api endpoint using DRF but the serializers have some really deep nested relationships and therefore cannot render out the serializer as form easily (for html). I therefore tried to create simple Django forms capture the user input and parse it into some complex nested jsons my own. However the serializers just cannot seem to accept normal json. Is it possible to make the serializer accept data in json format instead of "request.data"? If not what are the alternative ways of rendering forms in html? ( I thought of rendering out the serializer manually inside the template but I can't find any resources on how to do so) -
docker connect to server vps and local pc with github respository
Hi i have respository with django projects with 3 run settings files, I have in local PC and in server files with programs keys. Then all files without keys I have in github respository. In local PC I'm running app local with one local configure settings file. But when I'm on VPS server i can run this same app push and refresh changes in respository in my VS Code program. On VPS i have running hosts 80, 443 for 3 websites. with uwsgi and nginx. Usings env VM. Now I read about docker but i don't know how to build this. I want in my VSCode docker with my projects and connect them automatic when I'm using local PC, and when logging on SSH VPS server I want see this same projects in this same docker. Can i do that? What shood i look? and learn? maybe someone have tutorial for this. Thanks a lot. -
Httprequest has no attribute '_read_started'
I am trying to build a unittest for my weebhook_get_event(request). I use Django Httprequest to custom a request. When I test my function it said AttributeError: 'HttpRequest' object has no attribute '_read_started' on the line request.body def webhook_get_event(request): """ Exract the event form the request """ pdb.set_trace() event = None try: body = request.body.decode("utf-8") event = telnyx.Event.construct_from(body, telnyx.api_key) except: logger.exception(make_log_msg("get event failed", "", traceback.format_stack())) return evnet and my test is : class WebhookTest(TestCase): request = HttpRequest() def setUP(self): self.request.header = { 'telnyx-signature-ed25519' : "WkBFVhtpNBf+sOJ0+0sR1TntMqXsG2085AC1gvvRouPbHHlWZuDa7ZrHOFObucMOkcq3FY2/g9QzfD2EJ7FPAw==", 'telnyx-timestamp':"1615512013"} body = b'{"data":{"event_type":"message.received","id":"bc8ffc8d-89f6-4ee9-b28e-d15ea5a644da","occurred_at":"2021-03-12T01:20:13.341+00:00","payload":{"cc":[],"completed_at":null,"cost":null,"direction":"inbound","encoding":"GSM-7","errors":[],"from":{"carrier":"","line_type":"Wireless","phone_number":"+13125047267"},"id":"e3b8d304-c0d9-44a8-a6c0-73bb1d2665e9","media":[],"messaging_profile_id":"400177e5-e558-42c2-af2a-6b33574c2088","organization_id":"9da44375-48a0-46d2-9215-f788493def7c","parts":1,"received_at":"2021-03-12T01:20:13.335+00:00","record_type":"message","sent_at":null,"tags":[],"text":"hello","to":[{"carrier":"Telnyx","line_type":"Wireless","phone_number":"+155555555","status":"webhook_delivered"}],"type":"SMS","valid_until":null,"webhook_failover_url":null,"webhook_url":"https://encf7aq9g1rclj9.m.pipedream.net"},"record_type":"event"},"meta":{"attempt":1,"delivered_to":"https://encf7aq9g1rclj9.m.pipedream.net"}}' self.request._body = body def test_webhook_get_event(self): event = webhook.webhook_get_event(self.request) assertNotNone(event) -
calculate remaining days in python/django
I'm creating a django ecommerce site; This site "sells" digital items. On one of the templates, related to a "user profile", I'm trying to calculate the remaining days in an web app but so far have not been successfull at doing it and displaying on my template. I've tried to create a remaining_days function but unable so far to use it Hereunder the code: models.py class UserSubscription(models.Model): user = models.ForeignKey(User, related_name= 'tosubscriptions', on_delete=models.CASCADE, null=True, blank=True) subscription = models.ForeignKey("Subscription", related_name = 'tosubscriptions',on_delete=models.CASCADE, null=True, blank=True) # startdate of a subscription, auto_now_add needs to be "False" for acummulation of days in subscriptions start_date = models.DateTimeField(auto_now_add=False, null=True, blank=True,verbose_name="Start Date") expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True,verbose_name="Expiry Date") # expiry date of a subscription # "is_canceled" is used to calculate if a usersubscription is active is_canceled = models.BooleanField(default=False, verbose_name="Is Canceled") cancel_date = models.DateTimeField(auto_now=False, auto_now_add=False, blank=True, null=True) class Meta: verbose_name = "User Subscription" verbose_name_plural = "User Subscriptions" def __str__(self): """Unicode representation of UserSubscription""" return "PK: [{}] Subscription of: {}, {}, Expiring the: {}, is canceled: {}".format( str(self.pk), str(self.user), str(self.subscription), str(self.expiry_date), str(self.is_canceled ) ) def save(self, *args, **kwargs): # calculated when object is saved and saved in the db """ Function to calculate the expiry date of a … -
Annotating values from filtered related objects -- Case, Subquery, or another method?
I have some models in Django: # models.py, simplified here class Category(models.Model): """The category an inventory item belongs to. Examples: car, truck, airplane""" name = models.CharField(max_length=255) class UserInterestCategory(models.Model): """ How interested is a user in a given category. `interest` can be set by any method, maybe a neural network or something like that """ user = models.ForeignKey(User, on_delete=models.CASCADE) # user is the stock Django user category = models.ForeignKey(Category, on_delete=models.CASCADE) interest = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0)]) class Item(models.Model): """This is a product that we have in stock, which we are trying to get a User to buy""" model_number = models.CharField(max_length=40, default="New inventory item") product_category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Category") I have a list view showing items, and I'm trying to sort by user_interest_category for the currently logged in user. I have tried a couple different querysets and I'm not thrilled with them: primary_queryset = Item.objects.all() # this one works, and it's fast, but only finds items the users ALREADY has an interest in -- primary_queryset = primary_queryset.filter(product_category__userinterestcategory__user=self.request.user).annotate( recommended = F('product_category__userinterestcategory__interest') ) # this one works great but the baby jesus weeps at its slowness # probably because we are iterating through every user, item, and userinterestcategory in the db primary_queryset = primary_queryset.annotate( … -
OpenCV Live Stream from Camera in Django webpage with image details
I am making a project in Django. And have made live feed from camera on a webpage. I am also processing the video to detect faces, and gestures. But I am not able to send the array (i.e which contains the features of videos like face detected or not, hand gesture, etc) to the template. Views.py: from django.shortcuts import render from django.http.response import StreamingHttpResponse from streamapp.camera import VideoCamera from django.http import HttpResponse def gen(camera): while True: frame = camera.get_frame() feature = camera.render_features() print(feature) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type='multipart/x-mixed-replace; boundary=frame') def index(request): return render(request, 'streamapp/home.html') Urls.py: from django.urls import path, include from streamapp import views urlpatterns = [ path('', views.index, name='index'), path('video_feed/', views.video_feed, name='video_feed'), ] In View.py line number 10, feature is the array that I want to access inside the webpage(home.html). How to pass that array to the template? -
@permission_required doesn't check user group permissions
I am trying to check if a user has a permission to access a particular django view using @permission_required. The permission is assigned to the group x to which the user is assigned to. I confirmed with the database and through debugging that the user is member of the group and the group has the appropriate permission set. Nevertheless, @permission_required doesn't allow access to this user. The view has the following decorators: @login_required(login_url='ROUTE') @permission_required('PERMISSION', raise_exception=True) Is this an issue from django, or is there some workaround that needs to be done to consider group permissions? -
Creating automated docs for Django REST Framework
guys. I am to write documentation for Django (specially docs for APIs) project and want to use Sphinx. Unfortunately, Sphinx` docs and guides are out of date (Sphinx newest version is 3.5+). When I mean out of date guides and docs, I refer to this guides and others: https://www.freecodecamp.org/news/sphinx-for-django-documentation-2454e924b3bc/ (2018) https://www.sphinx-doc.org/en/master/usage/quickstart.html (official docs, it doesn't help) https://docs.djangoproject.com/en/dev/internals/contributing/writing-documentation/ https://columbia-it-django-jsonapi-training.readthedocs.io/en/latest/sphinx/ (Sphinx 1.8) The problem is that there are docs directory, that doesn't appear in new versions (in newest versions we`ve got sourse directory). I installed Sphinx to test project and run command sphinx-quickstart in app directory. My structure in test project after sphinx-quickstart: Test -- app ---- base ---- **build** ---- post ---- quickstart ---- templates ---- **sourse** ------ **_static** ------ **_templates** ------ **conf.py** ------ **index.rst** ---- **make.bat** ---- **Makefile** ---- manage.py ---- requirements.txt -- venv -- .gitignore -- Dockerfile -- docker-compose.yaml -- README.md Files between **** is what I`ve got after running sphinx-quickstart. If you know how to work with new version of Sphinx or now other services for automate generating docs for DRF and API, please, explain or provide link to actual docs of Sphinx -
how to extract specific values from json / dictionary in Python (Django)
This is my views.py : import requests import os import numpy as np import pandas as pd from pandas import Series, DataFrame from pprint import pprint from django.views.generic import TemplateView import json from django.http import JsonResponse, HttpResponse from django.shortcuts import render def btc(request): query_url = [ 'https://api.blockchair.com/bitcoin/stats', 'https://api.blockchair.com/ethereum/stats', 'https://api.blockchair.com/litecoin/stats' ] headers = { } result = list(requests.get(u, headers=headers) for u in query_url) json_data1 = result[0].json() json_data2 = result[1].json() json_data3 = result[2].json() y = json_data1['data']['transactions'] context = { "bitcoin": y, "ethereum": json_data2, "litecoin": json_data3, } return render(request, "index.html", context) the problem is in the variable : 'y' in the index.html file : ethereum.data.transaction for example works perfectly so i want to do the same thing but directly into the views.py file (in python) because i need the variable to be a simple value not a json/dict value -
How to render formset manually?
I can't figure out how to render formset manually. I created formset like this: ImageFormset = modelformset_factory(PostImages, fields=('image',), extra=0, can_delete=True). And when I render formset I get this: I want to get rid of all this text and write my own, how do I do this? -
Django, Dash App Safest Place to Keep Database Credentials
I'm new to web development. I have a Django project that loads a Dash app on one of it's pages. The dash app generates a chart that lets the user select certain datasets from the database. Directly inside my App.py (dash app) I placed my sqlalchemy database connection variables which one of the callbacks uses to fetch the data when requested. sqlEngine = sa.create_engine('mysql+pymysql://host:password@127.0.0.1:3306/db', pool_recycle=3600) dbConnection = sqlEngine.connect() conn = pymysql.connect(host='127.0.0.1',user='host',password='password',db='db') cursor = conn.cursor() app = DjangoDash(name='app', add_bootstrap_links=True, serve_locally = False) ... @app.callback(...) def fetch_data(...): select = """SELECT * FROM `db`.`table`;""" df = pd.read_sql(select, dbConnection) I'm not sure if this is a safe practice in a production environment. What would be the best/safest way to connect to the database inside of the dash app. My Django app is also connected to the database for migrations. Thanks for any help/advice.