Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I formulate this complex database query with Django 3.0?
I have the following table: Now I want to group the data by code, have a sum of visitors and the number of total nights the visitors stayed for each. I can do the first bit with this query: result = Entry.objects.filter(owner=request.user).values("code").annotate( total_visitors=Sum("visitors")) This yields something along those lines: [{'code': 'AT - Wien', 'visitors': 2}, {'code': 'CN - China', 'visitors': 4}, ...] I would need something like this: [{'code': 'AT - Wien', 'visitors': 2, 'nights': x}, {'code': 'CN - China', 'visitors': 4, 'nights': x}, ...] Now the problem is the number of total nights they stayed. For each entry, I would need to do the following to calculate that: nights = (departure - arrival) * visitors How do I do this the right way? I can do it in code and iterate over the individual entries but there has to be a cleaner way. Thanks! -
Django logout not working - can't understand why
Hi guys hope someone can help me here. I am just starting to create a simple web app using django and I am confused why this isn't working. views.py from django.shortcuts import render, redirect from django.contrib.auth import login, logout def index(request): return render(request, "fittracker/main.html") def login_view(request): pass def logout_view(request): logout(request) return redirect("fittracker/main.html") def signup(request): pass urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path("logout/", views.logout, name='logout') ] I am getting this error I have tired looking at the official docs, and this should redirect, but I am not sure why it isn't -
How to generate textboxes dynamically based on user input number in django?
I am developing a Todo App in which i want to add a new field which takes input as a number and when the user enters, say 3, the app should return 3 empty textboxes and if the user change the number to say 4, then it should refresh to 4 textboxes . So, how should i do it in django using views, models and html. These are my files: views.py from django.shortcuts import render from django.http import HttpResponseRedirect from . models import TodoItem def todoview(request): all_todo_items= TodoItem.objects.all() return render(request, 'todo.html', {'all_items': all_todo_items }) def addTodo(request): new_item = TodoItem(content =request.POST['content']) new_item.save() return HttpResponseRedirect('/todo/') def deleteTodo(request, todo_id): item_to_delete= TodoItem.objects.get(id=todo_id) item_to_delete.delete() return HttpResponseRedirect('/todo/') models.py from django.db import models class TodoItem(models.Model): content = models.TextField() todo.html <div class="p-3 mb-2 bg-warning text-dark">This is the Todo Page</div> <div class="p-3 mb-2 bg-info text-white">HelloPulkit!!!</div> <ol> {% for todo_item in all_items %} <li>{{todo_item.content}} <form action="/deleteTodo/{{todo_item.id}}/" style="display: inline;" method="post">{% csrf_token %} <input class="btn btn-secondary btn-sm"type="submit" value="delete"/> </form> </li> {% endfor %} </ol> <form action="/addTodo/" method="post">{% csrf_token %} <input type="text" name="content"/> <input class="btn btn-primary btn-sm"type="submit" value="add"/> </form> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> -
Getting error 405 while using ModelFormMixin with DetailView
I want to create a DetailView page which displays the detail of a model but I want to add a Comment section in the DetailView page using ModelFormMixin. This is my views.py code: class PostDetailView(ModelFormMixin, DetailView): model = UserPost context_object_name='post_detail' form_class = UserCommentForm def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data(*args, **kwargs) context['form'] = self.get_form() return context def get_absolute_url(self): return reverse(request, 'basic_app:post_detail', kwargs={'pk':self.pk}) But when I hit the submit button it shows the following error: When I hit enter it shows this error. This is the browser with the detailview page -
I get a Type Error when posting data using via REST. It says I may have a writable field on the serializer class that is not a valid argument
full error: Got a `TypeError` when calling `Certificate.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Certificate.objects.create()`. You may need to make the field read-only, or override the CertificateSerializer.create() method to handle this correctly. I have a certificate model which has the clean() and get_remote_image() methods since there are two options of posting image to my database, either with urls or file upload - so when one is already selected the other one is no longer needed. if url is the selected option, it saves to the image field. I get the error when posting data. models.py class Certificate(models.Model): certificate_name = models.CharField(max_length=50) template_img = models.ImageField(blank=True, default='', upload_to='certificate_templates') template_url = models.URLField(blank=True, default='') names_file = models.FileField(blank=True, default='', upload_to='names_files') names_csv = models.TextField(blank=True, default='') Y_RATIO = 1.6268 def get_remote_image(self): if self.template_url and not self.template_img: img_result = requests.get(self.template_url) img_name = os.path.basename(self.template_url) with open(os.path.join(TEMP_DIR, img_name), 'wb') as img_file: img_file.write(img_result.content) self.template_img.save( img_name, open(os.path.join(TEMP_DIR, img_name), 'rb') ) self.save() def clean(self): if not self.template_img and not self.template_url: raise ValidationError({'template_img': 'Either one of template_img or template_url should have a value.'}) if not self.names_csv and not self.names_file: raise ValidationError({'names_csv': 'Either one of names_csv or names_file should have a value.'}) … -
Django OAuth Toolkit logs out automatically
I have two applications sharing a common authentication server that uses Django Oauth Toolkit. Due to this, I manage some common profile settings on the authentication server itself. However, every time the clicks on a link to the authentication server (e.g. to edit profile), it asks them to login again. Not only that, when they come back from the site, the token stops working so they have to login for a third time. I tried adding the authorization token to the response headers through django but that does not seem to work. I am using python-social-auth on my client applications to manage the oauth login process. -
Change Default Functionality Of 'One' Model In One-To-Many Relationship In Django Admin
I have a one-to-many relationship. class User(AbstractUser): user_type = models.CharField(choices=USER_TYPES, max_length=255, default='student') class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='students', default=None, null=True) When I go into Student in Django Admin I have a dropdown box and can select their Teacher. This is good. However, when I go into Teacher, instead of a dropbox of Students, I get an 'Add Another User' button with a dropdown list of all Users. Clicking a student and pressing 'Save' throws the following error Student with this User already exists. How can I remove 'Add Another User' from the Teacher page and replace it with a dropdown list of all Students (or Students who havent been assigned a Teacher)? Thank you. -
How to force Django to use select2 from the CDN instead of the local admin version?
I am trying to implement a website using Django. I have used select2 as one of my components. My problem is that when rendering the template, Django is using select2 from admin which lives here: Click here to go to GitHub code. I want to use select2 loaded from the CDN because it is newer and also I want to pass extra parameters. Here is my code (I removed unnecessary parts to make it simpler): core/templates/core/base.html: <!DOCTYPE html> {% load static %} <html> <head> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet"/> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script> </head> <body> {% block content %} {% endblock %} {% block scripts %} {% endblock %} </body> </html> app_name/templates/app_name/template_name.html: {% extends 'core/base.html' %} {% block content %} <form method="post"> {% csrf_token %} <div class="form-group form-group-lg"> <div class="input-group input-group-lg col-12"> <select id="id_select2" class="form-control selectpicker" name="options[]" multiple="multiple" data-live-search="true"> <option data-tokens="123" value="456">Test</option> </select> </div> </div> </form> {% endblock %} {% block scripts %} <script> $(document).ready(function () { $('#id_select2').select2(); }); </script> {% endblock %} I know that this problem is caused because of having two functions with exactly the same name and parameters. -
Multiple form sets on one page - only first set is saved correctly
I tried to bring two formsets to one page and when I enter multiple inputs in the second it does only save the first input - I checked the len(formset) which always gives back 1, even when there are more. views.py: def create_inq_with_sets_and_parts(request): if request.method == 'GET': inquiry_form = InquiryModelForm(request.GET or None) setts_form = SRFormset(queryset=SettRelation.objects.none()) parts_form = PRFormset(queryset=PartRelation.objects.none()) elif request.method == 'POST': inquiry_form = InquiryModelForm(request.POST) setts_form = SRFormset(request.POST) parts_form = PRFormset(request.POST) if inquiry_form.is_valid() and setts_form.is_valid() and parts_form.is_valid(): i = inquiry_form.save() for form in setts_form: s = form.save(commit=False) s.inquiry = i s.save() print(len(parts_form)) # <-- always gives back 1 for form in parts_form: p = form.save(commit=False) p.inquiry = i p.save() return redirect("inquiry-list") return render(request, "gap/add_inquiry.html", {"inquiry": inquiry_form, "setts": setts_form, "parts": parts_form, }) The forms look very much alike: PRFormset = modelformset_factory(PartRelation, fields=("part", "qty", ), widgets={'part': forms.Select(attrs={'class': 'form-control'}), 'qty': forms.NumberInput(attrs={'class': 'form-control', })}) SRFormset = modelformset_factory(SettRelation, fields=("sett", "qty", ), widgets={'sett': forms.Select(attrs={'class': 'form-control'}), 'qty': forms.NumberInput(attrs={'class': 'form-control', })}) The models.py: class PartRelation(models.Model): part = models.ForeignKey(PartBase, on_delete=models.CASCADE) qty = models.PositiveIntegerField("Quantity") sett = models.ForeignKey(Sett, related_name='sets', on_delete=models.SET_NULL, blank=True, null=True) inquiry = models.ForeignKey(Inquiry, related_name='inq_part', on_delete=models.SET_NULL, blank=True, null=True) class SettRelation(models.Model): sett = models.ForeignKey(Sett, on_delete=models.CASCADE) qty = models.PositiveIntegerField("Quantity") inquiry = models.ForeignKey(Inquiry, related_name="inq_set", on_delete=models.SET_NULL, null=True) The form input is with some java, … -
Logging with django channels using thread local storage problem
I am having issues with debugging multiple requests going through same piece of code, so there is a need of context information. And using this stackoverflow's answer Django logging with user/ip Logging each request with a unique request_id, able to see each request flow easily. But the issue is when there is group_send inside django rest framework views using async_to_sync. Thread local storage won't work in this case due to the code running on a different thread, is there any possible way of propagating thread local storage onto the subthread? Also I found in the docs about async_to_sync that "Threadlocals and contextvars values are preserved across the boundary in both directions.". Does this mean that the thread local variables are shared in some way?, If it's so, why isn't the logger not able to pick up this thread local variable? Anyway to properly log django views, channels with all request information without having to give extra on every log message? Thank you! Link for that async_to_sync line: https://docs.djangoproject.com/en/3.0/topics/async/ -
How to combine product specifications from different websites fast and effectively?
I'm trying to build a price comparison website using Django and Scrapy (Python). The problem is that websites use different names for specifications which causes some issues when combining them. My current solution is to translate all the specifications into the correct format but this would mean that just adding one website may take days. -
Django Rest Framework not running code in perform_create function, so giving errors of field required
I know there are few similar questions here but no solutions proferred in them helped me so far. I have been on this for hours, so i will appreciate any assistance. I am using Django rest Framework to build an API. I have my models, serializers and views set up as follows: My model class Category(models.Model): name = models.CharField(max_length=40, unique=True) slug = models.SlugField() created = models.DateTimeField(auto_now_add=True) class Post(models.Model): title = models.CharField(max_length=100, null=False, blank=False) body= models.TextField(max_length=2000, null=False, blank=False) owner = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to="profiles", default='profiles/no_image.png', blank=True, null=True) created = models.DateTimeField(auto_now_add=True) #signal to create slug on save def pre_save_post_slug(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = slugify(instance.title) # connect signal to model; pre_save.connect(pre_save_post_slug, sender=Post) My Serializer.py: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['id', 'name', 'slug'] extra_kwargs = { 'name': { 'validators': [] } } class PostSerializer(serializers.ModelSerializer): owner = UserSerializer() image = serializers.ImageField(max_length=None) category = CategorySerializer(read_only=False) class Meta: model = Post fields = ['id', 'title', 'body', 'owner', 'slug', 'category', 'image', 'created'] def get_image(self, obj): request = self.context.get('request') image = obj.image.url return request.build_absolute_uri(image) def create(self, validated_data): title = validated_data.get('title') body = validated_data.get('body') slug = slugify(title) image = validated_data.get('image', None) category_data = validated_data.pop('category') … -
Modifying the GET request response in django rest framework
I am trying to implement a private field feature using django.I saved the private fields in django MutliSelectField.After this is done now a differnt API is used to fetch the data.Before sending the response I need to eliminate the fields specified in MultiSelectField.In the serializer we can use create and update method for modifying the results of a POST, PUT and PATCH requests. Similarly is there any method that I can override so as to remove the items specified in the django MultiSelectField. -
Connecting javasciript with django
I want to connect Django with JavaScript because I know a few tools that will help me with my applications and they work best with JavaScript I want to take all the urls and redirections with python and Django but I want some features working with JavaScript and possibly I might want to even want to connect my database with JavaScript. Most probably I will be using node.js and express. -
ImportError: DLL load failed while importing _socket: %1 is not a valid Win32 application. Django
I have jumped from python 32 bit to 64 bit and when I try to run the server, I get the error: ImportError: DLL load failed while importing _socket: %1 is not a valid Win32 application. full traceback is here, Traceback (most recent call last): File "C:\Users\Sheraram Prajapat\OneDrive\Desktop\venv\mysite\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\Sheraram Prajapat\OneDrive\Desktop\venv\mysite\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Sheraram Prajapat\OneDrive\Desktop\venv\mysite\lib\site-packages\django\__init__.py", line 16, in setup from django.urls import set_script_prefix File "C:\Users\Sheraram Prajapat\OneDrive\Desktop\venv\mysite\lib\site-packages\django\urls\__init__.py", line 1, in <module> from .base import ( File "C:\Users\Sheraram Prajapat\OneDrive\Desktop\venv\mysite\lib\site-packages\django\urls\base.py", line 9, in <module> from .exceptions import NoReverseMatch, Resolver404 File "C:\Users\Sheraram Prajapat\OneDrive\Desktop\venv\mysite\lib\site-packages\django\urls\exceptions.py", line 1, in <module> from django.http import Http404 File "C:\Users\Sheraram Prajapat\OneDrive\Desktop\venv\mysite\lib\site-packages\django\http\__init__.py", line 2, in <module> from django.http.request import ( File "C:\Users\Sheraram Prajapat\OneDrive\Desktop\venv\mysite\lib\site-packages\django\http\request.py", line 1, in <module> import cgi File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\cgi.py", line 39, in <module> from email.parser import FeedParser File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\email\parser.py", line 12, in <module> from email.feedparser import FeedParser, BytesFeedParser File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\email\feedparser.py", line 27, in <module> from email._policybase import compat32 File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\email\_policybase.py", line 9, in <module> from email.utils import _has_surrogates File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\email\utils.py", line 29, in <module> import socket File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\socket.py", line 49, in <module> import _socket ImportError: DLL load failed while importing _socket: %1 is not … -
What is the python script for sending email through yandex account?
import smtplib server=smtplib.SMTP('smtp.yandex.com',465) server.starttls() server.login('admin@cbitcse.cf','XXXXX') message='hurray' server.sendmail('admin@cbitcse.cf','xyz@gmail.com',message) server.quit() print('E-mail successfully sent!') Note: Here .cf is a free domain.I have got a free domain-based email address(admin@cbitcse.ml) with yandex. Why is this code not working? Any configuration settings needs to changed in yandex account? -
uploading images through form.py
if i upload the image through my admin dashboard, the image will be successfully uploaded, it will appear in media folder in my project directory i specified in settings.py. but if i upload an image through form.py as a user, every other field is saved except for the image field. I've tried most of the solutions on stackoverflow, dont know why mine ain't working. form.py from django import forms from django.utils.translation import gettext_lazy as _ from .models import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'mainimage', 'category', 'preview_text', 'detail_text', 'price','Quantity'] labels = { 'name': _('Product name'), } help_texts = { 'name': _('be specific eg Tomatoes, Rice'), } error_messages = { 'name': { 'max_length': _("This writer's name is too long."), }, } views.py from django.shortcuts import render, redirect from .form import ProductForm from .models import Product # Create your views here. def products(request): if request.method == 'GET': form = ProductForm() return render(request, 'products/add_product.html',{'forms':form}) else: # imagefield is different from other # fields and it needs to be handles properly # data fetched from imagefield would be stored # in request.FILES object. if request.method == 'POST': form = ProductForm(request.POST or None, request.FILES or None) if form.is_valid(): name = … -
How To Render ChoiceField options in Django template
I am trying to render a ChoiceField in django template, I do not know if i am doing the right thing but the selected ChoiceField saved in database when form is submitted. Now, how do i get the selected choice(Like Placeholder). If choice field is empty i do not want to see (---) I want a placeholder (Choose your gender). And when a gender is selected, i want the placeholder to be replaced by the value(Male instead of Choose your gender). Views.py: def profile_edit(request): updateform = UpdateUserForm(request.POST, instance=request.user) profileeditform = ProfileEditForm(request.POST, instance=request.user.profile) if request.method == 'POST': if updateform.is_valid() and profileeditform.is_valid(): updateform.save() profileeditform.save() messages.info(request, 'Your profile was successfully updated!') return redirect('site:profile-edit') else: updateform = UpdateUserForm(instance=request.user) profileeditform = ProfileEditForm(instance=request.user.profile) #I am trying to get the value of gender choices field of user and pass it value to template, but i am getting an error "invalid literal for int() with base 10: 'male'" gender = Profile.objects.filter(user=request.user.profile.gender) context = { 'updateform': updateform, 'profileeditform': profileeditform, 'gender': gender, } return render(...) Model.py: GENDER = ( ('male', 'male'), ('female', 'female'), ('custom', 'custom'), ('Prefer Not To Say', 'Prefer Not To Say'), ) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) gender = models.CharField(max_length=50, choices=GENDER, verbose_name="gender", blank=True) Forms.py: class ProfileEditForm(forms.ModelForm): class Meta: … -
django_admin_log is not getting created in Oracle and giving ORA-00955
i have been trying to do below steps and all the migrations except my custom apps are getting failed with ORA-00955 error saying name is already used by an existing object. When i search in oracle dba_tables i don't find DJANGO_ADMIN_LOG table i have executed below steps which is failing: python manage.py makemigrations python maange.py migrate admin django.db.utils.databaseerror ora-00955 name is already used by an existing object ***************************** while i am able to perform python manage.py migrate myapp same happening for other objects like auth and session. Any help is appreciated?? -
mongoengine update listed's embeddedfield, just update the first
mongo collection as follow: { "_id" : ObjectId("5eedb36d6cd00ed8e8748cc7"), "user" : "5", "search" : [ { "name" : "first", "status" : 1 }, { "name" : "second", "status" : 0 }, { "name" : "third", "status" : 0 } ] } and models: class HistoryItem(models.EmbeddedDocument): name = models.StringField() status = models.IntField() class History(models.Document): user = models.StringField(unique=True) search = models.EmbeddedDocumentListField(HistoryItem, default=[]) I want to update all status to 1, I try this: mongo_models.History.objects(user="5", search__status=0).update(set__search__S__status=1) but just update the first element which status is 0, what should I change my code update all element's status to 0 ? thanks. -
How to fetch image from temporary storage in Django
I am new at Django. I am uploading images in temporary storage using tempfile but i am now confused how to fetch that image and show on html side. views.py temp = tempfile.mkdtemp() predictable_filename = 'myfile' temporary_location = os.path.join(temp,predictable_filename) def upload_multiple_image(request): if request.method == 'POST': form = UploadFaceImageForm(request.POST,request.FILES) if form.is_valid(): request.session['name'] = file_name request.session['image'] = request.FILES['image'].name with open(temporary_location + file_name, "w") as tmp: tmp.write(file_name) return redirect("show_image") else: return render(request, 'camera/upload_knowface_images.html') def show_image(request): pass How to fetch image in show_image function -
Cannot load DetailView template . URL is generated incorrectly
I am a beginner in Django and I am learning CBV's. I used Django' built in User class to create several users on my website and then i created the following views below . The url generated for my user_list view is http://127.0.0.1:8000/basicapp/user_list/ and works. It shows the users The url generated my user_detail view is http://127.0.0.1:8000/basicapp/1/ (2,3...and so one) and works when manually entered. It shows the user detail The problem is this: In the user_list.html, i add : <a href="{{person.id}}"and In the url.py I add: url(r'^(?P<pk>[-\w]+)/$',views.UserDetailView.as_view(),name='detail') So, when the user list page loads with my users as links , when i hover over the links i get a path like: http://127.0.0.1:8000/basicapp/user_list/1 - this link does not work. I click on it and does not do anything I should be geting : http://127.0.0.1:8000/basicapp/1 . This link does work because i tested it manually. I think I am doing womething wrong in the urls.py but i am not sure. The regex i took was from a training video and have only a general idea about it does. basicapp/views.py: from django.contrib.auth.models import User from django.views.generic import View,TemplateView,ListView,DetailView class UserView(ListView): context_object_name='users' model=models.User template_name='basicapp/user_list.html' class UserDetailView(DetailView): context_object_name='user_detail' model=models.User template_name='basicapp/user_detail.html' basicapp/urls.py: from django.conf.urls import … -
Django OneToOneField not creating table
Thanks in advance, that.s my users/models.py file : from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return "{} profile".format(self.user.username) Then I run python manage.py makemigrations + python manage.py migrate, everything seems to works fine but it doesn't create a table users_profile : 1146, "Table 'polls_db.users_profile' doesn't exist") in the admin section + same when i try to manipulate profile threw the shell. I checked my mariadb database and there is indeed no users_profile table. I'm still learning django and it worked fine in a previous project with an sqlite database, is there a solution ? -
How to add pagination to a filtered table?
Below is the sample code I have for a page that shows a data table with crud options to edit, update, delete entries. I added django filters and it is filtering the data and displaying the queryset however I am unable to add pagination to the page. Can you please help advice how to add it. Also I am showing filters as a form however is it possible to add them individually so that I can format them.. Template: <div> <form action="" method="GET"> {{ mytablefilters.form }} *# Is it possible to show the elements separately so that they can be arranged and formatted easily* <button type="submit">FILTER DATA</button> <Table> <thead> <tr> <th> Employee Name </th> <th> Employee Email </th> <th> Employee Status </th> </tr> </thead> </tbody> {% for entry in tablefilters.qs %} <tr> <td>{{entry.employeename}}</td> <td>{{entry.employeeemail}}</td> <td>{{entry.employeestatus}}</td> </tr> </tbody> Views.py from .filters import mytablefilters from django.views.generic.list import ListView class tablenameview(ListView): model = tablename template_name = 'Index.html' def get_context_data(self, **kwargs): context=super().get_context_data(**kwargs) context['mytablefilters'] = mytabelfilters(self.request.GET,queryset=self.get_queryset()) return context Thank you so much! -
Django - Font sizes in saved form fields on initial page load are small until click / keystroke
I've noticed some strange behavior with my login page. On initial page load, the form fields with pre-populated saved values have smaller text than normal. Once you click on the page or push any key, the text pops back to its normal font size. login.html (simplified) {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container-fluid"> {% crispy form %} </div> {% endblock %} base.html (simplified) {% load static %} <!doctype html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- IE support --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content=""> <meta name="author" content=""> <!-- Allow web app on Chrome --> <meta name="mobile-web-app-capable" content="yes"> <!-- Import Jquery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Backup local file --> <script> window.jQuery || document.write('<script src="{% static 'js/jquery-3.5.1.min.js' %}"><\/script>'); </script> <!-- Import Bootstrap core files --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <!-- Import confirmation / alert box JS files --> <script src="{% static 'js/bootbox.min.js' %}"></script> <script src="{% static 'js/bootbox_common.js' %}"></script> <!-- Font Awesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- Custom CSS --> <link href="{% static 'css/base.css' %}" rel="stylesheet"> <!-- Page-specific imports --> {% block headimport %}{% endblock %} <!-- Allow styling of unknown HTML elements …