Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix ‘ No such file or directory’ error in execute console-script by setup.py?
I wrote a static blog generator built using Django. Some problems occurred when I packaged it with setup.py and created the corresponding executable. When I use pip install maltose to install it and run maltose-cli migrate, everything is normal so far. But when I run maltose-cli runserver, I get a error that c:\software\python\python.exe: can't open file 'C:\Software\Python\Scripts\maltose-cli': [Errno 2] No such file or directory. And then, I try maltose-cli.py runserver, everything is OK. This is my setup.py setup( name=NAME, version=about['__version__'], description=DESCRIPTION, long_description=long_description, long_description_content_type='text/markdown', author=AUTHOR, author_email=EMAIL, python_requires=REQUIRES_PYTHON, url=URL, packages=find_packages(include=["maltose", 'maltose.*']), scripts=['maltose-cli.py'], entry_points={ 'console_scripts': ['maltose-cli=maltose:execute'], }, install_requires=REQUIRED, extras_require=EXTRAS, include_package_data=True, license='MIT', classifiers=[ # Trove classifiers # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], # $ setup.py publish support. cmdclass={ 'upload': UploadCommand, }, ) Dir Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2019/4/20 18:41 maltose -a---- 2019/4/20 18:47 90 maltose-cli.py -a---- 2019/4/20 18:47 4047 setup.py In maltose/__init__.py import os import sys def execute(): os.environ.setdefault('DJANGO_DEBUG', 'True') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'maltose.maltose.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual … -
fill formset with django raw sql query
i use django formset factory and update view dont fill sub form with raw sql query and return 'RawQuerySet' object has no attribute 'ordered' error. object query set fine but raw sql query return this error -
How to set header 'Accept-Range' to bytes in HTTPResponse on mp3(media) request in django
I'm having trouble in adding a seek feature to my music player.The problem occurs for the google chrome while other browsers(Microsoft Edge,firefox,etc) works fine.The problem can be seen here in detail -> HTML audio can't set currentTime I'm guessing that the issue is in the HttpResponse Header 'Accept-Ranges' which is not present in the Header data.This is suggested in answers present in the link I provided above. I'm new to Django programming so I don't have any idea about how to tweak with the Http header.So It would be great if told how to do it. -
django ManyToMany Image field with different default images
I have a few models with the Image attribute. I recently got the need to apply many images to an attribute, so i decided to make my own model that includes the image field and relate to it via ManyToMany\OneToMany\OneToOne relationship. Some of my usecases are: profile should have only one user-image post should have OneToMany image field I created the following Image model: from django.db import models from PIL import Image class PandaImage(models.Model): def save(self, *args, **kwargs): default_image_path = kwargs.get('image_path', 'appicon.png') self.image = models.ImageField(default=default_image_path, upload_to='profile_pics') img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) super(PandaImage, self).save(*args, **kwargs) My question is how can I pass different params\default images from each model to the image model? for example, I would like the default picture for the profile to be different than the default picture for a post. later, I might want to change the size that I allow for profile pic but not for a post, and so on... I tried adding a path param to an init method in the Image model but I didnt find a way to pass that param to that class when assigning it to an attribut. eg: … -
How to add list valu in django?
How to add list values in django choice field? My code is from django import forms import os drives_a = [chr(x) + "," for x in range(65, 90) if os.path.exists(chr(x) + ':')] class contactForm(forms.Form): drives = forms.CharField(label='Drive Name', widget=forms.Select(choices=drives_a)) -
Django: can not create multiple model objects with one-to-one relation with one common model
I have two models that extend auth.models.User of django with one-to-one relation between model and the user. I want to create objects of either one of those two, using a form. two models are : class Worker(models.Model): address = models.CharField(max_length=400) user = models.OneToOneField(User, on_delete=models.CASCADE) class Employer(models.Model): address = models.CharField(max_length=400) user = models.OneToOneField(User, on_delete=models.CASCADE) And I have a creator view function as: def worker_sign_up(request): if request.method == 'POST': form = WorkerSignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.employer = None user.worker = Collector() user.worker.address= form.cleaned_data.get('address') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('home') else: form = WorkerSignUpForm() return render(request, 'registration/workersignup.html', {'form': form}) I expect to have a user and a worker in my database, but It creates both Worker and Employer objects. -
How do I populate my form fields with data from the database Django
Hello I have a form page and I only need users to fill in certain fields, with the rest of the fields being pre-filled for them based on the module they pick. While I can fetch the objects from my database -- i.e. the dropdown list shows Module Object (1), Module Object (2) -- I need only certain fields in these objects, which is why this similar sounding post couldn't answer my question: Populate a django form with data from database in view Here's my forms.py class inputClassInformation(forms.Form): module = forms.ModelChoiceField(queryset=Module.objects.all()) duration = forms.CharField(disabled=True, required=False) description = forms.CharField() assigned_professors = forms.ModelChoiceField(queryset=Class.objects.filter(id='assigned_professors')) models.py -- not the full models are shown to reduce the post's length class Module(models.Model): subject = models.CharField(max_length=200, default="") class Class(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE, default="") duration = models.CharField(max_length=200, default="") description = models.CharField(max_length=200, default="") assigned_professors = models.CharField(max_length=200, default="") So an expected result would be: 1) The Module field shows the subjects, instead of Module objects in its dropdown list and 2) The duration field is automatically filled in for the user. This has had me stuck for a long while, help is appreciated. Thanks! -
Migrating django-oscar project
I'm following the docs on building my own shop on django-oscar but get an error when I migrate it I've tried checking the docs if I missed something. $ python manage.py migrate Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/Users/user/main-folder/child-folder/oscar/lib/python3.7/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/Users/user/main-folder/child-folder/oscar/lib/python3.7/site-packages/django/core/management/init.py", line 357, in execute django.setup() File "/Users/user/main-folder/child-folder/oscar/lib/python3.7/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/user/main-folder/child-folder/oscar/lib/python3.7/site-packages/django/apps/registry.py", line 93, in populate "duplicates: %s" % app_config.label) django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: haystack It should create the database and be able to show me the shop. Is anyone experienced in django's oscar? -
Documenting a DRF GET endpoint with multiple responses using Swagger
I have a GET endpoint for a RESTful API I am creating using Django. This endpoint reads three values from the URL's query string. A particular parameter in the query string has the potential to change the data (include extra fields and change the structure slightly) which is returned in the JSON response from this endpoint. This endpoint is not tied directly to a single model. I have overriden the RetrieveAPIView, in the view, I override get_object and some logic is performed to query multiple models, make some decisions and return an ordered dictionary. My problem is as follows: I would like to document this endpoint using Swagger. I am using drf-yasg to generate my Swagger documentation. I have no serializers declared for this view; since I manually construct an ordered dictionary in get_object I don't see the purpose of declaring one. I'm not sure how to document my endpoint using drf-yasg. I have discovered only one approach to document the endpoint, but it is quite ugly and bloats my code, and I'm wondering if there is a better approach. By declaring an openapi.Response object, and supplying this object to the @swagger_auto_schema decorator Swagger displays the two possible responses, but … -
How can I assign the logged in (authenticated) user to the form data they submit?
I am developing an employee feedback interface with Django. They shall be able to log in and submit a complaint. That complaint is supposed to be stored in the database with the user who submitted it as an attribute. I have tried to somehow pass the user to the form so that the form saves the authenticated user's username, but I haven't been able to pass data from a view to a form. I have been able to integrate a ModelChoiceField() to the ModelForm, but that lets the authenticated user manipulate the username that the complaint is going to be associated with. models.py: from django.db import models from django.contrib.auth.models import User class Complaint(models.Model): complaint_text = models.CharField(max_length=1000, default='') switch_schedule_yes_or_no = models.BooleanField(default=True) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) views.py: from .forms import ComplaintForm from django.contrib.auth.decorators import login_required from django.shortcuts import render @login_required() def complaint_view(request): form = ComplaintForm(request.POST) if form.is_valid(): form.save() form = ComplaintForm() context = { 'form': form, } return render(request, 'complaint.html', context) forms.py: from django import forms from .models import Complaint from django.contrib.auth.models import User class ComplaintForm(forms.ModelForm): complaint_text = forms.CharField(max_length=1000) switch_schedule_yes_or_no = forms.BooleanField() user = forms.ModelChoiceField(queryset=User.objects.all()) class Meta: model = Complaint fields = ['complaint_text', 'switch_schedule_yes_or_no', 'user'] If it is possible to somehow … -
virtualenv and django interaction
I installed Django 2.1.3 in my windows computer for project then created a virtualenv for another django project, So after activating virtualenv. I nothing installed in my virtualenv yet, so why I am able to run the command django-admin startproject without installing django. But when i try to runserver in virtualenv by command: manage.py runserver it shows the error, i.e django is not installed in virtualenv Need some explaination why is happening in my virtualenv -
Many templates in one generic view - Django
I'd like to write a generic view, for my logging and signup views. I thought, since I am using forms.py about creating one .html file with if statement. I stuck with: how to pass to html, which context should be rendered (let's say default is login), but if you click on the url it will lead/show you to signup_form and the url will disappear. At this point I'm using two .htmls, but since they are almost the same, I'd like to combine them. views.py class HomePage(View): loginHTML = 'tripplanner/login_create.html' context = { 'login_form': Login, 'signup_form': UserForm } def get(self, request): return render(request, self.loginHTML, {'form': self.context)}) other attempt to views.py def get(self, request): return render(request, self.loginHTML, {'form': self.context.get('login_form)}) Here I can define, which is default, but then I don't know how to change it when I use url link. forms.py class Login(forms.Form): login = forms.CharField(max_length=64) password = forms.CharField(widget=forms.PasswordInput) class UserForm(ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email', 'password') login_create.html {% extends 'tripplanner/base.html' %} {% block content %} <form action="#" method="post"> {% csrf_token %} {{ form.as_ul }} <input type="submit" value="Submit"> </form> <a href="{% url 'createuser' %}">Create user</a> {% endblock %} urls.py url(r'^auth/test', HomePage.as_view(), name='test'), path('createuser', CreateUserView.as_view(), name='createuser'), -
Display the right Key at the right profile
My application stores public pgp keys which other users can see if the account owner has decided to display his public key the world. Now i want to display this key in RAW format but for some reasone i always get the account owners/ my own accounts key displayd whatever user profile/pk i call. views.py def raw_pgp_external(request, pk=None): user = get_user_model().objects.get(pk=pk) if user.option_pubpgp_key_visable == False: args = {'external_user': user} return render(request, 'Accounts/profile_as_external.html', args) else: user = request.user args = {'external_user': user} return render(request, 'Accounts/raw_pgp_external.html', args) urls.py url(r'^user/(?P<pk>\d+)/raw_pgp$', auth_required(Accounts.raw_pgp_external), name='raw_pgp_external'), In the end i simply want to filter if a external user is allowed to view the key in raw format of the user user ... thanks for help. Kind regards -
Html popup with contact form in django
A pop-up window that displays a successful message when the fields are filled in in Django and a failed message when empty {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> {% render_field field class="form-control" %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} <input data-toggle="modal" data-target="#myModal" type="submit" value="send" /> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> Some text in the modal. </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> If the user fills in the contact form and presses the button, I want a successful pop-up window. If you press the button without filling, I want a pop-up window that fails. Can you help me? -
social-django, About setting of pipeline and model
Django2.1 social-auth-app-django I have implemented twitter login in social-django, and in models.py I write to get username. I improved this and tried to get avatar from the pipeline. There was a problem. When getting avatar by pipeline, user and model are not linked yet. In other words, an error occurs. How can I improve it? Error RelatedObjectDoesNotExist at /complete/twitter/ User has no mymodel #models.py class Mymodel(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) username = models.CharField(max_length=30, unique=True, primary_key=True) title = models.CharField(max_length=20) content = models.TextField(max_length=5000) avatar = models.URLField(max_length=200, blank=True) def save(self, *args, **kwargs): if not self.username: self.username = self.user.username super(Mymodel, self).save(*args, **kwargs) #pipeline.py def get_avatar(backend, strategy, details, response, user=None, *args, **kwargs): url = None if backend.name == 'twitter': url = response.get('profile_image_url', '').replace('_normal', '') if url: user.mymodel.avatar = url user.save() thank you. -
Sort posts(either picture or status ) based on create date
For a pet project, i am trying to display the posts and pictures sorted on the date created. Right now i can display them is sorted order but separately ( like first posts in sorted order and then pictures in sorted order). I would like to show them on the wall based on create date (regardless of whether it is a post or picture) Models.py class AddStatus(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ) status = models.TextField() date = models.DateTimeField(default=datetime.now) class ImageLib(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ) picture = models.ImageField() date = models.DateTimeField(default=datetime.now) Views.py class ProfilePage(ListView): model = models.UserCreation context_object_name = 'profile' def get_context_data(self, *args, **kwargs): context = super(ProfilePage, self).get_context_data(*args, **kwargs) user =self.request.user try: context['data'] = ProfileData.objects.get( user=user) context['add'] = AddStatus.objects.filter(user=user).order_by('-date') context['uploadpic'] = ImageLib.objects.filter(user=user).order_by('-date') except ProfileData.DoesNotExist: context['data']= None context['add']=None context['uploadpic'] = None return context Template {% for items in add %} <h6 class="display-5" style="font-weight:1px"><i class="fas fa-plus-square"></i>&emsp;<strong class="capitalize">{{items.user.usercreation.fname}} {{items.user.usercreation.lname}}</strong><span style="font-size:16px; font-weight:1px"> wrote "{{items.status}}"</span> <small style="font-size:0.7rem">&emsp;{{items.date.date}} at {{items.date.time}}</small><a style="float:right" href="{% url 'usercreation:deletestatus' items.pk %}"><i class="fas fa-trash"></i></a></h6> <hr> {% endfor %} {% for pics in uploadpic %} <h6 class="display-5" style="font-weight:1px"><i class="fas fa-plus-square"></i>&emsp;<strong class="capitalize">{{pics.user.usercreation.fname}} {{pics.user.usercreation.lname}}</strong><span style="font-size:16px; font-weight:1px"> uploaded a picture</span> <small style="font-size:0.7rem">&emsp;{{pics.date.date}} at {{pics.date.time}}</small><a style="float:right" href="{% url 'usercreation:deletepic' pics.pk %}"><i class="fas fa-trash"></i></a></h6> <img style="width:300px" src="{{pics.picture.url}}" alt=""> … -
How do i play videos stored on a external drive on my webpage using python and django with postgresql
I am working on building a video tutorial website using python Django with PostgreSQL as db. I have around 2tb of videos that i need to play on the website. How do i get the videos to the front-end through the database from my hard-disk? i don't want to store the videos in my database. Just creating a link for the videos on the hard-disk that is stored in the database is my expected result. any kind of help is appreciated. -
winerror: The system cannot find the file specified
FileNotFoundError at /admin/audiofield/audiofile/add/ [WinError 2] The system cannot find the file specified Request Method: POST Request URL: http://127.0.0.1:8000/admin/audiofield/audiofile/add/ Django Version: 1.11.17 Exception Type: FileNotFoundError Exception Value: [WinError 2] The system cannot find the file specified Exception Location: C:\Users\agent\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py in _execute_child, line 1178 Python Executable: C:\Users\agent\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.2 Python Path: ['C:\blogs\blog\django_playlist\djangonautic', 'C:\Users\agent\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\agent\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\agent\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\agent\AppData\Local\Programs\Python\Python37-32', 'C:\Users\agent\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] Server time: Sat, 20 Apr 2019 06:13:27 +0000 That is the error that we have encountered while running the code from https://github.com/areski/django-audiofield/ and when we try to save an audio file the error above shows... and the exception line 1178 is a startupinfo and its kinda confusing because I am new to this environment of python and django ...... pls help me because we are running out time to meet our deadline -
Django deployment on windows server 2016 [WinError 193] %1
I am trying to deploy a Django project on Windows Server 2016 and I get the following error message when I open the website. Can you help me with that? I have installed 32bit python, and got the same error. Then I installed the 64bit python, again the same problem. I have also tried to pip upgrade any other dependencies in case there is a problem with them, but again no luck Any ideas? Environment: Django Version: 2.2 Python Version: 3.7.3 Traceback: File "c:\python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "c:\python37\lib\site-packages\django\core\handlers\base.py" in _get_response 100. resolver_match = resolver.resolve(request.path_info) File "c:\python37\lib\site-packages\django\urls\resolvers.py" in resolve 527. for pattern in self.url_patterns: File "c:\python37\lib\site-packages\django\utils\functional.py" in __get__ 80. res = instance.__dict__[self.name] = self.func(instance) File "c:\python37\lib\site-packages\django\urls\resolvers.py" in url_patterns 571. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "c:\python37\lib\site-packages\django\utils\functional.py" in __get__ 80. res = instance.__dict__[self.name] = self.func(instance) File "c:\python37\lib\site-packages\django\urls\resolvers.py" in urlconf_module 564. return import_module(self.urlconf_name) File "c:\python37\lib\importlib\__init__.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>" in _gcd_import 994. <source code not available> File "<frozen importlib._bootstrap>" in _find_and_load 971. <source code not available> File "<frozen importlib._bootstrap>" in _find_and_load_unlocked 955. <source code not available> File "<frozen importlib._bootstrap>" in _load_unlocked 665. <source code not available> File "<frozen importlib._bootstrap_external>" in exec_module 678. <source … -
How to respond with an upload identifier inside a fully custom Django uploads handler?
There is child class of FileUploadHandler which handles complete reading and writing of file from the client. I use default python's file object to write to disk skipping the Django's TemporaryUploadedFile. I use uuid4 name for the file. Now, my concern is that how do I respond the client with this uuid4 text to let them later send me that to continue their broken uploads? I see that the upload completes, then only the final response is sent. Session, I'm not using as there will be overhead to maintain it. Also I think, should not make request to server for an upload uuid4 as identifier to handshake an upload with. If that is a solution, I can use it, given that there isn't a way to respond in between the custom uploads handler. I'm expecting there's a possible way to send response in between the custom uploads handler. It doesn't seems to be a way to do that from my side as I tried. -
File Uploads via FormModel (Official description), but form.is_valid is always false
I'm trying to use FormModel to handle a file upload, but form.is_valid() is always returning false, and never shows any kind of error.Following is the code snippet from models.py,forms.py,views.py and my POST request. models.py class Pics(models.Model): id = models.AutoField(primary_key=True,) username = models.CharField(max_length=45) path = models.ImageField(upload_to=img_path) forms.py class PicsForm(forms.ModelForm): class Meta: model = Pics fields = ['username','path'] views.py def uploads(request:HttpRequest): form = PicsForm(request.POST,request.FILES) if form.is_valid(): # instance = Pics(username=request.POST['username'],path=request.FILES['file']) # instance.save() form.save() print('***') else: print('&&&&&&&&&&&&&') return HttpResponse("succeed") my postman data set I expect the output of '***', but the actual output is '&&&&&&&&&&&&&' -
how to save many to many field in django
I am trying to save students from addstudent form but it is not saving students and it is displaying error message 'error in form'. I think error is while saving many to many field.How can i save the many to many field in django.Is there any solutions for this models.py class Course(models.Model): title = models.CharField(max_length=250) basic_price = models.CharField(max_length=100) advanced_price = models.CharField(max_length=100) basic_duration = models.CharField(max_length=50) advanced_duration = models.CharField(max_length=50) class Student(models.Model): name = models.CharField(max_length=100) course = models.ManyToManyField(Course) address = models.CharField(max_length=200) email = models.EmailField() phone = models.CharField(max_length=15) image = models.ImageField(upload_to='Students',blank=True) joined_date = models.DateField() forms.py class AddStudentForm(forms.ModelForm): class Meta: model = Student fields = '__all__' views.py def addstudent(request): courses = Course.objects.all() if request.method == 'POST': form = AddStudentForm(request.POST) if form.is_valid(): student = form.save() student.save() messages.success(request,'student saved.') return redirect('students:add_student') else: messages.error(request,'error in form') else: form = AddStudentForm() return render(request,'students/add_student.html',{'form':form,'courses':courses}) add_student.html <form action="{% url 'students:add_student' %}" method="post"> {% csrf_token %} <div class="form-group"> <h5>Full Name <span class="text-danger">*</span></h5> <div class="controls"> <input type="text" name="name" class="form-control" required data-validation-required-message="This field is required"> </div> </div> <div class="form-group"> <h5>Course <span class="text-danger">*</span></h5> <div class="controls"> <select name="course" id="select" required class="form-control"> <option value="">Select Your Course</option> {% for course in courses %} <option value="{{course.title}}">{{course.title}}</option> {% endfor %} </select> </div> </div> <div class="form-group"> <h5>Address<span class="text-danger">*</span></h5> <div class="controls"> <input … -
How to merge two raw query in Django 2?
I was trying to merge two query return data, into one object like viewAllUq = Uqmain.objects.raw(''' select *, uqmain.id as uqmainID, company.name as companyName, uqmain.created_by as uqMainCreated_by, company.slug as companySlug, uqmain.slug as uqmainSlug from uqmain Left join company ON company.id = uqmain.company_id Left join user ON user.id = uqmain.created_by where uqmain.deleted = 0''') doneBids = Uqbids.objects.raw(''' select DISTINCT uq_main_id as bidDoneUqmain, id from uqbids where created_by = %s''',[request.user.id]) here viewAllUq and doneBids are two raw queries I want to merge this query into one query like merged = viewAllUq + doneBids #I want something like this to merge them for data in merged: print(data.companyName) # Access viewAllUq object data print(data.bidDoneUqmain) # Access doneBids object data I do a few google search but not helping me out. -
Refreshing table data using Ajax not working in django
Trying to build a web application for the first time using Django. The table UI from the below script is rendering the data for the first time. But the Ajax call doesn't seem to call the get_more_tables in views.py and refresh the table data. I have already looked at but didn't help my case Reload table data in Django without refreshing the page home.html {% block content %} <td class="more-padding-on-right">CURRENT RESPONSE TIME OF WEBSITES</td> <table id="_response_time" class="table table-striped table-condensed"> <tr> <th>Website</th> <th>Current Response Time(ms)</th> </tr> {% for posts in posts2 %} <td>{{ posts.website }}</td> <td>{{ posts.response_time}}</td> </tr> {% endfor %} </table> <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: '{% url 'get_more_tables' %}', data: {'append_increment': append_increment} }) .done(function(response) { $('#_response_time').append(response); append_increment += 10; }); }, 10000) </script> {% endblock content %} get_more_tables.html {% load static %} {% for post in posts %} <tr> <td>{{ post.website}}</td> <td>{{ post.response_time }}</td> </tr> {% endfor %} urls.py urlpatterns = [ path('', views.home , name='dashboard-home'), path('about/',views.about, name='dashboard-about'), path('get_more_tables', views.get_more_tables , name='get_more_tables'), ] views.py def get_more_tables(request): logger.info('************************************************** Refreshing Table Content') increment = int(request.GET['append_increment']) increment_to = increment + 10 my_response = responseTime(url,url2) return render(request, 'templates_dashboard/get_more_tables.html', {'posts': my_response[increment:increment_to]}) I'm expecting the table data … -
What is the best way to write multiple aggregate views in Django?
I have the following snippet: sum_games = GameHistory.objects.all().aggregate(Sum('games')) sum_played = GameHistory.objects.all().aggregate(Sum('games_played')) sum_goals = GameHistory.objects.all().aggregate(Sum('goals')) sum_assists = GameHistory.objects.all().aggregate(Sum('assists')) sum_clean_sheet = GameHistory.objects.all().aggregate(Sum('clean_sheet')) What is the best and cleanest way to write this? Because right now I am just repeating myself but with different variables. Thanks in advance.