Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Processing live RTMP stream using OpenCV and then streaming to browser [on hold]
Below is the use case with which i need some help. I am working on Windows platform and using Django for web development. 1) Get live stream from a drone. The drone uses RTMP to stream video feed. Hence, I setup nginx server(nginx 1.7.11.3 Gryphon) which has RTMP support. Using this, I was able to stream the feed to my nginx server(tested succesfully using VLC player). 2) Process the live stream. The live RTMP stream then needs to be processed for object detection using OpenCV with Python. ## capture video stream using OpenCV libray ## Process the stream using OpenCV library 3) The above processed video needs to be displayed in browser(in localhost itself) on Django server, as I am building a web application. This is what I need help with. I am not sure how to return an HTTP/HLS stream from the view to the web page. I understand we can configure the Nginx server to convert RTMP to HLS, but am not sure how to proceed now that processing is involved in the middle. I tried searching for packages in Django/OpenCV which will help convert, and found approaches using FFMPEG libraries, but I am not sure if it … -
cannot resolve "{% static 'images/image_name.jpg' %}
I am new to django and cannot seem to load images with bootstrap. I'm getting the error cannot resolve "{% static 'images/image_name.jpg' %} I understand that it is not finding the path. Notice that index.html is in products/templates and base.html is in templates/ . index.html extends base.html. Please tell me where am i setting the path wrong? This is my folder structure folder structure E:. | 1.py | db.sqlite3 | manage.py | +---.idea | hello-world.iml | misc.xml | modules.xml | workspace.xml | +---products | | admin.py | | apps.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | | | 0001_initial.py | | | 0002_offer.py | | | __init__.py | | | | | \---__pycache__ | | 0001_initial.cpython-37.pyc | | 0002_offer.cpython-37.pyc | | __init__.cpython-37.pyc | | | +---templates | | index.html | | | \---__pycache__ | admin.cpython-37.pyc | apps.cpython-37.pyc | models.cpython-37.pyc | urls.cpython-37.pyc | views.cpython-37.pyc | __init__.cpython-37.pyc | +---pyshop | | settings.py | | urls.py | | wsgi.py | | __init__.py | | | \---__pycache__ | settings.cpython-37.pyc | urls.cpython-37.pyc | wsgi.cpython-37.pyc | __init__.cpython-37.pyc | +---static | | press-single.html | | single.html | | | +---admin | | +---css | … -
How to remove index from csv file?
I am writing CSV file in html but whenever I run code it become save in table.html but its shows the index numbers also in browser. I want to remove index numbers and just want to show names. import pandas as pd df = pd.read_csv('filo.csv') with open('table.html', 'w') as html_file: df.reset_index(drop=False) df.to_html(html_file) -
Can I use react-native with django?
I want to use React-native to make an app and I wanted to use Django with it as the back-end due to it's high leveled performance therefore I want to know if I can use React-native and Django together if yes how? Is there any tutorial video? Thanks Appreciate it if you can kindly answer. -
Overwriting create model to send nested data in REST framework returns empty list
I have two models with a many to many relation and I am trying to send nested data to my API. Unfortunately it only gives me back an empty array. This is what I am trying: my models: class Building(models.Model): name = models.CharField(max_length=120, null=True, blank=True) net_leased_area = models.FloatField(null=True, blank=True) class BuildingGroup(models.Model): description = models.CharField(max_length=500, null=True, blank=True) buildings = models.ManyToManyField(Building, default=None, blank=True) My generic API view: class BuildingGroupCreateAPIView(CreateAPIView): queryset = BuildingGroup.objects.all() serializer_class = BuildingGroupSerializer My serializer: class BuildingGroupSerializer(serializers.ModelSerializer): buildings = BuildingSerializer(many=True) class Meta: model = BuildingGroup fields = ( 'description', 'buildings', ) def create(self, validated_data): buildings_data = validated_data.pop('buildings') building_group = BuildingGroup.objects.create(**validated_data) for building_data in buildings_data: Building.objects.create(building_group=building_group, **building_data) return building_group When I send data it returns this: {"description":"Test Description API","buildings":[]} In the array I would like to have my array of dictionaries. I am trying to follow the REST documentation here when I am overwriting the create method to send a nested object. (https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers) and I thought I am doing this correctly, but epic fail. I send data with request with my custom method like this: test_api_local(method="post", data={ "description": "Test Description API", "buildings": [{'name' : 'Testname'}, .... ], }) Any help is very appreciated. Thanks so much!! -
Django JWT extended TokenObtainPairSerializer not using overridden validate method
I've extended the TokenObtainPairSerializer class and re-wrote the validate method so when a user tries to login, they can use either a username or email. I've passed the extended class into the as_view init kwargs in my url_parameters. I know the extended class's validate method isn't called because I've put print('working') at the top of the method, which isn't printed when I send the request. I appreciate any help in advance. serializers.py from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from .models import Player from . import uuid_cache import re email_re = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") class InterchangeableJWTSerializer(TokenObtainPairSerializer): def validate(self, attrs): print('working') credentials = { 'email': '', 'password': attrs.get("password") } player = None login_input = attrs.get("username") if email_re.match(login_input): player = Player.objects.filter(email=login_input).first() else: uuid = uuid_cache.get_uuid(login_input) if uuid: player = Player.objects.filter(minecraft_uuid=uuid).first() if player: credentials['email'] = player.email return super().validate(credentials) urls.py # http://localhost:8000/api/token/ url(r'^api/token/$', TokenObtainPairView.as_view(serializer_class=InterchangeableJWTSerializer), name='token_obtain_pair'), url(r'^api/token/refresh/$', TokenRefreshView.as_view(), name='token_refresh') -
How can I join two MySql Database tables using Django and fetch data from both of them and view in browser using Django Rest Framework?
Actully I wrote a code in python using Django and MySql Database to join two tables and fetch data from both the tables and view them in browser using Django Rest Framework...I want to use raw sql query to do so and I have done so but it is not working...I am posting the code. Can anyone please help me out...???And yes I am using pagination...and data is coming from one table only...Please help.... view.py @api_view(['GET','POST']) def index(request): if request.method=='GET': all_dataobj=fetchdata.objects.raw("SELECT fetchdata.*, fetchdata_dum.* FROM fetchdata LEFT JOIN fetchdata_dum ON fetchdata.id = fetchdata_dum.ma_id") paginator = CustomPagination() result_page = paginator.paginate_queryset(all_dataobj, request) pserializer=fetchdataSerializers(result_page,many=True) return paginator.get_paginated_response(pserializer.data) # return Response(pserializer.data,status=status.HTTP_201_CREATED) elif request.method=='POST': serializer=fetchdataSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) model.py from django.db import models class fetchdata(models.Model): id = models.IntegerField first_name = models.CharField(max_length=250) middle_name = models.CharField(max_length=15) last_name = models.CharField(max_length=250) email = models.CharField(max_length=250) ma_id = models.CharField(max_length=250) menu_item_id = models.CharField(max_length=250) item_id = models.CharField(max_length=250) meta_key = models.CharField(max_length=250) meta_value = models.CharField(max_length=250) date_added = models.CharField(max_length=250) date_updated = models.CharField(max_length=250) class Meta: db_table = 'fetchdata' class fetchdata_dum(models.Model): id = models.IntegerField fetchdata_id = models.IntegerField first_name = models.CharField(max_length=250) middle_name = models.CharField(max_length=15) last_name = models.CharField(max_length=250) email = models.CharField(max_length=250) ma_id = models.CharField(max_length=250) menu_item_id = models.CharField(max_length=250) item_id = models.CharField(max_length=250) meta_key = models.CharField(max_length=250) meta_value = models.CharField(max_length=250) date_added = … -
What changes are needed to my django app when deploying to pythonanywhere? error points to nowhere
Deploying my django website with S3 as storage which runs fine locally to pythonanywhere gives a strange error I can't google a solution for: "TypeError: a bytes-like object is required, not 'str'" What I'm doing wrong? I've tried to put my environment variables out of settings.env (aws keys, secret_key, etc) ad set them directly in my settings.py app. + every suggestion I could find but it's still the same :( here's my /var/www/username_pythonanywhere_com_wsgi.py: # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys from dotenv import load_dotenv project_folder = os.path.expanduser('~/portfolio_pa/WEB') # adjust as appropriate load_dotenv(os.path.join(project_folder, 'settings.env')) # assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py' path = '/home/corebots/portfolio_pa' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'WEB.settings' ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ###### or, for older Django <=1.4 #import django.core.handlers.wsgi #application = django.core.handlers.wsgi.WSGIHandler() I'd expect the website to run fine just like it does locally. -
Getting an error with syntax getting a JSON file
I'm having a problem building a Twitter random quotes generator API. I'm following this tutorial: https://www.twilio.com/blog/build-deploy-twitter-bots-python-tweepy-pythonanywhere But I get an error that he doesn't have. This is the code: import requests api_key = '*****' api_url = 'https://andruxnet-random-famous-quotes.p.rapidapi.com' headers = {'afd9cbe77emshf06f5cb2f889689p1ca1c3jsne6e79ad808cc' : api_key, 'http://andruxnet-random-famous-quotes.p.rapidapi.com' : api_url} # The get method is called when we # want to GET json data from an API endpoint quotes = requests.get(quotes = requests.get(api_url, headers=headers) print(quotes.json()) And this is the error: File "twitter_bot.py", line 12 print(quotes.json()) SyntaxError: invalid syntax What am I doing wrong?? (I put *** on the key on purpose, I know the proper key is supposed to go there) Thank you! -
took too long to shut down and was killed
WARNING Application instance <Task pending coro=<__call__() running at /home/developer/projects/tabcon/tabcon_env/lib/python3.5/site-packages/channels/http.py:191> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/lib/python3.5/asyncio/futures.py:431, Task._wakeup()]>> for connection <WebRequest at 0x7ffa40e17b00 method=GET uri=/ clientproto=HTTP/1.1> took too long to shut down and was killed. The above exception is showing and entire service is stopped running, using channels==2.0 channels_redis==2.2.1 daphne==2.2.2 Django==2.1 channels_redis==2.2.1 -
How to view that items[ ] matrix in a html file instead?
The code is below in the image which prints a matrix items [ ]. I need to show that matrix in a html file instead. How to do that ? -
Django save file without using form, just by using ajax
How can i save file in database without using forms. models.py class mymodel(models.Model): lecture_video = models.FileField(upload_to='folder/', blank=True, null=True) ajax and html <input id="id_video" type="file"> <button onclick="upload_video()">save</button> function upload_video(){ var formData = new FormData(); formData.append('file', $('#id_video')[0].files[0]); console.log(formData) $.ajax({ type:'GET', url : '/upload-video/', async: true, data:formData,, contentType: false, processData: false, success : function(data){ alert(data) } }) } views.py def upload_videos(request): video_file = request.GET.get('formData') # how to save video_file.save() return Httpresponse('saved') -
Django Forms Set Name Of The Form
How can I set the name of the form with model form ? This is my model form : class DetayModelForm(forms.ModelForm): class Meta: model = Detay fields = [ 'yazi', 'tip', 'kullanimAdet'] I know how to set name attribute of a field in a form, there are a lot of examples also. But I really really couldn't find that how can I set the form's own name , not a field in the form, exactly form's own name attribute; in the ModelForm class. In html side , I will use this attribute : https://www.w3schools.com/tags/att_form_name.asp I need to use html form name attribute in my template but, I couldn't find how to add this attribute to the form directly in ModelForm class. I tried to use init in ModelForm class like that : def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.name = 'DetayFormu' But in html side, still form doesn't have a name attribute. And also I know , yes I can set this attribute in my template like that : <form method="post" name="DetayFormu"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Sign in</button> </form> But I really wonder how can I set this attribute in ModelForm class directly. How can … -
unable to filter or search the data in different languages in django
I have posted data(ex:title field) in different languages, when i try to filter the data in get request it is giving empty result GET /rails: My get request result is : [ { "id": 1, "type": "channel", "filter": [ 1 ], "data": [ 1 ], "status": 0, "rows": 0, "title": "string" }, { "id": 2, "type": "appgg", "filter": [ 2 ], "data": [ 2 ], "status": 1, "rows": 2, "title": "ಚಲನಚಿತ್ರ" } ] when i try to filter title data i am getting empty result GET /rails?title=ಚಲನಚಿತ್ರ: expected result : [ { "id": 2, "type": "appgg", "filter": [ 2 ], "data": [ 2 ], "status": 1, "rows": 2, "title": "ಚಲನಚಿತ್ರ" } ] Actual result: [] when I try to print request params in my django views like below: title = self.request.query_params.getlist('title',None) print(title) I am getting the following log: title filter �²¨�¿¤Í° Django is unable to identify the language I am passing, How can I add multi-language support in Django? Thanks -
Openpyxl library is not retaining the images on save
I have to manipulate an excel workbook. I was using xlrd library but because it was not retaining the images I had to move to openpyxl library of the latest version (2.6.4). It is still not working on the save. Please let me know if I'm missing out on something.. I have executed the same code on a QA server and it works absolutely fine. But on PROD it gives me a problem wb = openpyxl.load_workbook('Empty2.xlsx') // excel manipulation wb.save('Empty3.xlsx') I want to retain the images on the saved 'empty3.xlsx' file. -
Reusing subqueries for ordering in Django ORM
I run a dog salon where dogs get haircuts on an infrequent basis. In order to encourage customers back I would like to send out vouchers for their next visit. The voucher will be based on whether a dog has been washed within 2 months - 2 years. Before that is too soon and after that we assume that we have lost the customer. My underlying database is PostgreSQL. from datetime import timedelta from django.db import models from django.db.models import Min, OuterRef, Subquery from django.utils import timezone # Dogs have one owner, owners can have many dogs, dogs can have many haircuts class Owner(models.model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) class Dog(models.model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name="dogs") name = models.CharField(max_length=255) class Haircut(models.model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) dog = models.ForeignKey(Dog, on_delete=models.CASCADE, related_name="haircuts") at = models.DateField() today = timezone.now().date() start = today + timedelta(months=2) end = today + timedelta(years=2) It strikes me that the problem can be broken down into two queries. The first is something that aggregates an owner's dogs to most recently washed. dog_aggregate = Haircut.objects.annotate(Min("at")).filter(at__range=(start, end)) And then joins the result of that to the owners table. owners_by_shaggiest_dog_1 = Owner.objects # … -
Django social with facebook backend drops unicode letters from username
When django social auth creates user using facebook backend it drops non-ascii characters from the username. I was unable to find anything that could help me solve this problem. -
How can i use breakpoints to debut django projects
Why my breakpoints doesn't stop enter image description heremy code while debugging on django projects ? -
Where can I can find Django-admin style-guide?
Where can I see Django2 adminsite css/html/image style-guide? Every time I want to place some button/icon/style/comment/list/etc to my custom django template I have to find any examples on other pages and copy source-code from there. Is there any documentation? Thank you! -
Files inside PersistentVolume cannot be overwritten
I have project in GCP using django and created a persistent volume for static files, everything was fine for months until recently a deployment failed because django couldn't overwrite old static files. OSError: [Errno 30] Read-only file system: '/static/admin/img/selector-icons.svg' For now I simply disabled manage.py collectstatic and use the old ones since they don't change very often. My pv.yaml looks like this: metadata: name: backend-pvc labels: type: pvc spec: storageClassName: gce-pd resources: requests: storage: 1Gi accessModes: - ReadWriteOnce - ReadOnlyMany backend.yaml: volumes: persistentVolumeClaim: claimName: backend-pvc and nginx.yaml: volumes: - name: static persistentVolumeClaim: claimName: backend-pvc readOnly: true Checked the pods and volumes are mounted correctly, rw for backend: static-volume: Type: PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace) ClaimName: backend-pvc ReadOnly: false and read only for nginx: static: Type: PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace) ClaimName: backend-pvc ReadOnly: true Anyone has any suggestion how to fix it? Should I just delete PV and create it again? What might have caused this to happen? -
Django : How can I use the response returned by form_valid() of a CreateView on another model in a new template?
I am learning Django, and I am sure the solution is very simple but I can't find it; I have a model "profile" that needs to be filtered by a request. Requests and answers need to be kept in database. But I don't want the user to see all the profiles at any moment. So I wrote two models : the first one contains the requests (MyRequest), the second the potential answers (Profile). Profiles are created importing csv in Django admin. I wrote a code that is working fine BUT I can't figure how to send my response in a template to use all the customizations and securities as csrf_token. Currently it is showing the response in the same url than the request and I am blocked here I have tried to use get_succes_url with HttpResponseRedirect, usually I can do such things using (?P\d+)/$' in the success url but it doesn't work maybe because the two models don't share any key? I have tried to put and in success url but I think I did something wrong """Models""" class Profile(models.Model):#probgerme probpvt probservice probATCDpvt probATCDbmr probNB profname= models.CharField(max_length=20) bq = models.ForeignKey(Bq, on_delete=models.CASCADE)#, blank=True test1 = models.CharField(max_length=100) test2 = models.CharField(max_length=100) test3 = … -
django admin queryset display related objects in a field
def Ark(): li = Forti.objects.all(), Autre.objects.all() list1=list(li) return list1 class License(models.Model): assigne_a = models.CharField(default =Ark, max_length=25, verbose_name="assigné à l'equipement") categorie = models.TextField( max_length=15, choices=Cat_choice, verbose_name='Categorie generale', blank=True) cate = models.TextField( max_length=15, choices=Cat2_choice, verbose_name='Categorie Interne', blank=True) class Meta: verbose_name = 'License' """i want it to display related object in the field assigne_a in sort of list but it is diplaying it like this: [, ]>, ]""" -
cmd.exe is not recognized as an internal or external command when activatin virtual environment
I recently started learning Django and I am working on a small project. I successfully created a virtual environment but whenever I type "pipenv shell" I get this error in the command line which says "cmd.exe is not recognized as an internal or external command, operable programme or batch file" how do I fix it? -
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' When MySql is in Docker
I have mysql running in docker container 0.0.0.0:32768->3306/tcp. I am trying to connect to it using following config: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER': 'test', 'PASSWORD': 'test', 'HOST': 'localhost', 'PORT': '', 'OPTIONS': { 'init_command': "SET NAMES 'utf8'", }, 'TEST': { 'NAME': 'test-3944' } } } I am getting an error from my host ubuntu: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") What is wrong? How to fix this? -
Adding more than one instance of ArrayModelField item with Djongo
I am using djongo to add mongodb to my application. I have a model, say ModelA, that takes in an ArrayModelField of another model ModelB, which is an abstract model. I get a ModelForm for ModelA, but it shows fields for entry of only one ModelB. How can I get a functionality like an Add button, so that more ModelB fields can be added?