Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SQL Windows Function with Group By
I have this MariaDB Query SELECT DAYOFWEEK(date) AS `week_day`, SUM(revenue)/SUM(SUM(revenue)) OVER () AS `rev_share` FROM orders GROUP BY DAYOFWEEK(completed) It will result in a table which show the revenue share. I tried the following by using RawSQL: share = Orders.objects.values(week_day=ExtractIsoWeekDay('date')) \ .annotate(revenue_share=RawSQL('SUM(revenue)/SUM(SUM(revenue)) over ()')) This results in a single value without a group by. The query which is executed: SELECT WEEKDAY(`orders`.`date`) + 1 AS `week_day`, (SUM(revenue)/SUM(SUM(revenue)) over ()) AS `revenue_share` FROM `orders` And also this by using the Window function: share = Orders.objects.values(week_day=ExtractIsoWeekDay('date')) \ .annotate(revenue_share=Sum('revenue')/Window(Sum('revenue'))) Which results into the following query SELECT WEEKDAY(`order`.`date`) + 1 AS `week_day`, (SUM(`order`.`revenue`) / SUM(`order`.`revenue`) OVER ()) AS `rev_share` FROM `order` GROUP BY WEEKDAY(`order`.`date`) + 1 ORDER BY NULL But the data is completely wrong. It looks like the Window is not using the whole table. Thanks for your help in advance. -
ValueError: Number of features of the model must match the input. Model n_features is 25 and input n_features is 76
I am using MLPClassifier to train my model and then will be deploying it in an app/Website.But I am getting this error as the input from user will not be fixed ,using get_dummies is throwing an error.here is my code. Thanks in advance! import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder df = pd.read_csv("nikita_attrition.csv") df_o= pd.read_csv("nikita_attrition.csv") print(df.info()) df=df.drop('StandardHours',axis=1) df_o=df_o.drop('StandardHours',axis=1) features_in = pd.get_dummies(df, columns=['Education','JobSatisfaction', 'WorkLifeBalance', 'EnvironmentSatisfaction', 'StockOptionLevel', 'JobInvolvement', 'PerformanceRating', 'JobLevel'], dummy_na=False) features_out=pd.get_dummies(df_o,columns=['Attrition'],drop_first=True) features_in.shape I am taking input from user via App and coverting it into dataframe and then giving it to my model which is used through pickel file but I am getting the above error. -
Quit Django Celery worker from within task
From within a celery task (ie a Python function) I wish to be able to shutdown the entire celery worker - how can I do this? (Platform us Ubuntu.) -
Django - how to search multiple keywords with "AND" in a list?
Currently I have a list in which there are some keywords. For example: testList = ['apple', 'banana', 'orange'] Now I want to use django Q() to search items which have all the keywords above. Let's say Tom likes apple and orange, but Jerry likes all of these three fruits. When I use this testList, it will return Jerry from the database. Does anyone know how to realize this function? the example model.py is: class FruitInfo(models.Model): Name = models.CharField('Name', max_length=100) Fruits = models.CharField('Favourite fruits', max_length=200) ## here if a person have multiple favourite fruits, the "Fruits" will be "A,B,C" -
null value in column "user_id" violates not-null constraint DRF
I am new to django. I tried to implement registration of several types of users but ran into a problem. I have two models AbstractUser and Participant. Participant is associated with OneToOnefield with AbstractUser, I wrote a serializer for them following the drf documentation, but when sending a post request, an error occurs null value in column "user_id" violates not-null constraint. As far as I understand, the participant model cannot communicate with AbstractUser. What could be the problem Models.py class AbstractUser(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField( _('phone number'), max_length=14, unique=True, help_text='Enter your phone number', ) email = models.EmailField(_('email address'), blank=True) created = models.DateTimeField(_('date joined'), default=timezone.now) class Participant(models.Model): user = models.OneToOneField(AbstractUser, related_name='participants', on_delete=models.CASCADE, primary_key=True) first_name = models.CharField( _('first name'), max_length=50 ) last_name = models.CharField( _('last name'), max_length=50, ) device_reg_token = models.TextField( _('text mobile token'), ) is_participant = models.BooleanField( _('participant status'), default=True ) serializers.py class AbstractUserSerializer(serializers.ModelSerializer): class Meta: model = AbstractUser fields = ('id', 'phone_number', 'email', 'password') class ParticipantSerializer(serializers.ModelSerializer): participants = AbstractUserSerializer() class Meta: model = Participant fields = ('participants', 'first_name', 'last_name', 'device_reg_token') def create(self, validated_data): participants_data = validated_data.pop('participants') participant = Participant.objects.create_participant( **validated_data ) for participant_data in participants_data: AbstractUser.objects.create_user(participant=participant, **participant_data) return participant views.py class CreateUserView(generics.CreateAPIView): queryset = Participant.objects.all() permission_classes = [ permissions.AllowAny ] … -
Dynamically set the 'default' DB in Django Project
I am using Postgres DB and I have two databases that I am using. Consider this example as I have to make two version of the software. In one version there is the main DB used for real data and second DB for test version of the software for trainee person. Now how do I change the default DB according to the logged in User. P.S: I know I can use 'using(db_name)'. But I don't want that. I want to change the default DB in settings.py dynamically. The puspose is to provide a test version to the client with a seperate DB. -
How to dynamicaly rename and query a field with Django?
I'm trying to queryset a character field symbol in which values contain a / like in A/B. My problem is that the string AB I would like to query doesn't contains the / and I can't add it because / may be placed at different positions in the string. How can I query AB on the fly when field value is A/B? class Market(models.Model): symbol = models.CharField(max_length=50, null=True, blank=True) What I would like is a dynamic field with the renamed string in it. Something like this but Django complains that the F() object has no attribute 'replace'. Market.objects.annotate(symbol_renamed=F('symbol').replace('/', '')).get(symbol_renamed='AB') -
django modelform: only last form gets into db table
I am building a modelform to let the user enter several rows at once in the db table. I managed to get it all up and running but there is one issue. Only one row gets saved in the database table. here is what my view looks like: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount'), extra=10) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) elif request.method == 'POST': formset = form(request.POST) if formset.is_valid(): formset.save() for check_form in formset: quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) return redirect('/dash2.html') #else: #form = form(queryset= historical_recent_data.objects.none()) return render(request, 'new_sale.html', {'formset':formset}) and here is what my code look like: <form method="POST" class="form-validate"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle row1 row2 %}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ … -
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