Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset to get max score of individual ids using annotate
I have the followin model named sitting Class Sitting(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_("User"), on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, verbose_name=_("Quiz"), on_delete=models.CASCADE) current_score = models.IntegerField(verbose_name=_("Current Score")) complete = models.BooleanField(default=False, blank=False, verbose_name=_("Complete")) end = models.DateTimeField(null=True, blank=True, verbose_name=_("End")) class Question(models.Model): quiz = models.ManyToManyField(Quiz, verbose_name=_("Quiz"), blank=True) category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True, on_delete=models.CASCADE) questionmarks = models.PositiveIntegerField( blank=True, null=True, verbose_name=_("Question Marks"), help_text=_("Marks of each question. Beginner-1,Intermediate-2,Advanced-3,Expert-4")) I am trying to create a leaderboard where for a particular period which show all 10 toppers for that week/month. To determine score in % I use the following method. def get_max_score(self): questionmarks= Question.objects.filter(id__in=self._question_ids()).aggregate(Sum('questionmarks')) #return len(self._question_ids()) print(questionmarks) return questionmarks['questionmarks__sum'] def get_percent_correct(self): dividend = float(self.current_score) divisor = self.get_max_score if divisor < 1: return 0 # prevent divide by zero error if dividend > divisor: return 100 correct = float((dividend / divisor) * 100) if correct >= 1: return correct else: return 0 I wanted to get the top 10 users with max % score combined across all quizzes. I tried using code below but unable to determine % score using queryset. sitting = Sitting.objects.filter(complete=True).annotate(total=Count('id')).values('user__username','current_score').order_by('user__username')[:10] Any help is appreciated. -
django ...Could not parse the remainder: ''css/materialize.min.css’' from ''css/materialize.min.css’'
I do follow a tutorial where is add a chat bot ui...the ui is embedded in django.. the structure looks the following... . ├── db.sqlite3 ├── installDjango.sh ├── manage.py ├── rasadjango │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── static │ ├── urls.py │ └── wsgi.py ├── rasaweb │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py └── venv ├── bin ├── lib └── pyvenv.cfg static folder . ├── css │ ├── materialize.min.css │ └── style.css ├── img │ ├── banner.png │ ├── body.png │ ├── botAvatar_old.png └── js ├── chart.min.js ├── jquery.min.js ├── materialize.min.js └── script.js in the rasadjango/settings.py PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') when run ... python manage.py runserver i get an error Could not parse the remainder: ''css/materialize.min.css’' from ''css/materialize.min.css’' part of my index.html file...on top i do load the static.... {% load static %} .... <link rel= “stylesheet” type= “text/css” href= ”{% static 'css/materialize.min.css’ %}”> ... What is wrong... -
Django - Run collectstatic to collect static files but collect all the files in the project directory instead
I am trying to run collectstatic command to collect all of the my static files from the subdirectories of apps and deployed them to my Amazon S3 buckets. I tried to use Zappa following the steps as found in this link: https://romandc.com/zappa-django-guide/walk_static/ After running the command python /manage.py collectstatic, all of the files in my project directory get copied into the static folder. Plus, it is not deployed into the S3 bucket. Here is my code: STATIC_URL = '/static/' STATICFILES_DIRS = [ # os.path.join(BASE_DIR, "/static"), ] if os.environ.get("collectstatic")=='True': # STATICFILES_DIRS += 'static', STATIC_ROOT = os.path.join(BASE_DIR, 'test') #STATIC FILE SETTNGS FOR S3 #Used when we seperate css and js into a static folder DEFAULT_FILE_STORAGE = "django_s3_storage.storage.S3Storage" if os.environ.get('stage'): STATICFILES_STORAGE = "django_s3_storage.storage.StaticS3Storage" AWS_S3_BUCKET_NAME_STATIC = 'static-myapp-'+ os.environ.get('stage') # These next two lines will serve the static files directly from the s3 bucket AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_S3_BUCKET_NAME_STATIC STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN else: STATICFILES_DIRS+=BASE_DIR, # AWS BUCKET FOR UPLOADED FILES AWS_S3_UPLOAD_BUCKET = "myapp-uploads" Can anyone point out what I did wrong please? Thank you! -
Instantiating Django's User Model
I have seen the different ways of creating an instance of Django's User Model. Which follows best practices in Django development 1. from django.config import settings class Item(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) 2. from django.contrib.auth.models import User class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) -
How can I fix error "'NoneType' object has no attribute 'day'" in django website
I noticed this error in my application, "'NoneType' object has no attribute 'day'". What I have noticed about it is that. I have a model named course_schedule, the course schedule has an option of Monday to Sunday. If the course schedule is partially populated, that is I populate only some days, like 3 days out of the complete 7 days in a week, I get the error but whenever I populate the course schedule populate course schedule model completely, I don't have the error and everything works well. error log: Traceback (most recent call last): File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\sms\schoolapp\views.py", line 1609, in student_course_list get_all = getall(2021, sch.day) Exception Type: AttributeError at /en/student_course_list Exception Value: 'NoneType' object has no attribute 'day' models.py class course_schedule(models.Model): days_choices = ( ("Mon", 'Monday'), ("Tue", 'Tuesday'), ('Wed', "Wednessday"), ('Thurs', "Thursday"), ('Fri', "Friday"), ('Sat', "Saturday"), ("Sun", "Sunday"), ) day = models.CharField(max_length=60, default="Sun") time_session = models.CharField(max_length=150, default='8:00am') end_session = models.CharField(max_length=150, default='10:00am') def __str__(self): return self.day views.py def getall(year, day): dates = { "Sun": 6, "Mon": 0, "Tue": 1, "Wed": 2, "Thurs": 3, "Fri": 4, "Sat": 5 } d = date(year, … -
setting up search ui ("search experience") for django and elasticsearch
I have a django "back-end" app aiming to provide search & filtering view for an elasticsearch index (currently set-up locally; planned to be deployed on AWS Elasticsearch Service). I am researching how to provide a front-end for the search/filtering functionality with some sort of "boilerplate" package, and I came across the following two potential candidates: https://www.elastic.co/enterprise-search/search-ui https://searchkit.co/ However, I am struggling with this, as to me it feels both are a bit of an "overkill" i.e. they require set-up/installation of number of dependencies, running additional services on additional ports, setting up a proxy... etc. I would expect django to be able to handle most of it. What am I missing here? And is there a more straightforward solution? -
Use annotations on Pytnon 3.6.5
I'm working on a project where I was asked to code some validations using Chain of Responsibility. I am currently using python 3.9.2 on my machine, but the project on docker is on 3.6.5 This piece of code works nice on my machine, but it breaks on Docker: from __future__ import annotations from abc import ABC, abstractmethod from typing import Any, Optional class Handler(ABC): """ The Handler interface declares a method for building the chain of handlers. It also declares a method for executing a request. """ @abstractmethod def set_next(self, handler: Handler) -> Handler: pass @abstractmethod def handle(self, request) -> Optional[str]: pass The error that shows is the following: from __future__ import annotations django_1 | ^ django_1 | SyntaxError: future feature annotations is not defined Is there a way to make the code work on python 3.6.5? -
Working with sqlite django database in python
Im doing a web scraping django project which in short will be a site with pc components like gpus and cpus and it will work as a price monitoring site, tracking all daily price changes etc. Right now Im starting to write a code for the scraper itself which will be just checking and updating prices. My question is what would be the most efficient way to access the product sqlite database in order to get all links that will be redirected to bs4 scraping function which will check all prices. Should I just directly parse through fetched links through basic SELECT query like this (code below) or should I first save these links to other file and then open it with my scraper or is there other "recommended" way. I have 0 experience with working with databases via python and would appreciate all the suggestions. conn = sqlite3.connect('db.sqlite3') c = conn.cursor() c.execute("SELECT link FROM core_product") c.fetchall() #code for scraping would be here, for exapmle: def get_prices(link): #do webscraping for a single product for link in c.fetchall(): get_prices(link) -
Reverse URL resolution for Spring Boot GetMapping
I am currently writing a Spring Boot REST API and wanted to do a reverse resolution of a URL that is defined in a GetMapping. In the Django web framework there is a method for doing that: reverse. But I was not able to find anything like that for Spring Boot. I am looking for something like this: package help.me.stack.overflow; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("api") public class SomeController { @GetMapping(value = "/items/{filter}/blob") public ResponseEntity<?> getItems(@PathVariable String filter, @RequestParam String sorting) { return ResponseEntity.ok().body("here you go"); } @GetMapping(value = "/give-me-url") public ResponseEntity<?> getTheUrl() { return resolveUrl(SomeController.getItems, "foo-filter", "foo-sorting"); // should produce "api/items/foo-filter/blob?sorting=foo-sorting" } } Does something like that exist? How can I use it? -
How to filter by the last element of a json array field in Django
I have a model MyModel with a JSONField called data. This json field contains an array of objects like: [ { "date": "2021-01-01", "amount": 120 }, { "date": "2021-01-02", "amount": 150 } ] I would like to filter by the amount of the last element of the array. From the Django documentation, I understand that I can filter by the first element using: MyModel.objects.filter(data__0__amount__gte=100) How could I do this using the last element? -
I have an error in django views.py file, httpresponse
This is my views.py file from django.shortcuts import render, HttpResponse Create your views here. def Index(request): return HttpResponse("Danial") This is my urls.py file from django.shortcuts import render, HttpResponse Create your views here. def Index(request): return HttpResponse("Danial") -
Django filtered relation not adding condition to query
I have two models: class Album(models.Model): title = models.TextField() class Track(models.Model): name = models.CharField(max_length=50) album = models.ForeignKey('Album', on_delete=models.CASCADE) When build query I would like to achieve left outer join with extra condition. I'm using qs = Album.objects.filter(ljoin=FilteredRelation( 'tracks', condition=Q(tracks__name='demo') ) ) When printing print(qs.query) the join condition is made only on id columns. How to achieve that extra condition like track.name = 'demo' is included in join query? -
Serializes ManyToMany relations in Django Rest Framework
I want to serializing ManyToMany fields. So, in the response for tje Application model should also the band and the band description listed. But I've got the following error message: Got AttributeError when attempting to get a value for field bands on serializer OsdSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Application instance. Original exception text was: 'Application' object has no attribute 'bands'. Anyone who knows why it doesnt work? models.py class Band(models.Model): band = models.CharField(max_length=3) description = models.CharField(max_length=255) in_satellite = models.ForeignKey('Satellite', on_delete=models.PROTECT, blank=True, null=True) wavelength = models.DecimalField(max_digits=4, decimal_places=0, default='0', help_text='Central wavelength (nm)') resolution = models.DecimalField(max_digits=4, decimal_places=0, default='0', help_text='Spatial resolution (m)') def __str__(self): return '%s | %s' % (self.in_satellite, self.band) serializers.py class BandSerializer(serializers.ModelSerializer): class Meta: model = Band fields = ['band', 'description', ] class OsdSerializer(serializers.ModelSerializer): bands = BandSerializer() class Meta: model = Application fields = ['name', 'description', 'bands',] views.py class OsdView(APIView): def get(self, request): applications = Application.objects.all() serializer = OsdSerializer(applications, many=True) return Response({"Your open space data:": serializer.data}) -
Django-tables2 - how can I get counts out in my table on a custom table field?
I'm trying to get some frequency data out from my queryset in a column in my table in django-tables2. I am trying this via a custom field: class MyTable(tables.Table): custom_field = tables.Column(empty_values=()) def render_custom_field(self): total_queryset = self.data.data # trying to get out the row object, to do a filter query something like: row_object = self.rows.instance freq = total_queryset.filter(myfield=row_object.myfield) return f"{len(freq)}/{len(total_queryset)}" However I cannot get the row instance out to do this query. Does anyone know how I can get the row instance out to do this? (I'm also aware getting the total_queryset from self.data.data is probably a hacky way of doing this...) Thanks! -
Django namespace issue: django.urls.exceptions.NoReverseMatch: 'admin' is not a registered namespace
I've implemented user authentication using the urlpatterns in django.contrib.auth.urls. All the URLs work fine, except logging out. When attempting to logout what I get is this error: NoReverseMatch at /accounts/logout/ 'admin' is not a registered namespace I've tried setting a web_app namespace but then that leads to a new set of problems. Would this still be a better approach, or is there a simple fix to my issue? -
Django: Integrity error not null for ForeignKey id field
I have a model which contains ForeignKeys to a number of other models and find, for some reason, I am able to save one of these models absolutely fine, but another I receive a fault message saying: IntegrityError: NOT NULL constraint failed: app_eofsr.flight_id See below for my models.py: # models.py class Aircraft(models.Model): esn = models.IntegerField() acid = models.CharField(max_length=8) engpos = models.IntegerField() operator = models.CharField(max_length=5, default='---') fleet = models.ForeignKey(Fleet, blank=True) slug = models.SlugField(default=None, editable=False, max_length=50, unique=True) class EoFSR(models.Model): datetime_eofsr = models.DateTimeField(default=None) flight_number = models.CharField(max_length=10) city_from = models.CharField(max_length=4) city_to = models.CharField(max_length=4) and these both feed into this model: # models.py class Flight(models.Model): flight_number = models.CharField(max_length=10) city_from = models.CharField(max_length=4, default=None) city_to = models.CharField(max_length=4, default=None) datetime_start = models.DateTimeField(default=None) aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) eofsr = models.ForeignKey(EoFSR, on_delete=models.CASCADE) The odd thing being, I can save an Aircraft record no problem at all, but cannot save an EoFSR record and receive the NOT NULL constraint error message. I've done the usual deleting of the migrations and even tried deleting the db.sqlite3, but still no luck! Any suggestions? -
i have a django channels backend and i need a react redux typescript frontend to connect with that
from channels.generic.websocket import WebsocketConsumer from channels.db import database_sync_to_async import json from channels.consumer import AsyncConsumer from chat.models import Thread, Chat from chat.serializers import ThreadSerializer, ChatSerializer from network.models import Connection class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): self.sender = self.scope['url_route']['kwargs']['sender_id'] self.receiver = self.scope['url_route']['kwargs']['receiver_id'] self.thread_id = await self.get_thread(self.sender, self.receiver) self.chat_room = f'thread_{self.thread_id}' chat = await self.get_chat(self.thread_id) await self.channel_layer.group_add( self.chat_room, self.channel_name ) await self.send({ 'type': 'websocket.accept', }) await self.send({ 'type': 'websocket.send', 'text': chat }) async def websocket_receive(self, event): try: data = json.loads(event.get('text'))['text'] if data: recent_message = await self.create_chat(self.sender, self.thread_id, data) await self.channel_layer.group_send( self.chat_room, { 'type': 'send_recent_message', 'text': recent_message } ) else: await self.send({ 'type': 'websocket.send', 'text': 'No text containing message found.' }) except: await self.send({ 'type': 'websocket.send', 'text': 'Error, kindly send data in right format.' }) async def websocket_disconnect(self, event): print('Disconnected :-<', event) @database_sync_to_async def get_chat(self, thread_id): chat = Thread.objects.get(id = thread_id).messages serializer = ChatSerializer(chat, many = True, context = {'sender' : self.sender}) return json.dumps({"messages" : serializer.data}) @database_sync_to_async def create_chat(self, sender_id, thread_id, text): serializer = ChatSerializer(data = {'sender' : sender_id, 'thread' : thread_id, 'text' : text}, context = {'sender' : self.sender}) if serializer.is_valid(): serializer.save() # return json.dumps({"messsage" : serializer.data}) return json.dumps(serializer.data) # return text return serializer.errors @database_sync_to_async def get_thread(self, sender_id, receiver_id): thread = Thread.objects.filter(first_member_id = … -
Uncaught TypeError: dataFn.call is not a function in VueJS 3
I am trying to resolve the following error:- Uncaught TypeError: dataFn.call is not a function at resolveData (vue.global.js:7141) at applyOptions (vue.global.js:6947) at finishComponentSetup (vue.global.js:7718) at setupStatefulComponent (vue.global.js:7649) at setupComponent (vue.global.js:7589) at mountComponent (vue.global.js:5311) at processComponent (vue.global.js:5287) at patch (vue.global.js:4915) at render (vue.global.js:5988) at mount (vue.global.js:4253) I am using VueJS version 3 and I am not sure what is wrong with my following code:- const FormApp = { delimiters: ['[[', ']]'], data: { username: null, password: null, success_msg: "", err_msg: "ERROR", FILE: null, }, methods: { onFileUpload (event) { this.FILE = event.target.files[0] }, submitForm: function(){ this.success_msg = "" this.err_msg = "" const formData = new FormData() // formData.append('avatar', this.FILE, this.FILE.name) formData.append('username', this.username) formData.append('password', this.password) axios({ method : "POST", url:"{% url 'submitform' %}", //django path name headers: {'X-CSRFTOKEN': '{{ csrf_token }}', 'Content-Type': 'application/json'}, data : formData, }).then(response => { this.success_msg = response.data['msg']; }).catch(err => { this.err_msg = err.response.data['err']; }); }, }, }; Vue.createApp(FormApp).mount('#counter') and my HTML looks like below:- <div class="panel-body" id="app"> <div id="counter"> Counter: [[err_msg]] </div> </div> Can anyone explain me what's wrong in my code? -
Gunicorn taking up 100% on 72 core cpu (Django + Nginx)
I have a Django app with Nginx , gunicorn and postgresql as database. I have a aws server c5.18xlarge (72 cores and 137 gb ram). The problem is it gets slow with only 50 concurrent users. Using htop I found out that most of the cpu usage and ram is used by gunicorn workers and postgreql workers. Here is the htop screenshot: In the screenshot the usage is lower (38% load and around 100 gb of ram used ) because users are less. But as soon as there are 50 + concurrent users the usage goes to 100% in both cpu and ram. Here is the gunicorn worker settings: NAME="django_app" # Name of the application DJANGODIR=/home/ubuntu/bodhiai # Django project directory SOCKFILE=/home/ubuntu/env/run/gunicorn.sock # we will communicte using this unix socket USER=ubuntu # the user to run as GROUP=ubuntu # the group to run as NUM_WORKERS=72 # how many worker processes should Gunicorn sp TIMEOUT=120 DJANGO_SETTINGS_MODULE=app.settings # which settings file should Django use DJANGO_WSGI_MODULE=app.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/ubuntu/env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir … -
In Django, how to create join on either primary keys?
So, in Django, we have two models. model1(models): pk1 = models.pk(model2, on_delete=models.CASCADE) pk2 = models.pk(model2, on_delete=models.CASCADE) model2(models) somefield = models.charfield() I'd like to create a query to join then and match on either the first primary key or the second The sql equivalent would be select * from model1 join model2 on (model2.id = model1.pk1__id or model2.id = model1.pk2__id) for now I'm stucked with Model1.objects.select_related('model2') which always match on the first pk -
Change colors using CSS on a bootstrap .collapsed selector
Here is the important code in my Django template: <a class="notibell" data-toggle="collapse" href="#pgsettings"><i class="fa fa-bell"></i></a> <div class="collapse" id="pgsettings"> # content to show using the toggle anchor tag above. </div> I'm using this css in the page <head>: <style type="text/css"> .notibell.collapsed { color: green !important; text-shadow: 2px 2px 2px #ccc; } .notibell { color: red; text-shadow: 2px 2px 2px #ccc; } </style> On page load, the icon color is red (should be green). Then on click, the color remains red (correct color for expanded div). And then another click and the color changes to green (correct color for collapsed div). Then from this point forward the toggle and colors change correctly. The problem is on the page load, the color renders incorrectly despite the !important condition. I've also tried loading css in the head before and after bootstrap loads, but this hasn't made a difference. Thanks in advance, any help is appreciated. -
Django filtering DB items in a chain sequence
I am trying to build a project where I have a DB with toys where there are brands, each brand have products, the products have variety of sizes and sizes have colors. What I want to achieve is to have a home page with filtered the brands which I manage to achieve with the views.py below: def Index(request): toys = Toys.objects.values('brand').distinct().order_by('brand') context = {'index': toys } return render(request, 'index.html', context) with models.py class Vehicles(models.Model): brand= models.IntegerField(max_length=255) product = models.CharField(max_length=255) size = models.CharField(max_length=255) color = models.CharField(max_length=255) Now on the main page I have a list with all the different brans, what I'm trying to do is when I click on any Brand for the home page to redirect me to a result page with list of the Brand's products, product will lead to all available sizes and so on. How to implement that in the views? -
Multiple session in R
Can we create multiple sessions in R language . I am not using Rstudio or shiny app . I am just integrating R and python using pip module pypeR. I cannot see any R code where i can learn to create session. My requirement is to create a new session for every R request from python. Because whenever there are two requests to R at the same time my server gets blocked. Also i have used "pypeR" module to integrate R with python. I am a newbie in R as i have worked more in python.I have searched a lot about this issue and it seems to me that R works only in single session when called as a script through python. Any help would be appreciated. -
Is it good or bad practice to reference a single library.py file with all imports?
I am making a Django project with multiple apps and was wondering if it would be considered good or bad practice to create a single library.py file with all the "import x" and "from x import y, z" statements and then simply put "from library.py import *" at the top of every other file? What would be considered best practice for managing your imported libraries like this? Thanks for the help. -
Include my post with followers post in Django
How I can include my post with the followers' post def get(self, request, *args, **kwargs): logged_in_user = request.user video = Video.objects.filter( author__follow__in=[logged_in_user.id] ).order_by('-created_date')