Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error while installing virtual environment
I'm following official django tutorial on their webpage. When I run command "py -m pip install virtualenvwrapper-win", I get the the following errors. Please see the screenshot. I have Anaconda installed. The same error occurs on my other computer where I have only Python installed. What am I missing? Thanks -
i am using crispy for django and my success message works properly but my validation error messages show normal black text when it should be in red
so when i fill the login info correctly i get a message 'successfully added (username)' but when i fill in the wrong info i just shows plain black text but i want it to show error message in red color the tutorial .I followed a tutorial (by correy schafers) exactly the same but somehow i cant get the error message to show up in red color but my my success message shows up in green. register.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign In</a> </small> </div> </div> {% endblock content %} base.html {% load static %} <!DOCTYPE html> <html> <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="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div … -
TWILIO API ERROR Credentials are required to create a TwilioClient django
I am trying to include TWILIO API to my project. It should send sms. I have finished tutorial, but then i get error Credentials are required to create a TwilioClient. I have credentials in .env file and then i try to import them to settings and then get this credentials from settings to views. This is when i get error. .env TWILIO_ACCOUNT_SID= 'xxxxxxxxxxxxxxxxxxxxxx' TWILIO_AUTH_TOKEN= 'xxxxxxxxxxxxxxxxxxxxxxx' TWILIO_NUMBER= 'xxxxxxxxxxxxxxxxxx' settings.py import os TWILIO_ACCOUNT_SID = os.getenv('TWILIO_ACCOUNT_SID') TWILIO_AUTH_TOKEN = os.getenv('TWILIO_AUTH_TOKEN') TWILIO_NUMBER = os.getenv('TWILIO_NUMBER') SMS_BROADCAST_TO_NUMBERS = [ '+111111111', ] views from django.conf import settings from django.http import HttpResponse from twilio.rest import Client def broadcast_sms(request): message_to_broadcast = ("Have you played the incredible TwilioQuest " "yet? Grab it here: https://www.twilio.com/quest") client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) for recipient in settings.SMS_BROADCAST_TO_NUMBERS: if recipient: client.messages.create(to=recipient, from_=settings.TWILIO_NUMBER, body=message_to_broadcast) return HttpResponse("messages sent!", 200) and here is when code work, but i want to import this from settings.. # def sms(request): # TWILIO_ACCOUNT_SID = "xxxxxxxxxxxxxxxxxxxxxxx" # TWILIO_AUTH_TOKEN = "xxxxxxxxxxxxxxxxx" # TWILIO_NUMBER = "xxxxxxxxxxxxx" # message_to_broadcast = ("Have you played the incredible TwilioQuest " # "yet? Grab it here: https://www.twilio.com/quest") # # client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) # for recipient in settings.SMS_BROADCAST_TO_NUMBERS: # if recipient: # client.messages.create(to=+xxxxxxxxx, # from_=+xxxxxxxxxx, # body=message_to_broadcast) # return HttpResponse("messages sent!", 200) … -
Python Django - HTML for REST API JSON data in Async
I am making a Django web app. So far I have used templates for creating HTML in response to a POST request. I use 'context' to pass data to the template and fill the HTML with that data. This does not require any client-side work. Now I added a REST API to the app to be used Async, and I want all data to be processed by the API and return only in JSON format. This creates a problem, I cant use the templates anymore since I can't use 'context' to fill in the data in the HTML, I have to use client-side JS to do the filling but now I am missing the HTML appropriate to the data received. What are the ways in Django for generating HTML for an API JSON response in Async architecture? Are there any solutions, frameworks, JS libraries? I do not want to return HTML via API to keep things client mobile app/browser independent. -
Why I can't pass categories to my template in Django
I have a header.html file in my partials under template directory. I have a section for categories which I need to fetch from database. Therefore, I've created a custom templatetag in my app folder. I have written the tag for the latest dropdown article and categories. Well, somehow the articles are being fetched from the database but categories are not. models.py from django.db import models from django.utils.text import slugify from django.urls import reverse from ckeditor_uploader.fields import RichTextUploadingField from datetime import datetime class Category(models.Model): label = models.CharField(max_length=15, unique=True) def __str__(self): return self.label class Article(models.Model): title = models.CharField(max_length=80, unique=True, help_text='Max Length: 80') category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) banner_image = models.ImageField(upload_to='photos/%Y/%m/%d/', help_text='Banner Image', default=None) description = models.TextField(max_length=200 ,help_text='Short descirption about the post') content = RichTextUploadingField(help_text='Site Content') published = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) views = models.BigIntegerField(default=0) featured = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('article', kwargs={'category': self.category, 'post': self.title}) my custom tempalte tag from django import template from articles.models import Article, Category register = template.Library() @register.inclusion_tag('partials/_header.html') def recent(): category = Category.objects.all() #not being fetched recents = Article.objects.filter(published=True).order_by('-date_created')[:9] trendings = Article.objects.filter(published=True).order_by('-views')[:9] return { 'recents': recents, 'trendings': trendings, 'category': category, } ** my header.html file ** <div id="asmCategoryContents" class="asm-Category_Contents"> {% for cat … -
Compare the new and old field values in django, then update the old value
In the data is being pulled from the URL. Which is being stored in the database. Now I would want to only update the data that is being changed. hostandservicelisturl = 'http://192.168.232.133/query=servicelist' userpwd = ('xxx', 'xxx') data7 = requests.get(hostandservicelisturl,auth = userpwd).json() data8 = data7['data']['servicelist'] mylistik1 = [] for ik1 in data8: print(ik1) mylistik1.append(ik1) for x in mylistik1: for y in data8[x]: print(y) z = data8[x][y] Data.objects.update_or_create(hostname=ik1,service=y,servicestatus=z) class Data(models.Model): hostname = models.CharField(max_length=200, null=True, editable=False) service = models.CharField(max_length=200, null=True, editable=False) servicestatus = models.IntegerField(null=True, editable=False) Value In URL: "linksys-srw224p": { "PING": 2, "Port 1 Bandwidth Usage": 8, "Port 1 Link Status": 16, "Uptime": 16 Note : the number like 2 8 16 changes accordingly from the api pull. As of now i have seen field tracker() with pre save but I am not able to figure out how too as the documentation is not clear. -
i want to download number of media like 10 or 20 downloads per request but dont know how?
posts = [] links = driver.find_elements_by_tag_name('a') for link in links: post = link.get_attribute('href') if '/p/' in post: posts.append(post) print(posts) download_url = '' for post in posts: driver.get(post) shortcode = driver.current_url.split("/")[-2] type = driver.find_element_by_xpath('//meta[@property="og:type"]').get_attribute("content") if type == 'video': download_url = driver.find_element_by_xpath('//meta[@property="og:video"]').get_attribute("content") urllib.urlretrieve(download_url, '{}.mp4'.format(shortcode)) else: download_url = driver.find_element_by_xpath( '//meta[@property="og:image"]').get_attribute("content") urllib.urlretrieve(download_url, '{}.jpg'.format(shortcode)) print(download_url) -
django-admin startproject doesn't do anything
I use command "django-admin startproject myapp" and it doesn't do anything When I use this command again it says "CommandError: 'C:\Users\User\Desktop\djangotest2\myapp' already exists" I tried disabling my antivirus and I tried using absolute path to django-admin.py and django-admin.exe file -
Python HTTP server for shell commands
I look for Python package to expose shell command from a linux server. At this moment I use Django and ThreadPoolExecutor to asynchronously launch submit execution. Clients receives job id and 202 Accepted as HttpResponse. It feels like i re-invent a wheel. Is there python3 framework which can help me to expose and orchestrate running commands on a server through HTTP? launch a shell command by triggering http endpoint (returns 202 and launch-id) commands must run asynchronously and will have own side-effects (e.g. write something to db) obtain status of running command by launch-id log stderr and stdout of subprocess so later i can find the output in logs -
Stripe Variable amount checkout & Django
I am trying to implement variable amount checkout using Stripe, so that users can donate a chosen amount. The donation should then link to a customer id created using dj stripe (set up for recurring donations). So far, I have got the follwoing, however currently clicking the donate button does not load the stripe checkout page Views.py: customer, created = djstripe.models.Customer.get_or_create(subscriber=user) @require_http_methods(['POST']) def create_singlesession(): #read request data data = json.loads(request.data) # create checkout session with API api_key=stripe_key, session = stripe.checkout.Session.create( customer=customer.id, success_url='charity_app/success?id={CHECKOUT_SESSION_ID}', cancel_url='charity_app/cancel?id={CHECKOUT_SESSION_ID}', payment_method_types = ['card'], submit_type = 'donate', line_items = [{ 'amount': data['amount'], 'currency': 'gbp', 'quantity': 1, 'name': 'Single Donation', 'images': [], }], payment_intent_data = { 'metadata': { 'Charity': data['Organisation'], }, }, metadata={ 'Charity': data.get('Organisation') } ) return JsonResponse(session) Session.sync_from_stripe_data(create_singlesession) urls: url(r'^create-singlesession/$',views.create_singlesession,name='create_singlesession'), Template: <button id="donate-button">Donate</button> <script src="https://js.stripe.com/v3/"></script> <script charset="utf-8"> var stripe = Stripe('pk_test_jcFUmV2P0IREALGYggK6w2tT007W8QUaqd'); var amount = document.getElementById('amount-input'); var charity = document.getElementById('charity'); var button = document.getElementById('donate-button'); button.addEventListener('click', function(e) { /*alert( "Handler for .click() called." );*/ e.preventDefault(); createSessionAndRedirect(); }); function createSessionAndRedirect() { // 1. Pass the amount and organisation to server to create session fetch('/charity_app/create-singlesession/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ amount: amount.value, cause: charity.value, }), }) .then((response) => response.json()) .then((session) => { // 2. Redirect to … -
How to correct repeating code in view-functions?
I looked at one Django course on a site that starts with the letter U and at the end I have such a code. There is a lot of duplication and I show just one of them. On each page, I publish the same type of information, it hurts to look at it. So while I thought about two solutions to fix this: Create Global Variables Define a function that will return all these duplicate variables main.view def home(request): ''' index.page ''' site, _ = Main.objects.get_or_create(pk=1) # (1) news = News.objects.all().order_by('-pk') # (2) subs = SubCat.objects.all() # (3) lastNews = News.objects.all().order_by('-pk')[:3] popNews = News.objects.all().order_by('-show') bottomPopNews = News.objects.all().order_by('-show')[:3] # (5) trends = Trending.objects.all().order_by('-pk') # (6) # group Subcategories in each Category tags = SubCat.objects.values('catid', 'catid__name').order_by('catid').annotate(count=Count('catid')) # (4) Tracker.objects.create_from_request(request, site) return render(request, 'front/home.html', {'site' : site, 'news' : news, 'tags' : tags, 'subs' : subs, 'lastNews':lastNews, 'popNews' : popNews, 'bottomPopNews':bottomPopNews, 'trends':trends}) def about(request): ''' About page ''' site, _ = Main.objects.get_or_create(pk=1) # (1) popNews = News.objects.all().order_by('-show')[:3] news = News.objects.all().order_by('-pk') # (2) subs = SubCat.objects.all() # (3) bottomPopNews = News.objects.all().order_by('-show')[:3] # (5) tags = SubCat.objects.values('catid', 'catid__name').order_by('catid').annotate(count=Count('catid')) # (4) trends = Trending.objects.all().order_by('-pk') return render(request, 'front/about.html', {'site' : site, 'popNews':popNews,'bottomPopNews':bottomPopNews,'tags':tags,'subs' : subs,'news' : news,'trends':trends,}) def … -
Update nested field if a path to it isn't constant
I'm working on Django which uses MongoDB. One of collections has the following structure: { "inspectionType" : { "id" : "59a79e44d12b52042104c1e8", "name" : "Example Name", "inspMngrsRole" : [ { "id" : "55937af6f3de6c004bc42862", "type" : "inspectorManager", "is_secret_shoper" : false } ], "scopes" : { "56fcf6736389b9007a114b10" : { "_cls" : "SomeClass", "id" : "56fcf6736389b9007a114b10", "name" : "Example Name", "category" : "Example Category" }, } } } I need to update field "_cls" ("inspectionType.scopes.._cls") for all documents in the collection. The problem is the scope_id is dynamic and unique for each scope. Is it possible to use db.collection.update for that? And how should the path to the field look like? -
Проблема с созданием миграций для Django 2.11 [closed]
Стартанул новый проект на Django 2.11. Из кастомных моделей ничего еще не успел сделать. Создал только первое приложение, прописал базовые настройки (http://joxi.ru/ZrJ9zN4CMN7pMA). Пробую накатить базовые миграции Django командой python manage.py migrate. Получаю ошибку: File "E:\DjangoEnv\api_for_django22_env\lib\site-packages\django\apps\registry.py", line 155, in get_app_config return self.app_configs[app_label] KeyError: 'accounts' "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.Accounts' that has not been installed -
How to implement Django Form Live Validation?
Are there any packages to perform client-side validation over django forms? I'm Not really experienced with AJAX and Javascript. -
Custom User Authentication using DRF
Want to create a Web RESTful API with Django. For that I'm using Django REST Framework. What are the necessary steps to get the authentication using a custom User model (subclassing AbstractBaseUser) exposing the endpoints to be used? -
How to pass input value to function in view.py
Objective: ** To pass input value itemnumbervalue to itemnumber() in views.py > Error occured: method object is not subscribable line 17 in view.py views.py: from .forms import InputForm def home_view(request): context1 ={} context1['form'] = InputForm(request.POST) return render(request, "input.html", context1) def itemnumber(request): *if (request.POST('submitted')): c = request.POST['ENTER_ITEM_NUMBER'] print("input valuegiven by user",c)* cursor = connection.cursor() try: itemnumbervalue = c C=cursor.execute(f"EXEC ValidateBusinessrule '0000000000{itemnumbervalue}'") result_set = cursor.fetchall() result_set1= [' {} '.format(x) for x in result_set] context = {"row": result_set1} return render(request, "home.html", context) finally: cursor.close() forms.py class InputForm(forms.Form): regex = re.compile('^([1-9]{8})$', re.UNICODE) ENTER_ITEM_NUMBER= forms.RegexField(max_length=8, regex=regex,help_text=("Required 8 digits between {0-9}.")) home.html <body> <table> <tr> <ul> <th>(column 1,column 2)</th> </ul> <tr> <ul > {% for row in row %} <td style= "text-align: center;"> {{ row }} </td> </ul> </tr> {% endfor %} </tr> </table> </body> input.html <body> <form action = "{% url 'item'%}" method = "POST"> {% csrf_token %} {{form}} <input type="submit" value=Submit" name="submitted"> </form> </body> problem details: To get input from user and give this input to itemnumbervalue in itemnumber() in view.py. I already validated by putting itemnumbervalue='12345678' (without input value from user) is working fine and getting resultant table. -
Django cannot assign variable to objects
when i'm trying to add data to uer in many to many as showen in views code below views.py def playList(request, name, language): playlist = { 'classic': Classic, } playlist2 = { 'classic': 'classic', } num = { 'ar': 1, 'en': 2, } if request.method == 'POST': form2 = FavoriteForm(request.POST) if form2.is_valid(): x = Profile.objects.get(user=request.user) x.playlist2[name].add(playlist[name].objects.get(id=request.POST.get(playlist2[name]))) form = playlist[name].objects.filter(lang=num[language]) context = {} for i in form: context[i] = i context = { 'form': form, 'playlist': playlist2[name], } return render(request, 'playlist.html', context) get this error that str object has no attr objects 'str' object has no attribute 'objects' when i'm change str to istance as showen in views code below views.py def playList(request, name, language): playlist = { 'classic': Classic, } playlist2 = { 'classic': Profile.classic, } num = { 'ar': 1, 'en': 2, } if request.method == 'POST': form2 = FavoriteForm(request.POST) if form2.is_valid(): x = Profile.objects.get(user=request.user) x.playlist2[name].add(playlist[name].objects.get(id=request.POST.get(playlist2[name]))) form = playlist[name].objects.filter(lang=num[language]) context = {} for i in form: context[i] = i context = { 'form': form, 'playlist': playlist2[name], } return render(request, 'playlist.html', context) i get this error that profile has no attr playlist2 'Profile' object has no attribute 'playlist2' and this is my model code modles.py class Classic(models.Model): name = models.CharField(max_length=50, … -
is there memory issue?
https://www.google.com/search?q=MemoryError+at+%2Fquery%2F+No+exception+message+supplied+Request+Method%3A+POST+Request+URL%3A+http%3A%2F%2F127.0.0.1%3A8000%2Fquery%2F+Django+Version%3A+2.2.5+Exception+Type%3A+MemoryError+Exception+Location%3A+ops.pyx+in+thinc.neural.ops.NumpyOps.allocate%2C+line+491+Python+Executable%3A+C%3A%5CUsers%5CTOSHIBA%5CAnaconda3%5Cpython.exe+Python+Version%3A+3.7.3+Python+Path%3A+%5B%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CDocuments%5C%5Cclinical%5C%5Cdemoproject%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Cpython37.zip%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5CDLLs%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%5C%5Cwin32%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%5C%5Cwin32%5C%5Clib%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%5C%5CPythonwin%27%5D+Server+time%3A+Mon%2C+23+Mar+2020+17%3A41%3A09+%2B0000&oq=me&aqs=chrome.1.69i59l2j0j69i57j69i61l3j69i60.2878j0j7&sourceid=chrome&ie=UTF-8 i received many times this error please help me -
How to pass input value to function in view.py
Objective: ** To pass input value itemnumbervalue to itemnumber() in views.py > Error occured: The view item.views.itemnumer didn't return a return a HTTP return response. It return none instead views.py: from .forms import InputForm def home_view(request): context1 ={} context1['form'] = InputForm(request.POST) return render(request, "input.html", context1) def itemnumber(request): *if (request.GET.get('submitted')): c = request.get['ENTER_ITEM_NUMBER'] print("input valuegiven by user",c)* cursor = connection.cursor() try: itemnumbervalue = c C=cursor.execute(f"EXEC ValidateBusinessrule '0000000000{itemnumbervalue}'") result_set = cursor.fetchall() result_set1= [' {} '.format(x) for x in result_set] context = {"row": result_set1} return render(request, "home.html", context) finally: cursor.close() forms.py class InputForm(forms.Form): regex = re.compile('^([1-9]{8})$', re.UNICODE) ENTER_ITEM_NUMBER= forms.RegexField(max_length=8, regex=regex,help_text=("Required 8 digits between {0-9}.")) home.html <body> <table> <tr> <ul> <th>(column 1,column 2)</th> </ul> <tr> <ul > {% for row in row %} <td style= "text-align: center;"> {{ row }} </td> </ul> </tr> {% endfor %} </tr> </table> </body> input.html <body> <form action = "{% url 'item'%}" method = "post"> {% csrf_token %} {{form}} <input type="submit" value=Submit" name="submitted"> </form> </body> problem details: To get input from user and give this input to itemnumbervalue in itemnumber() in view.py. I already validated by putting itemnumbervalue='12345678' (without input value from user) is working fine and getting resultant table. -
Error with inlined profile form save in django admin
I really confised, because problem sounds trivial, but I didn't googled anything related to this. I found one very simular question Django Admin Create Form Inline OneToOne but in my case I cannot remove signal, it'll break normal way of user creation in my app. I have model User and Profile connected OneToOne relationship (models.py): from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from .managers import UserManager class User(AbstractUser): """auth/login-related fields""" username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Profile(models.Model): """profile fields""" user = models.OneToOneField(User, on_delete=models.CASCADE) about = models.CharField(max_length=2000, blank=True) telegram = models.CharField(max_length=25, blank=True) def save(self, *args, **kwargs): print('save profile', args, kwargs) # from admin it run 2 times, second with empty args, kwargs so PROBLEM HERE!!! super().save(*args, **kwargs) print('save profile complete') """receivers to add a Profile for newly created users""" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): print('create_user_profile', created, instance.id) if created: try: p = Profile.objects.create(user = instance) print('succsecc!!!!', p, p.id) ## here profile object created and got id except Exception as e: print('create profile error', e) # never prints else: instance.profile.save() """ @receiver(post_save, sender=User) def save_user_profile(sender, instance, … -
Django application error ,error H10 ,503 while pushing app on HEROKU
From a lot of time i m trying to deploy my Django website on heroku, but i am getting this error h10 and which is i think for service unavailable. Here are some ss of logs and procfile. procfile content: web: gunicorn pop.pop.wsgi logs: logs of app -
Send data to frontend with Django channels
I created a Django channels consumer that, once the connection is open, should establish a connection to an external service, retrieve some data from this service and send the data to my frontend. Here is what i tried: import json from channels.generic.websocket import WebsocketConsumer, AsyncConsumer, AsyncJsonWebsocketConsumer from binance.client import Client from binance.websockets import BinanceSocketManager import time import asyncio client = Client('', '') trades = client.get_recent_trades(symbol='BNBBTC') class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', self.process_message) bm.start() def process_message(self, message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate) When the connection is opened, this code will start printing some market orders to my console as soon as there is one. Now, instead of printing them to my console, i would like to send them to my frontend. Can someone explain me how to do that? Here is my frontend: {% load staticfiles %} <html> <head> <title>Channels</title> </head> <body> <h1>Testing Django channels</h1> <script> // websocket scripts var loc = window.location var wsStart = 'ws://' + window.location.host + window.location.pathname var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) if (loc.protocol == 'https:'){ … -
Is there a way to transfer images between Django Rest Framework and Flutter app?
I want to take a picture on an app in flutter using the phone's camera or gallery and send it (POST request) to a Django REST API along with some other information. When the Django REST API receives the image along with the other information, it should resize the image and then save it in a model like: class Animals(models.Model): animal_image = models.ImageField(blank = True, upload_to=getFileName) animal_name = models.CharField(max_length = 30) species = models.CharField(max_length = 30) And later, the flutter app should be able to do a GET request to the API in order to get the image along with other details in the model and display the image on a widget (in another screen of the app). Therefore, I want to know how to do the Django REST API (views code to handle the GET and POST request) and Flutter implementation (code for making the GET and POST requests with images to the Django server). Either code snippets, links to blog posts or documentation would be good. If this way is not possible, what are the alternate ways through which images can be exchanged between Django and Flutter? Please Help Cheers!!! -
Django using bulk_update to update all records
With 2.2 we now have the option to bulk update: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#bulk-update I have a model with say millions of rows and I want to efficiently update all the records. I am trying to use bulk_update, but which means I still have to load all the model objects in the memory, modify the field one by one and then use bulk update: What I am doing: def migrate_event_ip_to_property(apps, schema_editor): Event = apps.get_model('app' 'Event') events = Event.objects.all() for event in events: if event.ip: event.properties["$ip"] = event.ip Event.objects.bulk_update(events, ['properties'], 10000) Since there are millions of records, can I avoid doing Event.objects.all() and load all objects into the memory even while using bulk_update? -
djang-bootstrap avoid label tag being added when calling `field|bootstrap`
How to avoid label tag being added when calling field|bootstrap. I have the below code filter.py import django_filters from .models import Issue class IssuesFilter(django_filters.FilterSet): summary = django_filters.CharFilter(label="Summary", lookup_expr="icontains") class Meta: model = Issue Views.py def index(request): issues = IssuesFilter(request.GET, queryset=Issue.objects.all()) context = { 'user': request.user, 'message': 'LogedIn', 'filter': issues } return render(request, 'testApp/index.html', context) index.html {% extends "firstPage/base.html" %} {% load bootstrap %} {% load render_table from django_tables2 %} {% load crispy_forms_tags %} {% block body %} <form method="GET"> <table> {% for field in filter.form %} <tr class="table table-borderless"> <td>{{ field.label_tag }}</td> <td>{{ field|bootstrap }}</td> </tr> {% endfor %} </table> <button type="submit" class="btn btn-primary">Search</button> </form> {% endblock %} When I add field|bootstrap I could see the label tag of the field is displayed. Is it possible to remove additional label tag from being added?