Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading images in django using Dropzone
I am trying to upload images using dropzone, giving the user the option to upload images (It is not a required field): However, when uploading images the form does not get submitted correctly and my ajax request does not seem to be executed: Below is my js code for dropzone and ajax: Dropzone.autoDiscover = false; $(document).ready (function () { var myDropzone = new Dropzone("#my-dropzone" , { // my dropzone fields - removed for clarity init: function () { var myDropzone = this; $('#sub-etal').on("click", function (e) { if (myDropzone.getQueuedFiles().length > 0) { e.preventDefault(); e.stopImmediatePropagation(); myDropzone.processQueue(); } else { myDropzone.uploadFiles([]); //send empty } }); this.on('sendingmultiple', function(file, xhr, formData) { // Append all form inputs to the formData Dropzone will POST var data = $('.post-create-form').serializeArray(); $.each(data, function(key, el) { formData.append(el.name, el.value); }); }); this.on("error", function (files, data) { }); myDropzone.on("complete", function(file) { myDropzone.removeFile(file); }); } }); }) my ajax: $('#modal-post').on("submit",".post-create-form", function (e){ e.preventDefault(); e.stopImmediatePropagation(); var form = new FormData(this); $.ajax({ url: $(this).attr('data-url'), type: $(this).attr('method'), data: form, cache: false, processData: false, contentType: false, dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#modal-post').modal('hide'); $('#_np2u').prepend(data.post); } else { $('#modal-post .modal-content').html(data.html_form) } } }) }) my Django form: <form method="POST" data-url="{% url 'home:post-create' %}" id="my-dropzone" class="dropzone post-create-form" enctype="multipart/form-data"> {% csrf_token … -
how to use slug in django urls - i have ((NoReverseMatch)) error
hey im trying to use slug instead of id in my django project but i get NoReverseMatch error how can i fix it ? models.py class Product (models.Model): name = models.CharField(max_length=100) price = models.FloatField(default=0) description = models.TextField(null=True, blank=True) color = models.ForeignKey(Color , on_delete=models.DO_NOTHING) material = models.ForeignKey(Material, on_delete=models.DO_NOTHING) image = models.ManyToManyField(Image) category = models.ForeignKey(Category,on_delete=models.DO_NOTHING , default=0) slug=models.SlugField(max_length=300 , allow_unicode=True , blank=True , null=True , unique=True) views.py def details(request , prslug): pr = get_object_or_404(models.Product , slug=prslug) context = { 'products': pr } return render(request, "prDetails.html" , context) urls.py urlpatterns = [ path('' , views.page), path('<slug:slug>/' , views.details , name="details") ] prDetails.html <a href="{% url 'details' pr.slug %}" class="h4">{{pr.name}}</a> and i get this error : Exception Type: NoReverseMatch Exception Value: Reverse for 'details' with keyword arguments '{'slug': 'first_product'}' not found. 1 pattern(s) tried: ['paachin/(?P[-a-zA-Z0-9_]+)/$'] -
What is the best way to go about creating Django model instances from API using Python script?
I am creating a webapp that displays interesting graphics using my running data (from Strava API) using Django. I'm currently trying to figure out how I want to populate my database. Currently, I have a script written (in python) that gets all of my running activities from the API. I want to make all of these into instances in the Django model called Run that I have created. I plan on running this script every so often to get any new runs given by the API however, the API returns ALL of my runs while I only need the new ones after running the script for the first time. What is the best way to go about only selecting the new entries from the API? The way I currently have the script set up, it will try to create a new model instance for EVERY item in the returned API response. Here is my current model for reference: from django.db import models # Create your models here. class Run(models.Model): id = models.IntegerField(primary_key=True) distance = models.DecimalField(max_digits=8, decimal_places=2, null=True) # In meters elapsed_time = models.IntegerField(null=True) # In seconds start_date = models.DateTimeField(null=True) # DateTime object, local average_speed = models.DecimalField(max_digits=8, decimal_places=2, null=True) # In … -
How to use django-chartjs with model
hi i am trying to create Data Logger Dashboard using django i am getting this blank chart , views.py from django.shortcuts import render from django.http import JsonResponse from .models import * from django.views.generic import TemplateView from chartjs.views.lines import BaseLineChartView # Create your views here. class LineChartJSONView(BaseLineChartView): def get_labels(self): levels=DataLogs.objects.values('date_time').distinct() top_levels=[] for l in range(0,100): top_levels.append(levels[l]) print(top_levels) return top_levels def get_providers(self): """Return names of datasets.""" return [] def get_data(self): datas=DataLogs.objects.filter(tag_name='temp') data=[] for l in range(0,100): data.append(datas[l]) print(data) return data line_chart = TemplateView.as_view(template_name='main.html') line_chart_json = LineChartJSONView.as_view() i am generating my data using arduino ,generation code is # Importing packages from pyfirmata import Arduino,util from time import sleep from datetime import datetime import os import mysql.connector import keyboard # configuring board port='COM5' board=Arduino(port) sleep(5) it=util.Iterator(board) it.start() # Configuring Pins a0=board.get_pin('a:0:i') a1=board.get_pin('a:1:i') l=board.get_pin('d:13:o') h=board.get_pin('d:12:o') # massage print(" Dataloger is going to start ") # main loop try: while True: db_connection = mysql.connector.connect( host='localhost', user='root', passwd='101090', auth_plugin='mysql_native_password',database='data_logs', ) db_cursor = db_connection.cursor() db_cursor.execute('USE data_logs') volt_1=0.2 sensor_1=a0.read() sensor_2=a1.read() temp_max=200 pressure_max=10 if type(sensor_1) == type(12.00): percentage=(sensor_1-volt_1)/(.8) data_1=temp_max*percentage if data_1<0: data_1=0 else: data_1=999999 if type(sensor_2) == type(12.00): percentage=(sensor_2-volt_1)/(.8) data_2=pressure_max*percentage if data_2<0: data_2=0 else: data_2=999999 date_time=datetime.now() print("______________________________________________________________________________________________") print(date_time.date()) date_hour=date_time.time() print(date_time) print("______________________________________________________________________________________________") hour_log=date_time.hour print('hour_log : ',hour_log) min_log=date_time.minute print('min_log :',min_log) second_log=date_time.second print('second_log … -
How to block specific user to visit specific pages in Django
My Django project have some 10 apps. I am using default User. Then there is Role model, something like this class Role(models.Model): user_type = models.OneToOneField(User, on_delete = models.CASCADE) is_manager = models.BooleanField() is_employee = models.BooleanField() As I told I have 10 apps. Each app has its urls.py User with is_manager = True can visit all first 8 apps pages(pages those are in urls.py). But they should not be able to visit other 2 app pages. Similarly is_employee = True, User can only visit last 2 app pages and they cannot visit first 8 app pages. I don't know how to achieve such situation. -
How do I call slurm sbatch in a separate process?
I need to run another program with parameters based on the form data. I have a page handler on Django. It builds a .sh file from the form, this file is called in a separate process using Popen and SBatch. All this runs fine but the page itself hangs and memory overflow occurs via the python3 process. Below is a sample program: def sbatch_subproc(self, file_path): >>Creates .sh file. pop_sbatch = subprocess.Popen(args = ["sbatch", sh_file_path]) def post(self, *args, **kwargs): >>The path to the .sh file is created. proc = Process(target = self.sbatch_subproc, args=(sh_file_path)) proc.start() Example .sh file: #!/bin/sh srun ./program -param1 value1 -param2 value2 -param3 value3 exit 0 -
How can I work with a form, that uses a model, which has 2 foreign keys? Automatically updating author and linking form to database
New to django. Currently have 2 problems with one form. I created a form from the model'Submission', in which the user can change the submission _author. How can I set it so that django automatically assigns the current logged in user to the submission_author(undetiable field type of thing)? Whenever I submit the form, this error pops up (NOT NULL constraint failed: themainpage_submission.post_id), where post_id is taken from the Submissions model(linked image). How can this be fixed? sceenshot from the database models.py class Post(models.Model): title = models.CharField(max_length=40) author = models.ForeignKey(User, on_delete=models.CASCADE) post_creation_time = models.DateTimeField(auto_now_add=True) genre = models.CharField(max_length=30, blank=True, null=True, choices= genre_choices) stage = models.CharField(max_length=30, blank=True, null=True, choices= stage_choice) optional_notes = models.CharField(max_length=80, default= 'dummy-text') def get_absolute_url(self): return reverse('home_view') def __str__(self): return self.title + ' | ' + str(self.author) class Submission(models.Model): post = models.ForeignKey(Post, related_name='submissions', on_delete=models.CASCADE) submission_author = models.ForeignKey(User, on_delete=models.CASCADE) submission_title = models.CharField(max_length=40) submission_creation_time = models.DateTimeField(auto_now_add=True) submission_body = models.TextField() def __str__(self): return self.submission_title + ' | ' + self.submission_body forms.py class CreateNewSubmission(forms.ModelForm): class Meta: model = Submission fields = ('submission_title', 'submission_body', 'submission_author') urls.py path('view_post/<str:pk>', views.ViewPostMain, name='view_post'), path('view_post/<str:pk>/create_submission', CreateSubmission.as_view(), name='create_submission'), views.py def ViewPostMain(request, pk): post = Post.objects.get(id=pk) submissions = Submission.objects.filter(post_id = pk) context = {'post' : post, 'submissions' : submissions} return render(request, 'view-post.html', context) … -
Django/Graphene Mutation error "you need to pass a valid Django model" can't fix it
Below is the RDBMS diagram of the Django/Graphene example I am working with: Below is the code for my model.py for the app: from django.db import models # Create your models here. class ProductCategory(models.Model): category = models.CharField(max_length=50) parentCategory = models.ForeignKey('self',null=True, on_delete=models.CASCADE) class Product(models.Model): productNumber= models.CharField(max_length=50) description = models.CharField(max_length=50) productCategory= models.ForeignKey('product.ProductCategory', on_delete=models.PROTECT) Below is Schema.py for the app: import graphene from graphene_django import DjangoObjectType from .models import Product, ProductCategory class ProductType(DjangoObjectType): class Meta: model = Product class ProductCategoryType(DjangoObjectType): class Meta: model = ProductCategory class Query(graphene.ObjectType): products = graphene.List(ProductType) productCategories = graphene.List(ProductCategoryType) def resolve_products(self, info): return Product.objects.all() def resolve_productCategories(self,info): return ProductCategory.objects.all() class CreateProductCategory(DjangoObjectType): productCategory = graphene.Field(ProductCategoryType) class Arguments: category = graphene.String(required=True) parentCategory = graphene.Int() def mutate(self, info, category, parentCategory): productCategory = ProductCategory(category = category, parentCategory = parentCategory) productCategory.save() return CreateProductCategory(productCategory=productCategory) return CreateProductCategory(category=category,parentCategory=parentCategory) class Mutation(graphene.ObjectType): createProductCategory= CreateProductCategory.Field() Without the mutation codes, query request works fine as illustrated below But it would output an error when mutation codes are added and I can't figure out what I did wrong as I am a noob. Please help!! AssertionError: You need to pass a valid Django Model in CreateProductCategory.Meta, received "None". -
How can password2 be null in django rest auth registration
I don't want to write password2 in the rest auth. So I want to use RegisterSerializer to remove the value of password2, what can I do? -
What happened if I delete images upload_to in django
So, I made an Image Field model that upload my image to a folder in my computer, the question is I know that this image will use many space in a moment, so what happened if I delete the images of my folder but I already upload it in my website? -
What exactly is rabbitmq heartbeat? How it is used in rabbitmq?
I am having difficulty to understand what is heartbeat in rabbitmq? Does it used at publisher side or consumer side? What would happen is i dont use it while creating connection connection with rabbitmq. I am using python with pika. Please clear my doubts and help me to understand it in simple terms. -
reverse_lazy returns registration/login instead of accounts/login
#url.py (app's url.py) from django.conf.urls import url from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ path('login', auth_views.LoginView.as_view(template_name='accounts/login.html') , name='login' ), path('logout' , auth_views.LogoutView.as_view() , name='logout'), path('signup', views.SignUp.as_view() , name='signup'), ] #views.py from django.shortcuts import render , redirect from django.views.generic import TemplateView , CreateView from django.urls import reverse_lazy from accounts import forms # Create your views here. class HomePage(TemplateView): template_name = 'index.html' class SignUp(CreateView): form_class = forms.UserCreationForm success_url = reverse_lazy('login') template_name = 'accounts/signup.html' class ThanksPage(TemplateView): template_name = 'thanks.html' class TestPage(TemplateView): template_name = 'test.html' Error TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 3.0.3 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: C:\Users\dell\miniconda3\envs\myDjangoEnv\lib\site-packages\django\template\loader.py in select_template, line 47 Python Executable: C:\Users\dell\miniconda3\envs\myDjangoEnv\python.exe Python Version: 3.8.3 Python Path: ['E:\django\simplesocial', 'C:\Users\dell\miniconda3\envs\myDjangoEnv\python38.zip', 'C:\Users\dell\miniconda3\envs\myDjangoEnv\DLLs', 'C:\Users\dell\miniconda3\envs\myDjangoEnv\lib', 'C:\Users\dell\miniconda3\envs\myDjangoEnv', 'C:\Users\dell\AppData\Roaming\Python\Python38\site-packages', 'C:\Users\dell\miniconda3\envs\myDjangoEnv\lib\site-packages'] Server time: Sat, 8 Aug 2020 16:56:32 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: E:\django\simplesocial\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\dell\miniconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\admin\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\dell\miniconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\auth\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\dell\miniconda3\envs\myDjangoEnv\lib\site-packages\bootstrap4\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: E:\django\simplesocial\accounts\templates\registration\login.html (Source does not exist) -
TypeError: FormListView() missing 1 required positional argument: 'request'
I am newbie in django and i have a problem. When starting the server, the following error occurs: File "/home/user/Portfolio/web_project/web_page/urls.py", line 5, in <module> path('', FormListView(), name = 'home'), TypeError: FormListView() missing 1 required positional argument: 'request' I understand that I am not writing the requests correctly, but now I do not understand what exactly the problem is. urls.py: from django.urls import path from .views import FormListView urlpatterns = [ path('', FormListView(), name = 'home'), path('success/', Success(), name = 'success') ] views.py: from django.core.mail import send_mail, BadHeaderError from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .models import Form from django.views.generic import TemplateView def FormListView(request): if request.method == 'GET': form = FormListView() else: form = FormListView(request.POST) if form.is_valid(): name = form.cleaned_data['name'] surname = form.cleaned_data['surname'] email = form.cleaned_data['email'] try: send_mail(name, surname, email, ['kirill_popov_000@mail.ru']) except BadHeaderError: return HttpResponse('Invalid') return redirect('success') return render(request, "index.html", {'form': form}) def Success(request): return HttpResponse('Success!') -
How to publish posts on the home page?
I have some code: models.py (model Posts): STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True db_index=True ) slug = models.SlugField(max_length=200, unique=True) updated_on = models.DateTimeField(auto_now= True) publish = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) views.py class PostList(generic.ListView): queryset= Post.objects.filter(status=1).order_by('-publish') template_name = 'index.html' paginate_by = 6 urls.py path('', views.PostList.as_view(), name='home'), After I create an article in the admin panel, I click publish, the article is not displayed on the main page. But if you restart the server (manage.py run server), then the article appears on the main page. Question: How to make the article appear on page reload and does not require server reboot? -
Get Foreign Objects instead of QuerySet of List of ID's
single line of code to get the Foreign Key objects instead of QuerySet of UUID's. I have three Models, Student, College, Member Models are defined similar to below class Student(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name=models.CharField(max_length=128) class College(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name=models.CharField(max_length=128) class Member(models.Model): student= models.ForeignKey(Student, related_name="students", on_delete=models.CASCADE) college= models.ForeignKey(College, related_name="colleges", on_delete=models.CASCADE) Where Member contains of Student and College as Foreign Key fields Now I want to get all the Students who belong to a particular College based on college_id which should be filtered from the Member model How I am doing now student_ids = Member.objects.filter(college_id=college_id).values("student") Now students is a QuerySet of list of UUID's of Student As I need actual Student objects instead of QuerySet List of UUID's students = Student.objects.filter(id__in=[str(uid) for uid in student_ids]) I feel this is an improper way. Can anyone suggest a single line of code to get the Foreign Key objects instead of QuerySet of UUID's. Thanks in advance -
Efficient Count of Related Models in Django
In my Django app, when I add the host_count field to my serializer to get the number of hosts for each domain, the performance of the API response suffers dramatically. Without host_count: 300ms With host_count: 15s I tried adding 'host_set' to the prefetch_related method but it did not help. Would an annotation using Count help me here? How can I optimize the fetching of this value? serializers.py class DomainSerializer(serializers.Serializer): name = serializers.CharField(read_only=True) org_name = serializers.CharField(source='org.name', read_only=True) created = serializers.DateTimeField(read_only=True) last_host_search = serializers.DateTimeField(read_only=True) host_count = serializers.SerializerMethodField() def get_host_count(self, obj): return Host.objects.filter(domain=obj).count() views.py class DomainList(generics.ListAPIView): def get(self, request, format=None): domains = Domain.objects.prefetch_related('org').all() serializer = DomainSerializer(domains, many=True) return Response(serializer.data) models.py class Domain(models.Model): created = models.DateTimeField(auto_now_add=True) last_host_search = models.DateTimeField(auto_now=True) name = models.CharField(unique=True, max_length=settings.MAX_CHAR_COUNT, blank=False, null=False) org = models.ForeignKey(Org, on_delete=models.CASCADE, blank=True, null=True) -
AttributeError at /handlerequest/ 'AnonymousUser' object has no attribute 'customer' Even when the user is logged in and has the customer attribute
This is my views.py: @csrf_exempt def handlerequest(request): customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) form = request.POST response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': print('order successful') else: print('order was not successful because' + response_dict['RESPMSG']) return render(request, 'paymentstatus.html', {'response': response_dict,'types':Category.objects.all()}) Even when the user is logged in and has customer attribute(shows logged in on other pages of the site and also in admin I have checked that everything is fine) It gives me this error. I have tried several times to check the mistake but I cant figure out what the problem is. Only the page paymentstatus.html is showing this error(rendered by above view) else in all other pages user is being showed logged in. -
How do I get this python program into an HTML user interface?
This is a program for a twitter bot. I am trying to figure out how I can display it in a user friendly html interface. I think the interface will only need several input forms and a display. It would need four inputs for API key, API secret key, Access token, and Access token secret. It would also need inputs for "search" and "numberOfTweets". Finally it would just need a display to show "Tweet liked". I have some experience with Django so I think I could create the interface using it, but I have no idea where to start. Any help would be awesome. Thanks import tweepy import time auth = tweepy.OAuthHandler('API key', 'API secret key') auth.set_access_token('Access token', 'Access token secret') api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) user = api.me() search = '#InternationalBeerDay' numberOfTweets = 500 for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets): try: print('Tweet Liked') tweet.favorite() #print('Retweeted') #tweet.retweet() time.sleep(10) except tweepy.TweepError as e: print(e.reason) except StopIteration: break -
Why can't I iterate through object in get_queryset?
If i use Station.objects.last() in get_queryset method i will get an error TypeError at /data-show/ 'Station' object is not iterable. Why is that and how can i fix it? views.py class ShowStationAndSensorsView(ListAPIView): serializer_class = StationSerializer def get_queryset(self): queryset = Station.objects.last() return queryset serializers.py class SensorSerializer(serializers.ModelSerializer): class Meta: model = Sensor fields = '__all__' def create(self, validated_data): sensor_data = validated_data.pop('sensors') station = Station.objects.create(**validated_data) station.save() for sensor in sensor_data: s = Sensor.objects.create(**sensor) station.sensors.add(s.id) return station -
Error on a django-uwsgi-nginx example on Github
Im starting studying the django-uwsgi-nginx deploy, I have a doubt about an example posted on Github a time ago I will be glad if someone can help me solving my doubts although it may sound pretty noob: In this part: "Generate a Django secret key using the supplied script (python django-uwsgi-nginx/tools/django_secret_keygen.py), and put it in the uwsgi.ini file." I generate the key running the little script is provided (the KEY is umivu6his0a@dtovlw5_*17+pv6)f^=lof+&!e##&4xe2)bi**), and I copy and paste it into uwsgi.ini file, but when I try the part: Copy all static folders into the STATIC_ROOT directory: python manage.py collectstatic --settings=djangosite.settings.prod The shell answer me back with: File "/var/www/django-uwsgi-nginx/djangosite/djangosite/settings/prod.py", line 1, in <module> from .base import * File "/var/www/django-uwsgi-nginx/djangosite/djangosite/settings/base.py", line 22, in <module> SECRET_KEY = os.environ['umivu6his0a@dtovlw5_*17+pv**6)f^=lof+&!e##&4xe2)bi'] File "/usr/lib/python2.7/UserDict.py", line 40, in __getitem__ raise KeyError(key) KeyError: 'umivu6his0a@dtovlw5_*17+pv**6)f^=lof+&!e##&4xe2)bi' I have tracked down the base.py and prod.py files, copy and paste the Key inside them, but I get the exact same answer... What am I doing wrong? Greetings -
Allow choosing among a set of models in Django admin inline
I am trying to build an app to manage government forms in Django. I have structured it like so: A Question represents a field, or a set of fields, of a Form. Forms are made up of many Questions. Procedures are composed of one or more Forms. For example, you may have a Tax Procedure that has two forms: A Form where the user may declare their assets, and A Form where they may declare their wage. Each one of those Forms can have multiple Questions: bank account number, name, telephone number... So, in Django, I started by creating both the Procedure and Form models. For the Question model, I used inheritance: class Question(models.Model): #Parent model title = models.CharField(max_length=100) form = models.ForeignKey(Form, on_delete=models.CASCADE) class Meta: abstract = True class NameSurnameQuestion(Question): name = models.CharField(max_length=100) #Name of the user surname = models.CharField(max_length=100) #Surname Now, on the Form object page in the admin site, they should be able to add any Question to the Form object that is currently being edited, using something like a dropdown menu that has a set of predefined Question types (name, address, phone...). (It's like the process of creation in Google Forms). I can't find a way to … -
Django 3.1: StreamingHttpResponse with an async generator
Documentation for Django 3.1 says this about async views: The main benefits are the ability to service hundreds of connections without using Python threads. This allows you to use slow streaming, long-polling, and other exciting response types. I believe that "slow streaming" means we could implement an SSE view without monopolizing a thread per client, so I tried to sketch a simple view, like so: async def stream(request): async def event_stream(): while True: yield 'data: The server time is: %s\n\n' % datetime.datetime.now() await asyncio.sleep(1) return StreamingHttpResponse(event_stream(), content_type='text/event-stream') (note: I adapted the code from this response) Unfortunately, when this view is invoked, it raises the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/asgiref/sync.py", line 330, in thread_handler raise exc_info[1] File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 231, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "./chat/views.py", line 144, in watch return StreamingHttpResponse(event_stream(), content_type='text/event-stream') File "/usr/local/lib/python3.7/site-packages/django/http/response.py", line 367, in __init__ self.streaming_content = streaming_content File "/usr/local/lib/python3.7/site-packages/django/http/response.py", line 382, in streaming_content self._set_streaming_content(value) File "/usr/local/lib/python3.7/site-packages/django/http/response.py", line 386, in _set_streaming_content self._iterator = iter(value) TypeError: 'async_generator' object is not iterable To me, this shows that StreamingHttpResponse doesn't currently support async generators. I tried to modify StreamingHttpResponse to use async … -
Django video streaming
greetings! I'm trying to implement a video streaming application in django. the consumer of the video will be a mobile application which would stream and display the video. My requirement is to ensure that I stream the video (like in youtube), rather than downloading the video file and playing it on the device. I did go through the various resources available. I have the following implemented currently. urls.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import video_stream urlpatterns = [ path('admin/', admin.site.urls), path(r'videos/', video_stream, name='v_stream'), #url(r'^media/', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py import os, mimetypes from django.http import HttpResponseNotFound from ranged_response import RangedFileResponse from django.core.files.storage import default_storage from django.http import HttpResponse from django.core.files.storage import FileSystemStorage from django.conf import settings import urllib, mimetypes from django.http import HttpResponse, Http404, StreamingHttpResponse, FileResponse import os from django.conf import settings from wsgiref.util import FileWrapper import requests def video_stream(request): r = requests.get('http://127.0.0.1:8000/media/watermark.mp4', stream=True) response = StreamingHttpResponse(streaming_content=r) return response when I run the application, I do not get the video playing, however, I get the following: I tried using the vlc media player's stream from url function. I got the following error. System check … -
``` SECRET_KEY = config('SECRET_KEY') NameError: name 'config' is not defined```
I get that error when try to ```heroku run python manage.py migrate tree enter image description here i followed this tutorial Traceback C:\Users\Notnik-kg\Desktop\test\task-4-course-app-master>heroku run python manage.py migrate Running python manage.py migrate on ⬢ second-2... up, run.1359 (Free) Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/courses/settings.py", line 25, in <module> SECRET_KEY = config('SECRET_KEY') NameError: name 'config' is not defined -
Fill Django list based on another list selection
Is it possible to fill one form drop down list based on the selected item from another list? if possible How can I do this. Or should I use Java script?