Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing the file path from object created via mutagen.File() python django
I'm using django and filefields to upload a file to s3. I need to get the local path of the file in the the pre_save signal. Currently I am doing the following: def pre_save(sender, instance, **kwargs): mutagen_file = mutagen.File(instance.audio) Where instance is the model and audio is the FileField property. I think I found a work around via: instance.audio._file.temporary_file_path() but that should fail with files under 2.5MB and the mutagen variant wouldn't (if I could get the path from the mutagen_file object. -
DRF and Knox showing logged in user as anonymous (Django)
as I created an API with DRF and Knox and I am using token based authentication. Everything is working except the system is showing the logged in user as anonymous. I tried all this: current_user = request.user print(current_user.is_anonymous) # True print(current_user.is_authenticated) # False print(current_user.is_staff) # False print(current_user.is_superuser) # false print(current_user.is_active) # false u = User() print(u.id) # None I need the user id of the logged in user because I am using that as a foreign key in the other table. I checked the auth_user table and it has all the columns. Is there any way to get the user id or convert the anonymous user to authenticated user ? Thanks AJ -
Filter users by roles during serialization
I have a User model with 3 roles Teacher, Student, Admin as the choices. I wanted to have only users whose role is Teacher in TeacherSerializer. So, like this for Students and Admins. When I creating a Batch wise course I have to assign a Tutor(Teacher) in the API URL under tutor I wanted to show the users who are teachers. Who aren't teachers should not be included in that list -
Daphne server halts after executing a very long process in a Django Channels-based architecture
I am building a system for processing data and then train ML models using sklearn's builtins. I used digital ocean for deployment with Ubuntu, Nginx, Gunicorn, Daphne, Django, and Channels. All features work fine until it is required to train larger datasets through channels (sockets) asgi connection. When the execution starts, it takes few moments until the server (asgi) stops responding and all other WebSockets stop working, HTTP ones are fine though. I have followed the following tutorial for deployment: CodingWithMitch Channels Deployment, when I restart the server again with these commands, everything starts working fine except the training part (the long process): sudo systemctl daemon-reload sudo systemctl restart gunicorn sudo systemctl restart nginx sudo systemctl restart redis.service service daphne restart Restarting Daphne was the critical one I noticed. The confusing part is, the server logs show no error whatsoever. It seems to be an issue with the websockets keepalive timeout as my initial guess, but even after I increase the timeout in my nginx.conf file it and restart, it doesn't change the behavior: /etc/nginx/sites-availabel server { server_name 159.203.13.90; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django/EasyAI; } location / { include proxy_params; proxy_pass … -
TypeError: list indices must be integers or slices, not str . while working with json
I am making a simple weather app using API. I got the error: list indices must be integers or slices, not str. I know where the problem is but I don't know how to solve it. my code is: `from django.shortcuts import render import urllib.request import json Create your views here. def index(request): if request.method == 'POST': city = request.POST['city'] source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=5ba7df1f751428007642bf4e5f6c4c9a').read() list_of_data = json.loads(source) data = { "country_code": str(list_of_data['sys']['country']), "coordinate" : str(list_of_data['coord']['lon']) + ' ' + str(list_of_data['coord']['lat']), "temp" : str(list_of_data['main']['temp']) + 'k', "pressure": str(list_of_data['main']['pressure']), "humidity": str(list_of_data['main']['humidity']), "weather" : str(list_of_data['weather']['description']), } print(data) else: data = {} return render(request, 'main/index.html', data)` The problem is in the last line of the data dictionary. I don't know how to write it. Please help me with this. -
Is there will be any issue on django if I try to add a user to a group in which he/she already in
I am adding a user who is done some donation in the app to a group. My code is below: donation_event_group.user_set.add(customer_obj) My question is will there be any issue behind the scenes, if I try to add the user again, Like when the user try to donate more than once my code for adding him to the group will still execute. I don't have any errors in console so far, so I think there is no problem at all. Will there will be any problem? Or do I need to a strict checking and add only if the user is not in the group? -
Django Error: Field 'id' expected a number but got 'list'
I have an app with 2 models and I'm trying to create a List View and a Detail View. The list view worked fine, but when I created the detail view the list view stopped working and it's prompting me with this error: "Field 'id' expected a number but got 'list'. Models.py from django.db import models # Create your models here. class schools(models.Model): name=models.CharField(max_length=256) principal=models.CharField(max_length=256) def __str__(self): return self.name class students(models.Model): name=models.CharField(max_length=256) age=models.PositiveIntegerField() school=models.ForeignKey(schools,related_name='students',on_delete=models.CASCADE) views.py from django.shortcuts import render from django.views.generic import DetailView,ListView,CreateView,FormView,UpdateView from basicapp import models,forms from django.http import HttpResponseRedirect, HttpResponse # Create your views here. class SchoolListView(ListView): model = models.schools class SchoolDetailView(DetailView): context_object_name='schools_detail' model=models.schools template_name='basicapp/schools_detail.html' urls.py from django.contrib import admin from django.urls import path,re_path from basicapp import views urlpatterns=[ re_path(r'^(?P<pk>[-\w]+)/$',views.SchoolDetailView.as_view(),name="detail"), path('list',views.SchoolListView.as_view(),name="list"), path('create',views.cview.as_view(),name="create"), path('index',views.index,name='index'), ] and my templates: {% extends 'basicapp/base.html' %} {% block body_block %} <h1>Welcome to the List of Schools Page!</h1> <ol> {% for school in schools_list %} <h2> <li><a href="{{school.id}}"></a>{{school.name}}</li> </h2> {% endfor %} </ol> {% endblock %} {% extends 'basicapp/base.html' %} {% block body_block %} <div class="jumbotron"> <h1>School Detail Page</h1> <h2>School Details:</h2> <p>{{ schools_detail.name }}</p> <p>{{ schools_detail.principal }}</p> <h3>Students:</h3> {% for student in school_detail.students.all %} <p>{{ student.name }} who is {{ student.age }} years old.</p> … -
Using html input type month to show the value of year and month in Django
I have an input type month where I ask a user to type the start_month and start_year for a job. However, the field month is optional. Like a user can only specify the start year. In my model, I store start_month as a CharField with values like 'January', 'February'. I store start_year as an IntegerField. I already have the values stored and I have even successfully retrieved them such that they show up in the template if i do {{ job.start_month }} The issue is how do I display that by the value attribute in the input type month provided that a user can have only year and month or year? Thank you for your help guys Note: I am not comfortable with Django forms :/ Here is my code snippet: <div class="form-group col-md-6"> <label for="start">From:</label> <input style="margin-left: 5px;" type="month" id="start" value="{% if job.start_month %}{{ }}{% endif %}" name="start"> <p style="color: red;">Month is optional</> </div> -
connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream - Trying to upload django app to digitalocean
I am trying to upload my django project to digitalocean droplet. Followed this article https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 to upload it. After completing all the steps I am getting 502 bad gateway. Also the server is not running on SSL rather it is running on http//. I followed every steps the article provided. Somehow there is an error called "connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream" /etc/systemd/system/gunicorn.socket ----- [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service ---- [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/myproject ----- server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I ran this commands but getting no error sudo nginx -t && sudo systemctl restart nginx So I need help on this. -
Separating User Settings on to different views in Django
I was wondering if anyone could provide me when any references or guidance on achieving the following outcome: On my User Settings view currently, I am displaying the Username, Email and Profile Avatar fields belonging to a specific user. However as I begin to add more settings, it would be quite a nice touch if I could somehow separate these settings in to categories of their own to make it more clearer for users to navigate amongst the settings they wish to update. For example, on the Facebook app when you tap on to Settings, they feature a list of clickable setting categories e.g. General Information, Privacy & Security, Language and so forth. I think categories is perhaps the wrong term to use, I'm guessing "Setting Groups" would be a better way to describe the outcome of which I'm hoping to achieve. If anyone knows of any guidance, tips or references to achieving this outcome, that would be super helpful! Thanks, Jay. -
How to select distinct column A, then aggregate values of of column B in DJANGO?
I try to create a crypto portfolio webpage. My problem is the following. Current Transactions table when i render the html: Crypto_Name Total Trade Value BTC 150 BTC 100 DOGE 200 DOGE 210 Desired Transaction table: Crypto_Name Total Trade Value BTC 250 DOGE 410 I would like to select distinct values of Crypto_Name and then summarize the values in Total Trade Value. models.py: class Transaction(models.Model): """Model representing a trade.""" portfolio = models.ForeignKey('Portfolio',on_delete=models.CASCADE) coin = models.ForeignKey(Coin,on_delete=models.CASCADE) number_of_coins = models.DecimalField(max_digits=10, decimal_places=0) trade_price = models.DecimalField(max_digits=10, decimal_places=2) date = models.DateField() def __str__(self): return str(self.portfolio) @property def total_trade_value(self): return self.trade_price * self.number_of_coins views.py query: def my_portfolio(request): filtered_transaction_query_by_user = Transaction.objects.filter(portfolio__user=request.user) ... What I have tried among many things: test = filtered_transaction_query_by_user.order_by().values('coin__name').distinct() It gives me just two crypto name in an ugly format {'coin__name': 'Bitcoin'} {'coin__name': 'Doge'} but the other columns are empty when I render them in the html. I appreciate your help!!! :) -
How can I use django-bootstrap-icon inside JQuery insert function?
I'd like to insert bootstrap buttons into a table data element. What I've been doing until now, is something like: $("<td>").insert("{% bs_icon 'pencil-square' %}"); // or $("<td>").insert("{% bs_icon 'pencil-square' %}".toString()); // or similar things All I could achieve is > Uncaught SyntaxError: Invalid or unexpected token Is there any way I could make it work by scaping the svg tag generated by django-boos -
Run HtmlTestRunner Selenium UnitTests in Django GitLab Repository
I have a Django Project on a GitLab repository. I've created a Test Suite using Selenium, UnitTest and HtmlTestRunner in Python. I want to automatically run the tests when pushing in GitLab. I read something about GitLab CI, but I'm not sure how this can be made. -
how do I return an actually image instead of the array returned by sentinelhub py satelite data
I am trying to write an api endpoint using the sentinelhub py service using the process api module...that gets the NDVI index of place passed in by a geometry and returns its image now when I write this api everything works perfectly fine just that what I get is an array when testing with post man. response = request.get_data() returns an array and I can"t seem to get how to return the actually image using python class vegetativeIndexView(APIView): def get(self, request): #Credentials CLIENT_ID = 'client_id' CLIENT_SECRET = 'secrete' config = SHConfig() if CLIENT_ID and CLIENT_SECRET: config.sh_client_id = CLIENT_ID config.sh_client_secret = CLIENT_SECRET else: config = None evalscript = """ //VERSION=3 function setup() { return { input: [{ bands:["B04", "B08"], }], output: { id: "default", bands: 3, } }; } function evaluatePixel(sample) { let ndvi = (sample.B08 - sample.B04) / (sample.B08 + sample.B04) if (ndvi<-0.5) return [0.05,0.05,0.05] else if (ndvi<-0.2) return [0.75,0.75,0.75] else if (ndvi<-0.1) return [0.86,0.86,0.86] else if (ndvi<0) return [0.92,0.92,0.92] else if (ndvi<0.025) return [1,0.98,0.8] else if (ndvi<0.05) return [0.93,0.91,0.71] else if (ndvi<0.075) return [0.87,0.85,0.61] else if (ndvi<0.1) return [0.8,0.78,0.51] else if (ndvi<0.125) return [0.74,0.72,0.42] else if (ndvi<0.15) return [0.69,0.76,0.38] else if (ndvi<0.175) return [0.64,0.8,0.35] else if (ndvi<0.2) return [0.57,0.75,0.32] … -
Django send mail with slightly different templates
I am sending mail with django and I would like to send lots of mails at the same time to different users. I am aware that the recieverparameter takes a list with multiple users, but all of my email will have some small changes in the html-template which limits me to have only one messageobject per user. As for now I am just looping but is there a faster way? -
Why is my image field not getting updated in django?
Basically , in my django website , a user can register and make his profile . Now if he wants to change some data after creation of his profile , he can do it through the settings page . Now , one of the things that he can edit is his profile picture Here is the model of the user profile in question: class Vendor(models.Model): name = models.CharField(max_length=255) phone = models.CharField(blank=True, null=True, max_length=20) email = models.EmailField(blank=True, null=True) city = models.CharField(blank=True, null=True, max_length=40) state = models.CharField(blank=True, null=True, max_length=40) address = models.CharField(blank=True, null=True, max_length=200) pincode = models.IntegerField(blank=True, null=True) image1 = models.ImageField(upload_to='shop_images/', blank=True, null=True) latitude = models.DecimalField(max_digits=24, decimal_places=18, blank=True, null=True) longitude = models.DecimalField(max_digits=24, decimal_places=18, blank=True, null=True) created_by = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['name'] def __str__(self): return self.name def get_balance(self): items = self.items.filter(vendor_paid=False, order__vendors__in=[self.id]) return sum((item.product.price * item.quantity) for item in items) def get_paid_amount(self): items = self.items.filter(vendor_paid=True, order__vendors__in=[self.id]) return sum((item.product.price * item.quantity) for item in items) This is the view that I created for updating the model @login_required def vendor_settings(request): vendor = request.user.vendor if request.method == 'POST': name = request.POST.get('name') phone = request.POST.get('phone') email = request.POST.get('email') city = request.POST.get('city') state = request.POST.get('state') address = request.POST.get('address') pincode = request.POST.get('pincode') … -
Django how to avoid rounding decimals in ArrayField?
I'm trying to save decimals in ArrayField, using Django and Django REST Framework, but somehow when I save my model instance with my array of decimals set, django rounds it and saves only integers without precision. I have a following PostgreSQL field in model: losses = ArrayField( models.DecimalField( max_digits=7, decimal_places=2, ), blank=True, ) I pass values by REST API in the following way: { "losses": [ 9.93, 5 ], } Here is validated array of decimals in DRF serializer: [Decimal('9.93'), Decimal('5.00')] My current result is: [10, 5] Expected result is: [9.93, 5] Does anyone know why django round my DecimalField in array, despite of I have decimal_places=2 in model field? Thanks! P.S. Changing losses array in Django Admin with decimals also rounds my decimals, so it's not a problem of DRF. -
How to run Django and hardware code together on raspberry pi
I'm new to raspberry pi and Django. I'm creating an application that has a webpage (on Django) and some relays. Django is working fine. It serving the page as http server and I have another small code in another py file. I dont know how to make these things work together. Django has manage.py file. Should I write my relay code into manage.py or should I have to create another py file. Thanks in Advance -
How to pass and display value from a model on a template from another app upon login in views.py
views.py models.py template of another app where it is redirected after logging in -
Optimize Video Delivery(media files) in Django
I am using Amazon S3 for storing and serving Static Files and Media Files. For delivering optimized images I am using sorl-thumbnail. I want to know how to deliver optimized video to users so that page load speed increases and at the same time users are delivered optimized video. My main aim is to load the video as fast as possible and to achieve optimized delivery by any methods available for Django web application, like the best methods and practices. -
Problem with inlines formset using django-extra-views
I'm Having 3 models in my django app: Car, Driver and Access. Each Car has a unique Acces and each Driver has a unique Car. I would like to create objects from all of these models at the same time in the same view using django-extra-views inline formset. This is what i've done so far. models.py class Car(models.Model): # Some fields access = models.OneToOneField(Access, on_delete=models.CASCADE, default="", related_name="Car") Class Driver(models.Model): # Some fields car = models.OneToOneField(Car, on_delete=models.CASCADE, related_name="Driver") Class Access(models.Model): # Some fields views.py class DriverInline(InlineFormSetFactory): model = Driver form_class = DriverForm factory_kwargs = {'can_delete': False} class CarInline(InlineFormSetFactory, CreateWithInlinesView): model = Car inlines = [DriverInline] form_class = CarForm factory_kwargs = {'can_delete': False} class CreateAccess(CreateWithInlinesView): model = Acces inlines = [CarInline] form_class = AccessForm template_name = "create.html" success_url = reverse_lazy('access:list') create.html <form method="post"> ... {{ form }} {% for formset in inlines %} {{ formset }} {% endfor %} ... <input type="submit" value="Submit" /> </form> I was expecting to get the Driver inline formset in the inlines and therefore be able to create a Driver as well an his Car and the Access of his Car. -
i ran "Django manage.py runserver" and i get a "NodeNotFoundError"
newbie to python so i followed "Django by example" after i finished the blog project i committed to GitHub repository master. Only for me to clone the project later and -
Django PostgreSQL - the password isn't saved to the database
I have a custom User model and a function in views.py to handle the registration. when I register a user with Postman for example all the user data is stored in the database correctly but the password -field remains empty. I think that causes the problem when I try to use a simple login -page - it never accepts my credentials (because there is no password in the database). Any ideas why the password isn't saved and how to fix it? I have a function like this in views.py when registering a new user: def register(response): if response.method == 'POST': form = RegisterForm(response.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.id = form.cleaned_data.get('id') user.save() username = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(username=email, password=password) return HttpResponse(status=201) else: form = RegisterForm() return HttpResponse(status=400) And this is my custom user model: class UserManager(BaseUserManager): def create_user(self, email, password): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('A user must have a email.') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user -
Is there a way to put an interactive globe on your Django website?
I was looking at the home page of github, and saw that they had updated it with an interactive globe. I did some research, and I was able to find out a little about the globe. I was unable to find a definet answer, but I know that this is a WebGL globe that was probably taken from a three.js library. Does anyone know of any way that I could put this globe in my HTML file on my website? Thank you to everyone who helps! -
Getting continuous data stream on server side in django
I am pretty new to django. I want to run an everlasting task on server side to get continuous data using websocket and store it in database. What will be the best approach to do this ? Best regards,