Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django | How to use Html Templates without requirements of static and urls
I am sorry I can't frame the title to define exactly what I want, But I'll describe that here, in brief So I am making a Website selling project and in that project, I want the previewing functionality for themes. Now, If I were to go in an ideal way, making a preview app and adding themes inside templates, then I will have to add tons of URLs in urls.py file. Can anyone help me finding the best approach to gaining the functionality I want?. I am not attaching any files cause I don't think those are required to ans this. Still If you wanna have look at one, I'll attach it. Thanks -
Python, setting property causes Fatal Error
I'm trying to set a property on a class: class HandleOngoingStream: def __init__(self): self.live_data = None @property def live_data(self): return self.live_data @live_data.setter def live_data(self, value): url = 'http://monidor.herokuapp.com/' req = requests.get(url) my_data = req.json() self._live_data = my_data if __name__ == '__main__': data = HandleOngoingStream() print(data.live_data) I'm running This class inside a Django Project and using the PyCharm community version (not sure if maybe that's what causing this) When trying to debug this code ( using PyCharm's debugger) I'm getting the following error: Fatal Python error: Cannot recover from stack overflow. Python runtime state: initialized Thread 0x00007fa990be4700 (most recent call first): File "/usr/lib/python3.8/threading.py", line 306 in wait File "/usr/lib/python3.8/threading.py", line 558 in wait File "/snap/pycharm-community/211/plugins/python-ce/helpers/pydev/pydevd.py", line 144 in _on_run File "/snap/pycharm-community/211/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 216 in run File "/usr/lib/python3.8/threading.py", line 932 in _bootstrap_inner File "/usr/lib/python3.8/threading.py", line 890 in _bootstrap Thread 0x00007fa9913e5700 (most recent call first): File "/snap/pycharm-community/211/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 290 in _on_run File "/snap/pycharm-community/211/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 216 in run File "/usr/lib/python3.8/threading.py", line 932 in _bootstrap_inner File "/usr/lib/python3.8/threading.py", line 890 in _bootstrap Thread 0x00007fa991be6700 (most recent call first): File "/usr/lib/python3.8/threading.py", line 306 in wait File "/usr/lib/python3.8/queue.py", line 179 in get File "/snap/pycharm-community/211/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 365 in _on_run File "/snap/pycharm-community/211/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 216 in run File "/usr/lib/python3.8/threading.py", line 932 … -
user foreign key in django rest framework
I have one user model and Accesskey model. I want to save user who is accessing the API(access_key) in the accesskey table. models.py class AccessKeys(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user',null=True) access_keys =models.CharField(max_length=400) def __str__(self): return self.access_keys serializers.py class AccessKeySerializer(serializers.ModelSerializer): user_id = serializers.RelatedField(source='CustomUser', read_only=True) access_keys = serializers.CharField(max_length=200,required=True) class Meta: model =AccessKeys fields = '__all__' views.py class AccessKeyView(generics.ListCreateAPIView): permission_classes = [IsAuthenticated, ] queryset = AccessKeys.objects.all() serializer_class = AccessKeySerializer def post(self,request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) when I'm saving accesskey in the model there is null value in user_id field. -
Stream large video file in chunks to client browser using django
I'm building a web-app like Netflix and AmazonPrime just to explore knowledge about Django. My app is almost ready running on localhost. But it's streaming performance is very poor. I thought my router may not be able to stream such large data (in GB) that's why the video streaming is lagging. But when I took an insights on network monitor I noticed very strange network activity. When I click play button to play the video the entire bandwidth shoots up to 12mbps still it buffers, after some 45 seconds bandwidth drops significantly in kbps and video streaming starts. While the playback is going I cannot jump to the Nth time of the video. I did intense googling and found that for such large video, data is streamed to client in chunks. When I search for specific example related to django almost all of them are based on streaming live camera streaming to the client browser using OpenCV and Gstreamer (which is definitely no related to my project). Please provide me a short clean example or article of django StreamHttpResponsewhich streams local storage video to client in chunks. I have checked django documentation but it is based on csv file streaming. -
how to get first element of every sublist of a list (django template)
There is a list in view.py alist = [['Australian', 10], ['Canadian', 20], ['German', 6]] context = { 'alist':alist } In the HTML, How can I display the first element of each sublist only. like <a>Australian</a> <a>Candian</a> <a>German</a> -
Why EmailMultiAlternatives Not Sending Email?
I'm trying to send a message to an email address with a pdf attachment. Throws No exception message supplied error. What's wrong in my code, please tell me? email = EmailMultiAlternatives( 'Subject here', 'Here is the message.', 'eliz.moon5@gmail.com', ['elizzz.ekzo@mail.ru']) email.attach('nds.pdf') email.send() -
Is it possible to combine django-allauth with django-graphene?
I'm trying to learn how to create a Facebook login API using Django-allauth but my limited knowledge tells me that the library requires using the Django template engine to authenticate the user by providing the user with the correct {{ form }}. So I'm not sure how to create an API version of this functionality using Django-graphene to login with Facebook on a React or Flutter app. Any advice or links to useful articles will be much appreciated. Unfortunately, I don't have a code example of what I've tried since I'm not sure how to go about it in the first place. -
How to put an IF statement before SetTimeOut? Javascript
I have the following query that checks the starting time of a post in my django App and if the starting time is less than 15 minutes, will remove a class. So i want to put and if statement inside this query to check IF the starting Date Time of one post is >= to 1 hour from now, will return False, otherwise, run the query for that post. so I have the following script: var oneHourFromNow = new Date(); oneHourFromNow.setHours(oneHourFromNow.getHours() + 1); for (let publishReminder of document.querySelectorAll("div.publish-reminder.invisibles")) { setTimeout(function() { publishReminder.classList.remove("invisibles"); }, ((new Date(publishReminder.getAttribute("data-publish-time"))) - (new Date())) - (15 * 60 * 1000)); } Any ideas are comments will be great!! thank you!! -
How to stop audio recording in sounddevice python library if Twilio call ends using Django?
I have tried to record the call (using twilio services) in django using sounddevice library. But after the call ends, the recording does not stop, it continues recording with the duration of sec that I have input. I want to stop the recording when call ends. Please give me any suggestion of this problem. Here is my code. def recording_call(request): fs = 44100 duration = 30 print('recording...') record_voice = sounddevice.rec(int(duration * fs), samplerate=fs, channels=2) sounddevice.wait() write("output2.wav", fs, record_voice) file = "media/audio_call-%s.wav" % 23425 write(file, fs, record_voice) with open(file, 'rb') as f: print(f) return HttpResponse('') -
Is there a way to stop Django from automatically adding "_id" to foreign keys
does anyone know if it's possible to stop Django from adding the "_id" to foreign keys? As an example: i have a table services and recites. Services has as foreign key the recites id (primary key of recites) which i name re_id. I get the classical error: (1054, "Unknown column 'services.re_id_id' in 'field list'") where the second/last "_id" is added automatically and i would like to stop that. I also know that one way to prevent the error is to avoid using "_id" but i wonder if theres a way to use it anyway. THANKS! -
How to add a command line argument with gunicorn in django, to get a input?
If suppose, I have a two database defined in settings.py for example default and dev, I have to access the dev means how can i get the input in command line -
Travic CI is failind with: Temporary failure in name resolution
I trying to add test cases for the django application but the test pass successfully on the locally but it fails on the Travis CI. M .travis.yml files looks like this: dist: bionic services: - postgresql addons: postgresql: '9.5' apt: packages: - postgresql-9.5 before_script: - psql -c 'create database fecundity_test;' -U postgres branches: only: - "master" language: python python: - "3.8" install: - if [ "$TRAVIS_BRANCH" = "master" ]; then pip install -r requirements/dev.txt; fi - if [ "$TRAVIS_BRANCH" = "master" ]; then pip install coveralls; fi script: - if [ "$TRAVIS_BRANCH" = "master" ]; then ./scripts/lib/run-ci; fi after_success: - if [ "$TRAVIS_BRANCH" = "master" ]; then coveralls; fi And my settings.py looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['POSTGRES_DB'], 'USER': os.environ['POSTGRES_USER'], 'PASSWORD': os.environ['POSTGRES_PASSWORD'], 'HOST': os.environ['POSTGRES_HOST'], 'PORT': '', 'ATOMIC_REQUESTS': True, 'TEST': { 'NAME': os.environ['POSTGRES_TEST_DB'] } }, } When I run it on travis is get this error log: $ if [ "$TRAVIS_BRANCH" = "master" ]; then ./scripts/lib/run-ci; fi Using existing test database for alias 'default' ('fecundity_test')... /home/travis/virtualenv/python3.8.1/lib/python3.8/site-packages/django/db/backends/postgresql /base.py:294: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running … -
Django ORM query by related name
I am trying to query all the customer of a particular seller/user This is my sell model class Sell(models.Model): entry_for = models.ForeignKey( User, on_delete=models.CASCADE, related_name='sell_entry_for' ) paid_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='sell_customer', null=True, blank=True ) and this is my query seller_id = '1' user = User.objects.filter( sell_entry_for__id=customer_id ) and return empty but I have many entries for the user Can anyone help me to fix this issue? -
Django models - foreign keys set based on another foreign key
I have three models with the structure as shown below: class Company(models.Model): company_id = models.AutoField(primary_key=True) company_name = models.CharField(max_length=80, unique=True) company_address = models.CharField(max_length=80, unique=True) class Department(models.Model): department_id = models.AutoField(primary_key=True) company = models.ForeignKey(Company, on_delete=models.RESTRICT) department_name = models.CharField(max_length=80, unique=True) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') company = models.ForeignKey(Company, on_delete=models.RESTRICT) department = models.ForeignKey(Department, on_delete=models.RESTRICT) role = models.CharField(max_length=80) What I would like to do is limit the drop-down options for Profile.department based on what is only assigned in the Profile.company, based on Department: | department_id | company | department_name | --------------------------------------------------- | 1 | comp_A | Human Resources | | 2 | comp_A | Accounting | | 3 | comp_A | Legal | | 4 | comp_B | Human Resources | | 5 | comp_B | Accounting | | 6 | comp_B | Legal | | 7 | comp_B | IT | Such that IT department should only be selectable if user works in comp_B Thank you in advance! -
PyCharm Django - Cannot find declaration to go. For CSS file
I have created a simple Django project with one page which included custom css. and noticed that PyCharm can't find a declaration for CSS which located in static folder. See example: I have the following configuration in settings.py: STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ STATIC_DIR ] Please NOTE the file is loading and I can see changes in UI, but PyCharm constantly can't find it So looks like it is some PyCharm configuration problem. Could you please help to solve it? PyCharm version 2019.2 -
Problem in passing dictionary parameter to render template as Argument Django
I am trying to send a list of books objects to my template to display their names and images.Here is my book class class Book(models.Model): title=models.CharField(max_length=100) zonar=models.CharField(max_length=20) book_id=models.IntegerField(default=10) image=models.ImageField() file=models.FileField(upload_to="cars",default="") Here is my django view def books_display(request,zonar): ########### ########### zonar_books=Book.objects.filter(zonar=zonar) books={"zonar":zonar,"zonar_books":zonar_books} return render(request,"books/books_listed.html",books) finally this is my template <<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> {% if zonar %} {{ zonar }} {%endif%} books </title> </head> <body> {% if zonar_books %} {% for book in zonar_books %} <h1>{{ book.tile}}</h1> {% endfor %} {% endif %} </body> </html> And iam getting following error Error during template rendering In template C:\Users\Sriram\Desktop\books_site\books\templates\books\books_listed.html, error at line 12 no such column: books_book.zonar -
How to put array of names in CharField Django
In Models.py class Profile(models.Model): following = models.CharField(max_length=100,null=True, blank=True) user = models.ForeignKey('User',on_delete=models.CASCADE,related_name='user') I want to pass an array of names of following persons in profile model Also I am using sqlite3 database -
Validation/Validation+Creation based on input field in Django Rest Framework
I have my own model, Viewset and Serializer class. My requirement is based on input request's field value i have to perform Validation or Validation+Creation ie if action flag is "Validate", i have to perform validation only and if validations are passed i have to return 204 with no content And if action flag is "Save", I have to perform both Validation and creation. And at the end need to return created entity with status 201. Can any one please help me to implement this in DRF -
how to solve bulk_update() objects must have a primary key set error?
Here from the frontend user gives the input values like this ['1','2', '3']. I want to update the multiple objects at time with bulk_update and I tried like this but this is giving me this error. ValueError: All bulk_update() objects must have a primary key set. class PVariant(models.Model): name = models.CharField(max_length=255) product = models.ForeignKey(Product, on_delete=models.CASCADE) .... #views quantity = request.POST.getlist('quantity_available') #['1','2','3'] names = request.POST.getlist('names') fields = ['name', 'price', 'quantity'..] params = zip(names, quantity, weight,..) variants = [PVariant(display_name=param[0],sku=param[1], quantity=param[2], weight=param[3], product=product) for param in params] PVariant.objects.bulk_update(variants, fields) -
Client-Side Verification Django
I'm new to Django and I made a form that extends UserCreationForm and I want to verify the inputs on the client-side. How can I do that? Thanks in advance class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] -
MIME type Error Django/React project on PythonAnywhere
I've used PythonAnywhere before, but this is the first project that utilizes a Django back end and React front end. What is strange is that if I run this exact project on localhost, there are no troubles at all. It is only when I host this website on PythonAnywhere do I get this error. They're probably hard to see... Refused to apply style from 'http://bluebirdteaching.pythonanywhere.com/static/css/2.8aa5a7f8.chunk.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Looking this up, I've come across this page a lot, but I just can't seem to make sense of the answers provided there. I just don't understand why this works on localhost, but not on PythonAnywhere. I included the above image not just to show my index.html, but also to show the project directory as that seems to be necessary as the other post linked explains. If the answer I'm looking for is in that other post, I just can't make sense of it. Again, everything works as expected when I run the project locally. Of course, thanks guys for any help. I've been going at this problem for a while now; any help/explanations would be a … -
How to show the string value instead of id in Django Templates?
I have here my codes : views.py chem_inventory_solid = models.ChemInventorySolid.objects.values('solidSubstance').order_by('solidSubstance').annotate(total_kgs=Sum('kgs')) template {% for list in chem_inventory_solid %} <tbody> <tr> <td>{{list.solidSubstance }}</td> <td>{{list.total_kgs}}</td> <td> </td> </tr> </tbody> {% endfor %} output Solid Substance | Total Qty 1 1542 2 2000 How to show the solid substance name instead of id ? -
Using django-embed-video in bootstrap carousal
I am working on a django project. In the project, I have a set of youtube videos That I want to display in a carousal. For displaying the videos, I am using django-embed-video. This is my code for displaying the videos in a template {% for i in videos %} {% video i.video 'medium' %} {% endfor %} This works. All of the videos are arranged one after the other in the webpage. Now I want to display them in a carousal. This is the sample code for the carousal <div id="carouselVideoControls" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselVideoControls" data-slide-to="0" class="active"></li> <li data-target="#carouselVideoControls" data-slide-to="1"></li> <li data-target="#carouselVideoControls" data-slide-to="2"></li> </ol> <div class="carousel-inner"> {% for i in videos %} <div class="carousel-item active"> {% video i.video 'medium' %} </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselVideoControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselVideoControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> This is not working. Only the first video is displayed. And when I click the next button nothing happens. Not sure what I am doing wrong here. FYI, The default carousal from bootstrap works. Checked that out with a couple of images. -
Having issues loading django admin static files
Im having issues loading the static files for django admin using the latest django. Now i have tried multiple methods and really would appreciate help. For info im using pythonanywhere for deployment. This is the settings.py file """ Django settings for MyDjangoApp project. Generated by 'django-admin startproject' using Django 2.2.15. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import server_keys as sk # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = sk.django_key # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['192.168.1.22','localhost','username.pythonanywhere.com ','username.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'regs', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'MyDjangoApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['regs/templates/regs'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'MyDjangoApp.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } … -
How to split a form field to display multiple values in Django
My Journey model contains two fields, distance and time: class Journey(models.Model): distance = models.PositiveIntegerField(default=0) time = models.PositiveIntegerField(default=0) I am trying to create a Modelform where the time field will be split to display inputs for 'hrs', 'min' and 'sec'. I would then like these values to be compressed in order to return one single value. Currently my forms.py looks like this: from django import forms from django.forms import MultiWidget from .models import Journey class DistanceTimeModelForm(forms.ModelForm): time = forms.MultiValueField(widget=MultiWidget(widgets=[forms.IntegerField(attrs={'placeholder': 'hrs'}), forms.IntegerField(attrs={'placeholder': 'min'}), forms.IntegerField(attrs={'placeholder': 'sec'})]), require_all_fields=True, error_messages={'incomplete': 'Please enter a number'}) class Meta: model = Journey fields = ['distance', 'time'] I am receiving TypeError: __init__() got an unexpected keyword argument 'attrs' when I attempt to run the server. Is anyone able to help me understand how to fix this? I have been searching for a solution online for some time but so far am still stumped.