Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add progress bar while uploading using django
I'am working on Django project and I need to add progress bar while uploading file.I have tried celery. -
how can i resolve the issue in displaying the ajax search results in django?
Problem The results are being retrieved by the ajax search function but when I display the data retrieved in the selector using $(selector).htm(data) it loads whole the page with a page with correct search results. The code is attached below with the screenshot of what I'm getting from this code for a better understanding. JS $('#searchsubmit').on('click', function(e){ e.preventDefault(); q = $('#search').val(); console.log(q); updateContentBySearch(q); }); function updateContentBySearch(q) { var data = {}; data['search_by'] = q // data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val(); $.ajax({ method: 'POST', url: "{% url 'main:Search' %}", data: { 'search_by': q, 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: function (data) { searchSuccess(data) } }); } function searchSuccess(data, textStatus,jqXHR) { $('#search-results').html(data); } HTML <div class="row"> <div class="row justify-content-center" style="text-align:center"> <form class="d-flex col-md-6" id="searchform" method="POST"> {% csrf_token %} <div class="input-group mb-3" style="text-align:center"> <input name="q" type="text" class="form-control" placeholder="Search" id="search"> <button class="btn btn-primary shadow px-5 py-2" type="submit" id="searchsubmit">Search</button> </div> </form> </div> <hr style="border-top: 1px solid #ccc; background: transparent;"> <div class="row" id="search-results"> {% regroup transaction by productID as ProductList %} {% for productID in ProductList %} ///some code </div> {% endfor %} </div> VIEWS @csrf_exempt def search(request): q = request.POST.get('search_by') print(q) product = Products.objects.all() cart_product_form = CartAddProductForm() transaction = transactions.objects.filter(productID__name__icontains=q,status='Enable').order_by('productID') print(transaction) context={ 'products':product, 'transaction': transaction, 'cart_product_form':cart_product_form } … -
Django HTML template not rendering content
I am building an notifcation system. I am almost complete the notifcation system. Now my problem is notifcation content not rendering my html template. I am not understanding where I am doing mistake.here is my code: notifications models.py: class Notifications(models.Model): blog = models.ForeignKey('blog.Blog',on_delete=models.CASCADE) NOTIFICATION_TYPES = (('New Comment','New Comment'),('Comment Approved','Comment Approved'), ('Comment Rejected','Comment Rejected')) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.CharField(choices=NOTIFICATION_TYPES,max_length=250) text_preview = models.CharField(max_length=500, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) views.py def ShowNOtifications(request): user = request.user notifications = Notifications.objects.filter(user=user).order_by('-date') Notifications.objects.filter(user=user, is_seen=False).update(is_seen=True) template_name ='blog/notifications.html' context = { 'notify': notifications, } return render(request,template_name,context) #html {% for notification in notifications %} {% if notification.notification_type == "New Comment" %} @{{ notification.sender.username }}You have received new commnet <p>{{ notification.text_preview }}</p> {%endif%} {%endfor%} why notification content not showing in my html template? where I am doing mistake? -
Why getting settings.DATABASES is improperly configured. Please supply the ENGINE value.?
I have not written so much line just created a new database in setting.py and routers file in django project. After this run following command in shell and every this goes well and a new file with name auth_db.db.sqlite3 create. python manage.py migrate --database=auth_db C:\Users\Admin\Desktop\project\assignment>python manage.py createsuperuser --database=auth_db Username (leave blank to use 'admin'): admin Email address: admin@gmail.com Password: Password (again): The password is too similar to the username. This password is too short. It must contain at least 8 characters. This password is too common. Bypass password validation and create user anyway? [y/N]: y Superuser created successfully. But when i tried to login in admin panel i get error as:- settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. -
fetching data from database ajax with django based on click button
I'm trying to show some data as notification click on the button the view will appear class Post(models.Model): title = models.CharField(max_length=40) boolean = models.BooleanField(default=False) my views.py from django.core import serializers @login_required def alerts(request): if request.is_ajax(): lists = Post.objects.filter() list_serializer = serializers.serialize('json',lists) return JsonResponse(list_serializer,safe=False) return JsonResponse({'message':'bad request'}) $(document).ready(function(){ $('.myBtn').click(function(){ $.ajax({ url:'{% url 'booking:alerts' %}', type:'json', method:'GET', success:function(data){ var k; for(i=0; i<data.length; i++){ k = '<div class="p-2 mt-1 text-center bgpurple textpurple">' k+= '<p class="p-1 text-white border-2 bgpurple rounded-3xl">'+data[i]['title']+'</p>' k+='</div>'; } console.log(data) document.getElementById('notification').innerHTML = k; } }) }) }) <div class="fixed z-50 w-1/5 h-screen overflow-y-scroll shadow-xl header" id="notification"> <button class="px-4 py-1 m-2 bg-opacity-75 rounded-lg bgorange focus:outline-none myBtn" onclick="showNotifcation()"><i class="bi bi-x"></i></button> <!-- im trying to show the data here --> </div> <button class="relative px-6 py-1 rounded-full focus:outline-none textpurple" onclick="showNotifcation()" style="background-color: #ed9720;"> <span class="absolute top-0 w-4 h-4 text-xs rounded-full left-3 bgpurple" style="color: #ed9720;">display quantity of posts here</span> <i class="fas fa-bell "></i> </button> but it doesnt show anything except in the console return a dictionary is there something i have to change or add please ! -
Added prefix to django tables resulted in ProgrammingError. How can i solve it?
I have added prefix to all my tables in DB using package https://pypi.org/project/django-db-prefix/ I have made all migrations, and when I run the server its working fine. I am not able to open any page and is showing ProgrammingError File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... ^ [07/Jul/2021 05:53:37] "GET /sr_admin/signin/ HTTP/1.1" 500 181053 After migrations all the default tables like 'django_session', 'django_migrations', 'auth_group' etc. are also overridden, and I hope the error is because of that. What should I do to solve this? -
Linkage between pages not working but no error in powershell
I'm a beginner in python-django coding. Currently I am following this guide and doing the challenging part for the author page (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views) but I am facing a issue of the page im trying to set up is not loading. Page is catalog/authors. The catalog page is workable Below are the codes: urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), path('authors/', views.AuthorListView.as_view(), name ='authors'), path('authors/<int:pk>', views.AuthorDetailView.as_views(), name='author-detail'), ] views.py: from django.shortcuts import render # Create your views here. from .models import Book, Author, BookInstance, Genre def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) from django.views import generic class BookListView(generic.ListView): model = Book paginate_by = 5 class BookDetailView(generic.DetailView): model = Book class AuthorListView(generic.ListView): model = Author paginate_by = 5 class AuthorDetailView(generic.DetailView): model = Author author-list.html … -
Django- allow both images and text to be uploaded at the same time?
I would like to have a field in my models.py and forms.py to have the option to upload either photos or text, or both at the same time. Currently, I use a WYSIWYG editor to do that. How would I modify my models so that I can have that option? Here is my code so far: models.py class Problem(models.Model): slug = models.SlugField(null = False, unique = True, max_length = 255) topic = models.ForeignKey(Topic, on_delete = models.CASCADE) free = models.CharField(max_length = 1, choices = Free) #problem when introducing UUID field traceID = models.UUIDField(default=uuid.uuid4, editable = True) #use meta tags to optimize SEO metaTags = models.TextField(default = "") questionToProblem = models.TextField() #migration with CKEDitor is 0023_alter_problem_solutiontoproblem.py solutionToProblem = RichTextUploadingField(blank = True, null = True) The field solutiontoProblem is where I have my text editor- I want to have the field so that it accepts both text and images. Similarily, here is my forms.py: forms.py class ProblemForm(forms.ModelForm): slug = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'link'})) topic = forms.ModelChoiceField(label = "Topic", queryset = Topic.objects.all()) metaTags = forms.CharField(label = "Meta Tags", widget=forms.Textarea(attrs={"rows" : 15, "cols" : 90})) questionToProblem = forms.CharField(label = "Question", widget = QuestionFormWithPreview(attrs={'id' : 'mathInputForQuestion', 'cols': 90, 'rows': 15, 'onkeyup':'PreviewQuestion.Update()'})) solutionToProblem = forms.CharField(widget = CKEditorUploadingWidget(), label = … -
django TypeError: 'coroutine' object is not iterable
Here is the code snippet. I am fetching data from fatabase asynchronusly. but, I am getting below error for contract in contracts: TypeError: 'coroutine' object is not iterable @sync_to_async def get_all_contract_objects(): return EthereumContract.objects.all() def compute_topics_to_eventabis() -> Dict: "Loop through all contracts in our DB and compute topics to ABI mapping" topics_to_event_abis = {} contracts = get_all_contract_objects() for contract in contracts: print(contract) return topics_to_event_abis This part only need to fix. so that i can loop over contracts and print it. -
Is the data type of bid getting changed while I submit the data in HTML form?
I am working on a django project. I want to bid for an item. But when I enter a specific amount of float data it converts the type of the float data. I have been trying to solve this error for a couple of days but I didn't found a solution anywhere. This is what my bids model look like: models.py class bids(models.Model): auction = models.ForeignKey(auction_listing,on_delete=CASCADE) user = models.ForeignKey(User,on_delete=CASCADE) bid = models.FloatField(validators=[MinValueValidator(0.01)]) def __str__(self): return f"{self.bid}" Here is the view function of my code. views.py if request.method == "POST": if request.user.is_authenticated: bform = bid_form(request.POST) author = request.user post = listing user = request.user if bform.is_valid(): bid = bform.save(commit=False) biddata = bids(user=user,auction=post,bid=bid) biddata.save() return HttpResponseRedirect(reverse("displaylistitem",kwargs={"list_id" : list_id})) template.html <form action="" method="POST" class="form-inline"> {% csrf_token %} <div> {{ bform.as_table }} <input type="submit" name="bform" value="Submit" class="btn btn-warning text-light"> </div> </form> This form will redirect the user to the current page itself. But whenever I submit the form it gives this kind of weird error: TypeError while inserting float data. -
Posts liked by favorite user is not showing
I am building a Blog App and I made a model of Favourite Users with ManyToManyField in which a user can add multiple users as favorite users. I am trying to access the posts created by favorite users of user_1. AND I have successfully accessed the posts created by favorite users BUT now i am trying to access the likes hit by favorite users ( which posts are liked by favorite users ) BUT when i access it then it is showing nothing. models.py class Favourite(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user') favourites = models.ManyToManyField(User, related_name='favourites', blank=True) class Post(models.Model): post_creater = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') likes = models.ManyToManyField(User, related_name='post_like', blank=True) views.py def ParenCont(request): obj = Favourite.objects.filter(user=request.user) context = {'obj':obj} return render(request, 'favourite_users.html', context) favourite_users.html {% for objects in obj %} {% for favours in objects.favourites.all %} {% for posts in favours.post_set.all %} <!-- It is successfully showing the posts that are created by favorite users --> {% for post_likes in posts.likes.all %} {{ post_likes }} <!-- It is showing nothing --> {% endfor %} {% endfor %} {% endfor %} {% endfor %} I can understand that there is so much for loop in template but i convert this in view, … -
Django Form Neither Shows Up nor Is It Integrated in The HTML
I'm trying to write a django form that works as a search bar, i've been following the tutorial i'm watching to the T, but for some reason when i run the code the form isn't there, and there's no trace of it in the HTML when i inspect it, it's as if i wrote nothing at all. below is the code i wrote in views.py, layout.html and the path in urls.py . It should be noted that this is the first time i work with django and so far it's been a bit confusing so please do check the code out and point out any and all bug(s). Thank You. Views.py from django import forms from django.shortcuts import render class searchForm(forms.Form): query = forms.CharField() def search(request): return render(request, "encyclopedia/entry.html", { "form": searchForm() }) layout.html <form action="{% url 'wiki:search' %}" method="post"> {{ form }} </form> urls.py from django.urls import path from . import views app_name = "wiki" urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.title, name="title"), path("<str:query>", views.search, name="search") ] -
How to group_by an annotated field for django querysets?
Hers is my model like this: class Article(models.Model): title = models.CharField(max_length=50, blank=True) author = models.CharField(max_length=50, blank=True) created_at = models.DateTimeField(auto_now_add=True) I want to return a queryset which is group_by created_at month, I annotated a created_month field for the queryset: queryset = Article.objects.annotate(created_month=TruncMonth('created_at')) but when I tried to group by created_at by adding .values('created_at'), like this: queryset = Article.objects.annotate(created_month=TruncMonth('created_at')).values('created_month').order_by('-created_month') The queryset returns only created_month field. What shall I do to get whole Article queryset group_by created_month like this: [ { 'created_month': '2021-07', 'articles': [ {'title': 'Article 1', 'author': ...} ] }, { 'created_month': '2021-06', 'articles': [ {'title': 'Article 2', 'author': ...}, {'title': 'Article 3', 'author': ...} ] } ] -
AttributeError: type object 'AuthorDetailView' has no attribute 'as_views'
I'm a beginner in python-django coding. Currently I am following this guide and doing the challenging part for the author page (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views) but I am facing a issue of AttributeError: type object 'AuthorDetailView' has no attribute 'as_views'. Below are my codes: In urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), path('authors/', views.AuthorListView.as_view(), name ='authors'), path('authors/<int:pk>', views.AuthorDetailView.as_views(), name='author-detail'), ] In views.py: from django.shortcuts import render # Create your views here. from .models import Book, Author, BookInstance, Genre def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) from django.views import generic class BookListView(generic.ListView): model = Book paginate_by = 5 class BookDetailView(generic.DetailView): model = Book class AuthorListView(generic.ListView): model = Author paginate_by = 5 class AuthorDetailView(generic.DetailView): model = Author Would appreciate if someone can help me. Thank you -
How to solve InterFAX python library 400 error?
I've been working on a django project that needs to send faxes. For sending faxes I am using interfax python library. To generate pdf from html, I am using xhtml2pdf. I wrote like below, and it didn't work and threw an error. I don't know what to do now. Please help. The code # interfax authentication interfax_password = config("INTERFAX_PASSWORD") interfax_account = config("INTERFAX_ACCOUNT") interfax = InterFAX(username=interfax_account, password=interfax_password) f = File(interfax, pdf, mime_type="application/pdf") fax_number = config("INTERFAX_DESTINATION") # actually sending the data fax = interfax.outbound.deliver(fax_number=fax_number, files=[f]) The error thrown equests.exceptions.HTTPError: 400 Client Error: Bad Request for url:https://rest.interfax.net/outbound/faxes?faxNumber=111111111 Thank you in advance -
Django with websockets - Uvicorn + Nginx
I am trying to run a Django website with channels activated to use the websocket. Everything is working fine when using runserver, but things are getting spicy while switching to Nginx + Uvicorn. here is my /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/myapp/ ExecStart=/usr/local/bin/gunicorn -w 1 -k uvicorn.workers.UvicornWorker --timeout 300 --bind unix:/home/myapp/myapp.sock myapp.asgi:application [Install] WantedBy=multi-user.target here is my /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/home/myapp/myapp.sock [Install] WantedBy=sockets.target and here is my /etc/nginx/sites-available/myapp server { listen 80; server_name myapp.box 10.42.0.1; location = /favicon.ico { access_log off; log_not_found off; } location ~ ^/static { autoindex on; root /home/myapp; } location ~ ^/ { include proxy_params; proxy_pass http://unix:/home/myapp/myapp.sock; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_buffering off; proxy_pass http://unix:/home/myapp/myapp.sock; } } Nginx is running, the socket and gunicorn too. but I have the following error while checking the gunicorn status Jul 07 11:14:11 hostname gunicorn[1825]: File "/usr/local/lib/python3.8/dist-packages/django/apps/registry.py", line 134, in check_apps_ready Jul 07 11:14:11 hostname gunicorn[1825]: settings.INSTALLED_APPS Jul 07 11:14:11 hostname gunicorn[1825]: File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 76, in __getattr__ Jul 07 11:14:11 hostname gunicorn[1825]: self._setup(name) Jul 07 11:14:11 hostname gunicorn[1825]: File "/usr/local/lib/python3.8/dist- packages/django/conf/__init__.py", line 57, in _setup Jul 07 11:14:11 hostname gunicorn[1825]: raise ImproperlyConfigured( Jul 07 11:14:11 … -
How to retrieve a list of objects (including ForeignKey Field data) in django (DRF) without significantly increasing DB call times
I have three models in a django DRF project: class ModelA(models.Model): name = .... other fields... class ModelB(models.Model): name = .... other fields... class ModelC(models.Model): name = .... model_a = FKField(ModelA) model_b = FKField(ModelB) I was using the default ModelViewSet serializers for each model. On my react frontend, I'm displaying a table containing 100 objects of ModelC. The request took 300ms. The problem is that instead of displaying just the pk id of modelA and ModelB in my table, I want to display their names. I've tried the following ways to get that data when I use the list() method of the viewset (retreive all modelc objects), but it significantly increases call times: Serializing the fields in ModelCSerializer class ModelCSerializer(serializers.ModelSerializer): model_a = ModelASerializer(read_only=True) model_b = ModelBSerializer(read_only=True) class Meta: model = ModelC fields = '__all__' Creating a new serializer to only return the name of the FK object class ModelCSerializer(serializers.ModelSerializer): model_a = ModelANameSerializer(read_only=True) (serializer only returns id and name) model_b = ModelBNameSerializer(read_only=True) (serializer only returns id and name) class Meta: model = ModelC fields = '__all__' StringRelatedField class ModelCSerializer(serializers.ModelSerializer): model_a = serializer.StringRelatedField() model_b = serializer.StringRelatedField() class Meta: model = ModelC fields = '__all__' Every way returns the data I need (except … -
How to use Django slugs creatively
In my frontpage.html. I have two buttons that link to the different categories of products I have I was using a for loop to get the slug needed for the URL link In the button, but this causes issues because it renders two buttons for each category i created in the models. My question: Is there a way for Django to only use one of these category slugs so I can specifically pick which URL it will render? I attached a picture of the frontpage.html file notice the for loop I am using to get the category slug that is being used to render the correct detail page. a for loop won't work since i have multiple categories HTML {% for category in menu_categories %} <a href="{% url 'category_detail' category.slug %}">Get Started</a> {% endfor %} models.py for categories class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) ordering = models.IntegerField(default=0) Here is the models.py as well. I was thinking there should be a way to explicitly call a specific slug and not render both buttons right next to each other -
My form is not getting submitted in django. What's wrong with my code?
I am making a complaint management system but the page where I need to accept and save complaints from users, the form isn't even getting submitted as I can't even see the submitted message. models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.CharField(max_length=200, blank=True) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title forms.py: PRIORITY_CHOICES= [ ('high', 'High'), ('low', 'Low'), ] class ComplaintForm(ModelForm): highpriority = forms.CharField(label='Priority', widget=forms.RadioSelect(choices=PRIORITY_CHOICES)) class Meta: model = Complaint fields = ['title', 'description', 'highpriority', 'document'] def clean(self): cleaned_data = super(ComplaintForm, self).clean() title = cleaned_data.get('title') description = cleaned_data.get('description') if not title and not description: raise forms.ValidationError('You have to write something!') template: <!-- Middle Container --> <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field" name="title">{{form.title}}</div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <div class="Descr " name="description">{{form.description}}</div> {{message}} <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> <button type="submit" name="submit" class="btn btn-secondary save-btn" value="Submit"><i class="fas fa-save"></i> Save</button> </form> </div> <!-- Right Container --> <div class="col right-pro-con"> <div class="img-cir"> <form method='POST' action="" enctype="multipart/form-data"> {% csrf_token %} {% if request.user.profile.profile_pic.url %} <img src={{request.user.profile.profile_pic.url}} alt="" … -
Multiple For Loops Django
I have the following two models ASPBoookings and Athlete. The Athlete model is linked to the ASPBookings model by the foreign key named athlete. I am trying to create a loop that will cycle through all of the bookings in the ASPBooking table and find out which is the most recent booking by each athlete. (the table can contain multiple bookings each to the same or different athletes (athlete_id) Once I have this information (booking_date and athlete_id) I then want to be able to automatically update the "Lastest ASP Session Field" in the Athlete Model. This is what I have tried so far. I can cycle through the bookings in the ASPBookings table and retieve and update the "Latest ASP Session Field" using the booking_date and athlete_id, but I cannot do this for multiple different athletes that are within the table. Currently the view just identifies the latest booking and the assigned athlete_id and then updates the field. Thanks in advance for any help. Below is the code. ASPBookings Model. class ASPBookings(models.Model): asp_booking_ref = models.CharField(max_length=10, default=1) program_type = models.CharField(max_length=120, default='asp') booking_date = models.DateField() booking_time = models.CharField(max_length=10, choices=booking_times) duration = models.CharField(max_length=10, choices=durations, default='0.5') street = models.CharField(max_length=120) suburb = models.CharField(max_length=120) region = … -
Django return HLS streaming to frontend
I have encountered an issue during develop HLS live streaming through Django restframework. Currently, I have a shell script that generates HLS files(m3u8), and now I am confused about how to respond the generated HLS files to the frontend so that the user able to view the HLS streaming from web. I did a little bit research on this, looks some developers suggest use Django serve, but I am confused will it be enough if I only return the m3u8 to the frontend. HLS source files generated from ffmpeg -
How to limit the pages to display using Django pagination module
I am trying to implement Django pagination on my page, and I don't want to show more than 5 pages at the same time. what I expect is, that when I click >> the next 5 pages are loaded so the user can click on it. But I don't know how I can do it so that when I click, the next 5 pages are displayed. For example, if the user clicks »: « 1 2 3 4 5 » Expected result: « 6 7 8 9 10 » Current result: « 1 2 3 4 5 » My code: index.html: {% for form in forms %} {% if forms.has_other_pages %} <ul class="nav nav-pills" id="evidence-formset-tab" role="tablist"> {% if forms.has_previous %} <li><a class="nav-link active" id="evidence-form-{{ forms.previous_page_number }}-tab" data-toggle="pill" href="#evidence-form-{{ forms.previous_page_number }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="true">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in forms.paginator.page_range %} <li class="nav-item"> {% if forms.number == i %} <a class="nav-link active" id="evidence-form-{{ i }}-tab" data-toggle="pill" href="#evidence-form-{{ i }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="true">{{ i }}</a> {% elif i > forms.number|add:'-5' and i < forms.number|add:'5' %} <a class="nav-link" id="evidence-form-{{ i }}-tab" data-toggle="pill" href="#evidence-form-{{ i }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="false">{{ i }}</a> … -
Django Forum App, comments don't update on user-side, but can be seen through admin
For reference, here are my models in my Forum app: class Forum(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('forum-detail', kwargs={'pk': self.pk}) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) forum = models.ForeignKey(Forum, on_delete=models.CASCADE) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) To display the forum posts, I have a CBV 'ForumListView': class ForumListView(ListView): model = Forum template_name = 'forum/forum.html' context_object_name = 'forum_posts' ordering = ['-created_at'] From this list, the user can click on any forum and it will lead them to 'forum-detail' with the CBV 'ForumDetailView': class ForumDetailView(DetailView): model = Forum extra_context = { 'comments': Comment.objects.all().order_by('-created_at')} Here is where I passed in the comments from my Comment model to be shown alongside the post. I think this is the reason why the comments don't update, but I'm not too sure how to fix this. In the template for forum_detail.html, this is how I display all the comments made: {% for comment in comments %} {% if comment.forum == forum %} <div class="content-section"> <p>{{ comment.description }}</p> <small>{{ comment.user.username }}, on {{ comment.created_at|date:"F d, Y" }}</small> </div> {% endif %} {% endfor %} Note that the new comment made will be shown … -
Combined or get the Total value of the same fields using Django
I want to get the summary of data with in the same table. Get the duplicate value in "Changing Department" fields, changing department value are depends on the user input. Total the Product Quantity. The output will store in variable. How can I do that? Can you please drop any example for my reference?. Output are same as the picture below but I will display it using HMTL. Im using Django==3.2.3, and Python 3 Excel Sample Data -
In DJANGO, Is there a way to transfer the existing users in django.contrib.auth to SAML or OpenID?
I have used django-oidc-provider, but all it does is create a new user. For a large pre-existing user datatbase, it is inconvenient to create new accounts for all users. I want to do this because I cannot integrate AWS services into my django website without an industry standard for federated authentication.