Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Executing a function when a task is due
I am writing a React Native app. On the backend I have Django and PostgreSQL. I want to be able to create a task with a specific due date and time and pop a notification at that datetime. I was wondering what would be the best implementation or how others have solved this. So far my ideas: Pull in the tasks from the backend, store them locally then apply a setInterval function - then once the time is up pop that notification. Run a schedular on the backend that checks if any tasks are due, push something through webhooks and if so then pop a notification. Any ideas wellcome, thank you! Ellen -
I have a question about django rest auth customization
I'm trying to solve some of the things that don't fit me in the current django rest auth. First of all, I would like to make it possible to sign up as a member only once I enter the password without using password2 in the rest auth. And when I sign up as a member, the following error occurs when I insert the duplicate email. UNIQUE constraint failed: api_user.email How can I solve these problems? Here is my code. models.py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, profile, userName, password): user = self.model( email=self.normalize_email(email), userName=userName, profile=profile, ) user.set_password(password) user.save() return user def create_superuser(self, email, password, userName, profile): user = self.create_user( email=self.normalize_email(email), password=password, userName=userName, profile=profile, ) user.is_staff = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(_('email address'), unique=True) userName = models.CharField(max_length=10) profile = models.ImageField(default='default_image.jpeg') is_staff = models.BooleanField(_('staff status'), default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['userName', 'profile'] serializers.py from .models import User from rest_framework import serializers from rest_auth.registration.serializers import RegisterSerializer from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenRefreshSerializer from rest_framework_simplejwt.tokens import RefreshToken from allauth.account import app_settings as … -
How to learn Django with Python?
what would be the best site, video, or any which way to learn Django? I have gone to youtube but I can't find the perfect video to best explain it to me... -
What exception to raise for duplicate instance Django
I have a util method called add_user, which takes in an email and password and creates a user. First, it checks if that user already exists though: if User.objects.filter(email=email).exists(): # raise some exception What kind of exception should I raise here? Thanks!! -
How to create an AWS role for a Django Application
I have a Django app and I want to create an AWS IAM role for it. I want to do this so that I can get access to AWS Secrets Manager, among other AWS services. How do I set this up? Thanks! -
Stream specifier '' in filtergraph description [0][1]concat=a=1:n=1:v=1[s0] matches no streams
i am trying to concatenate two audio files in django with ffmpeg but getting this error Stream specifier '' in filtergraph description [0][1]concat=a=1:n=1:v=1[s0] matches no streams.` here is my function def audiomarge(request): recorded_audio = request.FILES['audio'] new = tempSong(tempSongFile=recorded_audio) new.tempSongFile.name = 'test.wav' new.save() record_file_path = new.tempSongFile.path record_file_path = str(record_file_path) recorded_audio = request.POST.get('audio') songslug = request.POST.get('songslug') current_song = Song.objects.filter(slug=songslug)[0] current_song_path = current_song.songFile.url current_song_path = '.'+(str(current_song_path)) input_first = ffmpeg.input(current_song_path) input_second = ffmpeg.input(record_file_path) ffmpeg.concat(input_first, input_second, v=1, a=1).output('./finished_video.wav').run() return HttpResponse('okay') i have also tried .compile() instead of .run() in this case nothing is happening -
How to keep typing in the terminal after 'python manage.py runserver' in Django?
I was following along this tutorial on Django until minute 28:36 when the teacher uses a quick shortcut that appeared as ^C(trydjango) $ on the terminal, allowing him to continue typing to makemigrations after he did runserver. When I try to type in the terminal after python manage.py runserver, the enter button does not submit the commands, but rather enters down to a newline making me stuck. I am unsure what I am doing wrong, so any help would be greatly appreciated. -
Django-Channels: another chatconsumer that is the same websocket
So I am making a project that use websockets, it works very well. I decided to include the websocket connection to another page, so I decided to add the other page in my routing.py, also I made another ChatConsumer for the other page, the problem is that I release that they are two different connections, how can I make my other chatconsumer the same as the other chatconsumer for this connection to be the same websocket connection? here is my consumer.py: import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] # print(other_user, me) thread_obj = await self.get_thread(me, other_user) self.thread_obj = thread_obj chat_room = f"thread_{thread_obj.id}" self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ "type": "websocket.accept" }) # await asyncio.sleep(10) async def websocket_receive(self, event): # when a message is received from the websocket print("receive", event) front_text = event.get('text', None) if front_text is not None: loaded_dict_data = json.loads(front_text) msg = loaded_dict_data.get('message') user = self.scope['user'] username = 'default' if user.is_authenticated: username = user.username myResponse = { 'message': msg, 'username': username, } await self.create_chat_message(user, msg) # broadcast … -
Specifying number of objects to serialize DRF
I have this problem with serializing nasted objects in DRF. Let's say i have these classes: class RecordSerializer(serializers.ModelSerializer): class Meta: model = Record fields = [..some fields] class ListSerializer(serializers.ModelSerializer): record = RecordSerializer(many=True, read_only) class Meta: model = List fields = [..some fields, 'record'] This gives me serialized data of List with every record that is related to it. How do i specify a number of records that i want to serialize with nasted objects? -
Reasons that might rise when submitting a Strip Payment
I was making a payment trial for my e-commerce project and it was working perfectly fine before and now all of a sudden when i am using the Credit Card Trial Numbers the payment is getting through and the order is made but I receive a message that an "A serious Error Occured. We have been notified." the very last message in the Payment Views. I am trying to figure out what error might lead to this. Here is the views.py: class PaymentView(View): def get(self, *args, **kwargs): # order order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False } return render(self.request, "payment.html", context) else: messages.warning( self.request, "You have not added a billing address") return redirect("core:checkout") # `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create # -token def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.grand_total() * 100) try: charge = stripe.Charge.create( amount=amount, # cents currency="usd", source=token, ) # create payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.grand_total() payment.save() # assign the payment to the order order_items = order.items.all() order_items.update(ordered=True) for item in order_items: item.save() order.ordered = True order.payment = payment order.ref_code = create_ref_code() order.save() messages.success(self.request, "Your Order … -
multiples django apps deployment on docker and nginx
hello i want to deploy two Django apps on Docker and Nginx and Gunicorn with different static volume,i am on local with Kali Linux OS. this my docker-compose.yml: version: '3' services: appone: build: ./appone volumes: - .:/opt/services/appone/src - static_volume:/opt/services/appone/static # <-- bind the static volume - media_volume:/opt/services/appone/media # <-- bind the media volume networks: - nginx_network - database1_network depends_on: - database1 apptwo: build: ./apptwo volumes: - .:/opt/services/apptwo/src - static_volume:/opt/services/apptwo/static # <-- bind the static volume - media_volume:/opt/services/apptwo/media # <-- bind the media volume networks: - nginx_network - database2_network depends_on: - database2 nginx: image: nginx:1.13 ports: - 8000:80 - 8001:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/opt/services/appone/static # <-- bind the static volume - media_volume:/opt/services/appone/media # <-- bind the media volume - static2_volume:/opt/services/apptwo/static # <-- bind the static volume - media2_volume:/opt/services/apptwo/media depends_on: - appone - apptwo networks: - nginx_network database1: image: postgres:10 env_file: - config/db/env networks: - database1_network volumes: - database1_volume:/var/lib/postgresql/data database2: image: postgres:10 ports: - "5433:5432" env_file: - config/db/env2 networks: - database2_network volumes: - database2_volume:/var/lib/postgresql/data networks: nginx_network: driver: bridge database1_network: driver: bridge database2_network: driver: bridge volumes: database1_volume: database2_volume: static_volume: # <-- declare the static volume media_volume: # <-- declare the media volume static2_volume: # <-- declare the static volume media2_volume: and my … -
Connecting django signal to a button click
I'm trying to use a Django signal to toggle a model's boolean value to False from True when a button is clicked. I think that the Django sender would be the button click and the receiver would be the function that changes the boolean value. I'm not sure how to write out a button click as a signal sender however. -
Using APIs in a React Template
I am learning the ropes of React and JavaScript. I started by grabbing a free template I found from GitHub. After creating a few other pages, I connected the app to a Django back end and created a model with two entries. The objective is to be able to display the information from the model like title, objective, etc. I'm also new to using APIs to get this information, so I've been looking through various places online, but I just can't figure out how to fit in the code examples online with the code I have from the template from GitHub. One of the places I've looked: https://reactjs.org/docs/faq-ajax.html Below is Hero.js. This is routed to the home page and it's just what the template provider named it. The code example provided above and in many other places I've looked puts all their code in App.js. I know they're just doing that for demonstration purposes, but I'm not sure how to fit it into the template code. import React, { useState } from 'react'; import classNames from 'classnames'; import { SectionProps } from '../../utils/SectionProps'; import ButtonGroup from '../elements/ButtonGroup'; import Button from '../elements/Button'; import Image from '../elements/Image'; import { Link } from … -
django at aws for iot logging and rendering of data
I am planning on making a django iot project hosted on aws ec2 instance. The architecture is on the picture. The sensor's data will be read by raspberry pi 3 and will be sent to django web app (django/raspi-data/) on json format hosted on an ec2 instance by creating an api to communicate the raspberry with django. The sent data will be logged on a postgresql hosted on aws rds. For the user to be able to see the data summary, he/she will access another web app (django/client/) hosted on the same ec2 instance as the previous one. The web app will get the data from postgresql db and will be sent to the user's browser in json format. javascript then will handle how to summarize the data. The user can choose if s/he want to render the data in line graph on daily average reading of the data or in monthly basis. My question is, is this architecture good? or there are any problems here? if there are problems, what could be the possible solution for these? -
How to install PyAudio correctly for Python 3.8.4?
I have installed PyAudio 0.2.11 and I'm trying to deploy a Django application in Heroku. Everything is going well until I do git push heroku master and while installing the requirements the following error comes up: ERROR: PyAudio-0.2.11-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. The complete record is: remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.11 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: ERROR: PyAudio-0.2.11-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to rwa-apirest. remote: To https://git.heroku.com/rwa-apirest.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/rwa-apirest.git' My requirements.txt is asgiref==3.2.10 astroid==2.4.2 backcall==0.2.0 beautifulsoup4==4.9.1 certifi==2020.6.20 cffi==1.14.0 chardet==3.0.4 ChatterBot==1.0.2 chatterbot-corpus==1.2.0 click==7.1.2 colorama==0.4.3 comtypes==1.1.7 cryptography==2.9.2 decorator==4.4.2 dj-database-url==0.5.0 Django==3.0.8 django-cors-headers==3.4.0 django-environ==0.4.5 django-rest-knox==4.1.0 django-webpack-loader==0.7.0 djangorestframework==3.11.0 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==4.4.0 docopt==0.6.2 gTTS==2.1.1 gTTS-token==1.1.3 gunicorn==20.0.4 idna==2.10 inflection==0.5.0 ipykernel==5.3.2 ipython==7.16.1 ipython-genutils==0.2.0 isort==4.3.21 jedi==0.17.1 joblib==0.16.0 Js2Py==0.70 jupyter-client==6.1.5 jupyter-core==4.6.3 lazy-object-proxy==1.4.3 mathparse==0.1.2 mccabe==0.6.1 more-itertools==8.4.0 nltk==3.5 numpy==1.19.0 packaging==20.4 pandas==1.0.5 parso==0.7.0 pickleshare==0.7.5 Pint==0.14 pipwin==0.5.0 playsound==1.2.2 prompt-toolkit==3.0.5 psycopg2==2.8.5 PyAudio … -
OSError in django.contrib.gis : [WinError 127] : The specified procedure could not be found
I am following this guide to build location based web app. Also followed the installlation guide on Django official site. I am getting this error when I try to add django.contrib.gis in my installed app and try to perform any task using manage.py. The solution that solution here does not work for me. I have doubled checked that I am using only one version of python with Anaconda. I have also made sure that I install GDAL in my virtualenv and that directories and files are present in django/contrib in my virtualenv. I am still getting this error and seem to find no fix for this. -
Error in sending email using gmail smtp in Django app
I set up everything as the Django documentation but when I test sending an email.It works but When I check my inbox I find out that I sent and revived from to the same email address. Here is the settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "myemail@gmail.com" EMAIL_HOST_PASSWORD = "mypassword" And the views.py ... send_mail( 'subject', 'message', 'user@gmail.com', ['myemail@gmail.com',], fail_silently=False, ) ... But I received an email from myemail@gmail.com to me(myemail@gmail.com). -
Python pandas, stock portfolio value timeseries
I'm trying to build a time series consisting of the market value of my portfolio. The whole website is build on django framework. So the datasets will be dynamic. I have a dataset named dataset, this dataset is containing stocks close price: YAR.OL NHY.OL date 2000-01-03 NaN 18.550200 2000-01-04 NaN 18.254101 2000-01-05 NaN 17.877100 2000-01-06 NaN 18.523300 2000-01-07 NaN 18.819500 ... ... ... 2020-07-27 381.799988 26.350000 2020-07-28 382.399994 26.490000 2020-07-29 377.899994 26.389999 2020-07-30 372.000000 25.049999 2020-07-31 380.700012 25.420000 And I have a dataframe named positions consisting of the positions in a users portfolio: Date Direction Ticker Price ... FX-rate Comission Short Cost-price 0 2020-07-27 Buy YAR.OL 381.0 ... 1.0 0.0 False 381.0 1 2020-07-31 Sell YAR.OL 380.0 ... 1.0 0.0 False -380.0 2 2020-07-28 Buy NHY.OL 26.5 ... 1.0 0.0 False 26.5 code for the postions dataset: data = zip(date_list, direction_list ,ticker_list,price_list,new_volume_list,exchange_list,commision_list,short_list, cost_price_list) df = pd.DataFrame(data,columns=['Date','Direction','Ticker','Price','Volume','FX-rate','Comission','Short','Cost-price']) Further, I have managed to split the postions dataset into one dataset for each ticker: dataset = self.dataset_creator(n_ticker_list) dataset.index = pd.to_datetime(dataset.index) positions = self.get_all_positions(selected_portfolio) for ticker in n_ticker_list: s = positions.loc[positions['Ticker']==ticker] s = s.sort_values(by='Date') print(s) This gives me: Date Direction Ticker Price ... FX-rate Comission Short Cost-price 0 2020-07-27 Buy YAR.OL 381.0 ... 1.0 … -
How to deploy django channels with Apache and Daphne?
I am trying to deploy this django app which uses channels. I use Apache for regular HTTP requests and want to forward the web socket requests to Daphne. Here are some of my important files: apache config: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR] RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC] RewriteRule .* ws://127.0.0.1:8001%{REQUEST_URI} [P,QSA,L] Alias /static /home/anna/tchan/static <Directory /home/anna/tchan/static> Require all granted </Directory> Alias /media /home/anna/tchan/media <Directory /home/anna/tchan/media> Require all granted </Directory> <Directory /home/anna/tchan/tchan> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/anna/tchan/tchan/wsgi.py WSGIDaemonProcess django_app python-path=/home/anna/tchan python-home=/home/anna/tchan/venv WSGIProcessGroup django_app </VirtualHost> Last few lines of settings.py: ASGI_APPLICATION = 'tchan.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 8001)], }, }, } asgi.py import os import django from channels.routing import get_default_application from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tchan.settings') django.setup() application = get_default_application() With these in place, I run daphne -p 8001 tchan.asgi:application and then sudo service apache2 reload. Finally, when testing the websocket in my page here's what happens: websocket.js:4 WebSocket connection to 'ws://192.168.0.57/ws/chat/8/' failed: Error during WebSocket handshake: Unexpected response code: 403 This error 403 happens whether or not I'm running daphne. What am I doing wrong here? Note: the … -
Django Error: 'OrderItem' object has no attribute 'order'
I am trying to fix an error AttributeError at /update-qty which appears which I try to update the quantity related to items in order summary page in my project I have indicated the line related to the error showing. Here is the views.py: class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'order_summary.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("/") @login_required def update_qty(request): if request.method == 'POST': item_slug = request.POST.get('item_slug', None) # Check for an order_item order_item_pk = request.POST.get('order_item', None) order_item = OrderItem.objects.filter(pk=order_item_pk).first() if not order_item: messages.info(request, "Product was not in your cart") return redirect("product", slug=item_slug) # Check for an active order order = Order.objects.filter(user=request.user, ordered=False).first() if not order: messages.info(request, "You do not have an active order") return redirect("product", slug=item_slug) # Check that order_item is in active order if not order_item.order == order: <---------------------------------------- Error line messages.info(request, "Product was not in your cart") return redirect("product", slug=slug) # Update quantities action = request.POST.get('action', None) if action == "plus": order_item.quantity += 1 order_item.save() messages.info(request, "Product quantity was updated.") elif action == "minus": order_item.quantity -= 1 if order_item.quantity < 1: order_item.delete() messages.info(request, "Product was removed from … -
Are there any extensions for django for automatic generation PlantUML diagram code of django models?
The whole question in the title. I would like to generate PlantUML class diagram of my application, are there any ways to do this? -
Where is stored index file example in python Django?
Starting study Django, i try check all files of project example installation For example when we install and run Apache with PHP we can see the tipical index.html on /var/www/html/index.html. I know Django run over MTV pattern and it is new fo me, like MVC too. I try understand how script call and mount the presentation page in web. Well the question is, where is stored, the index.html it we see when we start Django, the example page? -
Sorting a list of Model Objects before bulk_create - object is not subscriptable?
I'm reaching out to an external API and saving that information to a model. However, before saving to the model I need to sort the items by a key (price) and assign a unique ID (this is a custom ID we use a function to create) to the item. So the process looks like this: Loop through the external API Each item from the external API is saved to a updated_listings list When the loop is done, save list of items to the model using bulk_create However, before step 3 (before saving to the database), I need to assign a each item a unique ID. Here is what I have so far (simplified a bit for sanity). get_listings.py # Loop through all pages of API to get all listings def get_all_listings(card_type, model): updated_listings = [] item_to_add = model ( price = listing["best_sell_price"], ) # We push the objects into a list so we can bulk add them to the DB updated_listings.append(item_to_add) # Before pushing the updated objects to the DB, we need to add unique listingsIDs listings_with_unique_ids = update_all_listing_ids(updated_listings) # Save items to the model model.objects.bulk_create(listings_with_unique_ids, ignore_conflicts=True) create_unique_listings_ids.py def update_all_listing_ids(listings): sorted_listings = listings.sort(key=itemgetter('price'), reverse=True) print(type(sorted_listings)) However, I'm getting the following … -
Dev Test and Prod Env Django with Elastic Beanstalk
I have three envs for my Django app: Dev: local Test: hosted on EBS Prod: hosted on EBS I want to setup a blue green deployment configuration. I have two ideas to do so: In my Django app, check if the current url is myapp.com vs. myapp-test.com and change the settings accordingly. Then just switch the CNAME for two different EBS instances. Use environment variables on each EBS instance and change the settings accordingly in my Django app based on an environment variable. Then just switch the CNAME for two different EBS instances. What is the best way to do this? Thanks! -
Django Error: update_qty() got an unexpected keyword argument 'slug'
I am trying to fix an error when I try to update the number of items in Order Summary Page which returns update_qty() got an unexpected keyword argument 'slug' There is no specific line indicating the reason for this error Here is the views.py: class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'order_summary.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("/") Here is the template: <div class="pull-center"> <form method="POST" action="{% url 'core:update-qty' order_item.item.slug %}"> {% csrf_token %} <button type="submit" name="action" value="minus" class="btn mr-2"><i class="fa fa-minus"></i></button> {{ order_item.quantity }}<button type="submit" name="action" value="plus" class="btn ml-2"><i class="fa fa-plus"></i></button> <input type="hidden" name="item_slug" value="{{ order_item.item.slug }}"> <input type="hidden" name="order_item" value="{{ order_item.pk }}"> </form> </div> </td> here is the urls: path('update-qty/<slug>/', update_qty, name='update-qty'), Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() slug = models.SlugField(unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_update_qty(self): return reverse("core:update_qty", kwargs={ 'slug': self.slug })