Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authentication in Django Rest framework using django-auth-adfs
I am using the django-auth-afs python library to authenticate and protect my DRF API. I have registered my app in Azure and have client_id, client_secret and tenant_id. Can someone help to tell me how to configure the django rest framework? I have tried out the following documentation https://django-auth-adfs.readthedocs.io/en/latest/rest_framework.html https://django-auth-adfs.readthedocs.io/en/latest/azure_ad_config_guide.html#step-1-register-a-backend-application My current configuration in settings.py AUTHENTICATION_BACKENDS = ( 'django_auth_adfs.backend.AdfsAuthCodeBackend', 'django_auth_adfs.backend.AdfsAccessTokenBackend', ) AUTH_ADFS = { 'AUDIENCE': client_id, 'CLIENT_ID': client_id, 'CLIENT_SECRET': client_secret, 'CLAIM_MAPPING': {'first_name': 'given_name', 'last_name': 'family_name', 'email': 'upn'}, 'GROUPS_CLAIM': 'roles', 'MIRROR_GROUPS': True, 'USERNAME_CLAIM': 'upn', 'TENANT_ID': tenant_id, 'RELYING_PARTY_ID': client_id, } REST_FRAMEWORK = { # type: ignore # disable this until Azure SSO integration done 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_auth_adfs.rest_framework.AdfsAccessTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), When to try to access my API I get response back but it should throw Unauthorised message and When I try to access the /admin page I get the following error 022-06-09 08:36:33,718 - INFO - django_auth_adfs - django_auth_adfs loaded settings from ADFS server. 2022-06-09 08:36:33,718 - INFO - django_auth_adfs - django_auth_adfs loaded settings from ADFS server. 2022-06-09 08:36:33,718 - INFO - django_auth_adfs - operating mode: openid_connect 2022-06-09 08:36:33,718 - INFO - django_auth_adfs - operating mode: openid_connect ...... 2022-06-09 08:36:33,719 - DEBUG - django_auth_adfs - django_auth_adfs authentication backend was called … -
Django disable checkboxes in dependent lists
I have 3 lists of checkboxes and I'd like to disable all unnecessary checkboxes in my HTML file if there are no relevant products connected to this product and change the count number dynamically. For now, I managed to display the total number of items per checkbox but I am not sure how to make the count dynamic so if the user chooses checkbox 1 in the team list then numbers in other lists will adjust and show relevant count. If the user selects checkbox 1 in the team list I want to disable all change from this: <input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="type"> To this: <input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="type" disabled> views.py class Search(LoginRequiredMixin, ListView): login_url = 'login' redirect_field_name = 'login' template_name = 'product-list.html' model = Product queryset = Product.objects.filter(status=1) def get_context_data(self, **kwargs): context = super(Search, self).get_context_data(**kwargs) type = Type.objects.annotate(type_count=Count('type_product', filter=Q(type_product__status=1))) role = Role.objects.annotate(role_count=Count('role_product', filter=Q(role_product__status=1))) leading_team = Team.objects.annotate(team_count=Count('product', filter=Q(product__status=1))) product_list = Product.objects.filter(status=1) context['product_type'] = product_type context['role'] = role context['leading_team'] = leading_team context['product_list'] = product_list return context #Filter data def filter_data(request): type = request.GET.getlist('product_type[]') role = request.GET.getlist('role[]') leading_team = request.GET.getlist('leading_team[]') product_list = Product.objects.filter(status=1) if len(type) > 0: product_list = product_list.filter(type__title__in=type).distinct() if len(role) > 0: product_list = product_list.filter(service_role__title__in=role).distinct() if len(leading_team) … -
Django return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: CsExpert_user
So I am working on a website, and whenever I want to create a new user, I am getting this error, and I don't know what to do next, it seems like tables for my models are not being created, in this case what can I do? my models.py : class User(AbstractUser): pass my views.py: def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "CsExpert/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: user = User.objects.create_user(username, email, password) user.save() except IntegrityError: return render(request, "CsExpert/register.html", { "message": "Username already taken." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "CsExpert/register.html") -
I am getting Error: create_user() missing 1 required positional argument: 'username'
I am creating a Profiles REST API I am getting error on line 30 of serializers.py i.e the password. This is the models.py def create_user(self,email,name,password=None): """Create a new user profile""" if not email: raise ValueError('User must have an email address') email = self.normalize_email(email) # normalize_email() is a helper function that converts email 1st to lowercase user = self.model(email=email,name=name) # self.model is the UserProfileManager class user.set_password(password) # set_password() is a helper function that hashes the password user.save(using=self.db)# save() is a helper function that saves the user to the database return user This the serializers.py class UserProfileSerializer(serializers.ModelSerializer): def create(self,validated_data): """Create and return a new user""" user = models.UserProfile.objects.create_user( email=validated_data['email'], name=validated_data['name'], password=validated_data['password'], ) return user -
How to return only specified fields from serializerMethodField using DRF
it will return nested array like { project_name:test, site_id:[[1],[2]],site_name:[[test1],[test2]] },but I would like to return like this {{sitename:test1, siteid:1},{sitename:test2, siteid:2}} class ProjectSite(models.Model): site_id = models.AutoField(primary_key=True, unique=True) site_name = models.CharField(max_length=200,name='project_site_name') project_id = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True, related_name="projectid") class Serializer(serializers.ModelSerializer): ... site_ids = serializers.SerializerMethodField(read_only = True) site_name = serializers.SerializerMethodField(read_only = True) ... def get_site_ids(self, obj): return list(obj.projectid.values_list('id').distinct()) def get_site_name(self, obj): return list(obj.projectid.values_list('site_name').distinct()) -
django - relation between server tags, server and the post
I'm creating a reddit clone app, There are 3 servers, each server has its own set of tags(e.g., for food server: burger, pizza,...) and each server can have multiple posts(just like Reddit). so how can I make it so that the user can choose between tags when creating a new post? user should only be able to choose on of the tags dedicated to the server which the post is going to be posted on. I've made a ServerTag model to save tags when creating a new server: class ServerTag(models.Model): server = models.ForeignKey(Server, on_delete=models.CASCADE, related_name='tags') name = models.CharField(max_length=20) primary_color = ColorField(default = '#ffff') secondary_color = ColorField(default = '#ffff') is_allowed = models.BooleanField(default=True) def __str__(self) -> str: return f'{self.name} --> r/{self.server}' Server model: class Server(models.Model): creator = models.ForeignKey(User , on_delete=models.CASCADE) created = models.DateTimeField(auto_now=True) name = models.CharField(max_length=50) about = models.TextField(default='about') tag = models.CharField(max_length=50) slug = models.SlugField(default='server') image = models.ImageField(upload_to='servers/pic/') header_image = models.ImageField(upload_to='servers/header-pic/') members_count = models.IntegerField(default=0) online_count = models.IntegerField(default=0) required_karma = models.IntegerField(default=0) def __str__(self): return self.name and Post Model: class Post(models.Model): post_type_choices = [('text', 'text'), ('video', 'video'), ('image', 'image'), ('link','link')] title = models.CharField(max_length=200) slug = models.SlugField(max_length=50, default='slug') text = models.TextField(null=True, blank=True) text_allowed = models.BooleanField(default=True) image = models.ImageField(upload_to='posts/images/', null=True, blank=True) image_allowed = models.BooleanField(default=True) video = … -
ModuleNotFoundError: No module named 'models. Unable to import models into folder
I'm creating a project in django called social_monitoring and I'm getting the error within the app 'fb_scraping'. I'm trying to import models from the models folder that I have created into a python file in another folder in the same directory. But, it keeps giving me this error from models.scrapingmodels import Scrapedposts, Postcomments Error: ModuleNotFoundError: No module named 'models' The structure of the project: social_monitoring/ --└── fb_scraping/ -----├── models/ -----│ -----├──__init.py__ -----│ -----└──scrapingmodels.py (where I'm importing from) -----└── scripts/ -----------└──fbscrape.py (where I'm importing to) scrapingmodels.py contains 2 class: Scrapedposts and Postcomments In the init.py file in models folder, I've added: from .scrapingmodels import Scrapedposts as _Scrapedposts from .scrapingmodels import Postcomments as _Postcomments In fbscrape.py, I have tried to import in several ways: from fb_scraping.models.scrapingmodels import Postcomments, Scrapedposts and i get the error: ModuleNotFoundError: No module named 'fb_scraping' What do you suggest I do to fix this issue? -
audio cannot played but detected to local storage
my website have form using models to upload audio file. when it uploaded, the file cannot be played but at my terminal it’s already detected the file name. but when i open new page, the audio can be play without i need to upload again. anyone know what’s wrong? here’s my html: <audio controls="controls"> <source src="/media/mp3/{{last_audio.audio}}" type="audio/mpeg"> </audio> views.py: def homepage(request): form = AudioForm() last_audio = Audio_store.objects.all().last() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): audio = form.cleaned_data.get("audio") print(audio) context={'form':form, 'last_audio':audio} print(context) form.save() return render(request, "homepage.html", context=context) context={'form':form, 'last_audio':last_audio} return render(request, "homepage.html", context=context) models.py: from django.db import models from django.core.files.storage import FileSystemStorage fs = FileSystemStorage(location='media/mp3') fss = FileSystemStorage(location='media/txt') class Audio_store(models.Model): password=models.FileField(storage=fss, null=True) audio=models.FileField(storage=fs, null=True) -
TinyMCE in Wagtail/Django project doesn't save some of the rich text features, like font size, alignments
I have a Django/Wagtail project. The project uses wagtailtinymce package. The TinyMCE looks great and it shows fine in all rich text fields and stream blocks. The Problem When I change the font size and save it. It is back to normal size as soon as the page refresh. so it doesn’t save the font size, and some other features too. However, it only saves a few features, like headings. Here is some code I have: requirements.txt ... wagtail==2.11.3 Django==2.2.16 wagtailtinymce @ git+https://github.com/TwilioDevEd/wagtailtinymce.git ... urls.py path('tinymce/', include('tinymce.urls')), ###settings INSTALLED_APPS = [ ... 'tinymce', 'wagtailtinymce' ] WAGTAILADMIN_RICH_TEXT_EDITORS = { 'default': { 'WIDGET': 'wagtaildashboard.models.MyTinyMCE' }, } wagtaildashboard.models.MyTinyMCE from django.db import models # Create your models here. from django.utils import translation from wagtailtinymce.rich_text import TinyMCERichTextArea from django.conf import settings class MyTinyMCE(TinyMCERichTextArea): @classmethod def getDefaultArgs(cls): return { "passthru_init_keys": { 'mode': 'textareas', 'plugins': 'preview importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media template codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount help charmap quickbars emoticons', 'editimage_cors_hosts': ['picsum.photos'], 'menubar': 'file edit view insert format tools table help', 'toolbar': 'undo redo | bold italic underline strikethrough | fontfamily fontsize blocks | alignleft aligncenter alignright alignjustify | outdent indent | numlist … -
redis-sentinel connection error in django with "AUTH <password> called without any password configured for the default user. Are you sure ..."
I have a problems with redis-sentinel connection. I tried to connect redis-sentinel by using django-redis. # redis connection factory DJANGO_REDIS_CONNECTION_FACTORY = 'django_redis.pool.SentinelConnectionFactory' # These sentinels are shared between all the examples, and are passed # directly to redis Sentinel. These can also be defined inline. SENTINELS = [ (env('REDIS_SENTINEL_IP_1'), 26379), (env('REDIS_SENTINEL_IP_2'), 26379), (env('REDIS_SENTINEL_IP_3'), 26379) ] CACHES = { "default": { "BACKEND": env('DJANGO_CACHE_BACKEND_REDIS'), # THE HOSTNAME IN LOCATION is the primary (service/master) name # example : redis://dev-redis/db # example : redis://staging-redis/db "LOCATION": env('DJANGO_CACHE_LOCATION_REDIS'), "OPTIONS": { # django_redis.client.SentinelClient "CLIENT_CLASS": env('DJANGO_CACHE_CLIENT_CLASS'), "SENTINELS": SENTINELS, "SENTINEL_KWARGS":{'password':env('REDIS_PASSWORD_VALUE')}, 'PASSWORD': env('REDIS_PASSWORD_VALUE'), "CONNECTION_POOL_CLASS": "redis.sentinel.SentinelConnectionPool", }, "KEY_PREFIX": "mapsvc" } } this is my settings.py. and my environment is on the kubernetes cluster and the redis-sentinel is the just node can access on the kubernetes cluster. I tried the connect to master in kubernetes pod. use this command redis-cli -h {master-ip} -p 6379 -a {password} and it works! but the django can't not connect to redis-sentinel. and it printed ERROR - create_cache: AUTH <password> called without any password configured for the default user. Are you sure your configuration is correct? the redis server version is 6.2.6. and django-redis version is 5.2.0. and I also tried without "CONNECTION_POOL_CLASS": "redis.sentinel.SentinelConnectionPool",settings in settings.py. please … -
How to use correctly types for Django model fields with django stubs?
Consider the following code fragment related to Django models: class Machine(HasStatus): # type: ignore machines: "models.Manager[Machine]" = models.Manager() number = models.IntegerField(verbose_name="Číslo stroje", unique=True) #Type of "number" is "IntegerField[Unknown, Unknown]" class Meta: #"Meta" overrides symbol of same name in class "HasStatus" verbose_name = "Machine" I was able to find out how to annotate Manager, but I don't know how to satisfy PyLance for model fields and Meta class. For the model fields, it seems I need to provide two types, but I have no idea which is the second. Please, provide examples of how to use type annotation for more Django model fields like ForeignKey and others. -
Django MSSQL query better way to fetch 100k records
I have a MSSQL database from where i need to fetch the records of about 100k. Then this record is shown in the dashboard and each operation in record is saved to the postgres DB which is the main DB of django. What is the best way to fetch the MSSQL server records, fetching everytime 100k records or is there is any way to store the query results to speed up the dashboard data view. -
Find Wagtail rootpage in users language
I have setup 2 rootpages according to https://wagtail.org/wagtail-localize/ English and Dutch For my menu system I have: {% get_site_root as site_root %} {% top_menu parent=site_root calling_page=self %} Which calls @register.simple_tag(takes_context=True) def get_site_root(context): return Site.find_for_request(context["request"]).root_page But it's always returning the Dutch root page. And when I'm on english it's not returning the english rootpage. Any ideas? -
control the empty data in django filter
I was coding the backend using Django. I am a beginner in Django. I used a filter to filter some post requests from the HTML form. here is the code. @api_view(["POST"]) def program_search(request): Data_List = [] MyFilter = CreateProgram.objects.filter(price__lte=request.POST['price'], days=request.POST['days']).values() ... but if I send a request from HTML form that one field of data be null the filter function cant handle it. -
Does a Django Model Serializer need performance tuning?
Is a Django serializer doing things like .only() on the same fields that are specified in the Serializer Meta: fields attribute or do I have to do it manually like saying in my view: def get_queryset(self) return SomeModel.objects.only('my_field_on_serializer') ? -
Django duplicate file to all the records with M2M which is self referencing
I have a Serializer & APIview where i upload a file it should be uploaded to other related records as well. class Record(models.Model): name = models.CharField(max_length = 122) related_records = models.ManyToManyField('self', null = True) class RecordDocument(models.Model): record = models.ForeignKey(Record, related_name = 'documents', null = True, blank= True ) file = models.FileField(max_length=255, blank=True, null=True) class RecordDocumentSerializer(serializers.ModelSerializer): save_documents_to_related_records = serializers.BooleanField() class Meta: model = RecordDocument fields = ( 'upload_to_related_cases', 'file' ) class RecordDocumentUploadView(APIView): def post(self, request, *args, **kwargs): 'how do i get serializers field **save_documents_to_related_records** and save the file on **related_records** which is not used in serializer till now if there are any inside it' -
DRF Invalid pk object does not exist for foreign key on POST create
I have two classes related to each other. One class I have made the primary key a char field so I can easily reference to it or create it to match the id of the actual object (all objects will have this unique name). from django.db import models class Ven(models.Model): id = models.CharField(max_length=80, primary_key=True) statusOn = models.BooleanField(default=True) class Device(models.Model): device_id = models.CharField(max_length=80) ven_id = models.ForeignKey(VEN, related_name='devices', on_delete=models.SET_NULL, null=True) class DeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = ['id', 'device_id', 'ven_id'] class VENSerializer(serializers.ModelSerializer): class Meta: model = VEN fields = ['id', 'statusOn', 'devices'] class DeviceList(generics.ListCreateAPIView): logger.info("DeviceList: view") # permission_classes = [permissions.IsAuthenticated] queryset = Device.objects.all() serializer_class = DeviceSerializer however when I try to run my test: class DevicesTestCase(TestCase): def setUp(self): self.factory = Client() def test_create_device(self): device = { "ven_id": "TEST_VEN_1", "device_id": "TEST_DEVICE_1", "statusOn": True, } response = self.factory.post('/devices/', data=device) self.assertEqual(response.status_code, 201) my response returns 400 and states: b'{"ven_id":["Invalid pk \\"TEST_VEN_1\\" - object does not exist."]}' I'm trying to write a custom create in my serializer to create the ven if it does not exist but it's not being called. Data is being validated else where. My breakpoint in my view set's perform_create also does not fire. I don't want to write a … -
How to serialize data more efficiently in Django Rest Framework?
So guys, part of my problem is solved by the question: #72534250 I understood that the path I was following was wrong, and I should change the optimization of the models to serializers and/or viewsets. But how? I had this structure: *I already removed element_name and element_text from Models Foo class User(models.Model): name = models.CharField(max_lenth=50) age = models.IntergerField() class Customer(models.Model): user = models.ForeingKey(User, on_delete=models.CASCADE, verbose_name='User') class Element(models.Model): name = models.CharField(max_lenth=50) text = models.TextField() class Bar(models.Model): element = models.ForeingKey(Element, on_delete=models.CASCADE, verbose_name='Element') class Foo(models.Model): bar = models.OneToOneField(Bar, on_delete=models.CASCADE, verbose_name='Bar') customer = models.ForeingField(Customer, on_delete=models.CASCADE, verbose_name='Customer') is_active = models.BooleanField('Is Active', default=False) def user(self): return self.customer.user # Removed def element_name(self): return self.bar.element.name # Removed def element_text(self): return self.bar.element.text And these serializers: class UserSerializer(ModelSerializer): class Meta: model = User fields = '__all__' class CustomerSerializer(ModelSerializer): class Meta: model = Customer fields = '__all__' class ElementSerializer(ModelSerializer): class Meta: model = Element fields = '__all__' class BarSerializer(ModelSerializer): element = ElementSerializer() class Meta: model = Bar fields = '__all__' class FooSerializer(ModelSerializer): bar = BarSerializer() user = UserSerializer() class Meta: model = Foo fields = '__all__' And this viewset: class FooViewSet(ModelViewSet): serializer_class = FooSerializer permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] http_method_names = ['get', 'post', 'patch'] def get_queryset(self): active = self.request.query_params.get('is_active', False) … -
Django multitenant migration raises KeyError: "prune"
So I've been working in a project for a while, and haven't really changed the models at all, and therefore haven't done any migrations. Now I needed to add two new fields and delete another one, which should be normally fine. I'm using django-tenants, so my command to run the migrations is ./manage.py migrate_schemas. Now, whenever I run that, I get the error KeyError: "prune" (the full traceback is below) in what seems to be internal code of Django. Now, afterwards I tried reverting my changes, so no new migration and running the comnad again, and got the same error. I also thought that maybe the database had gotten "dirty" at some point, so I tried migrating a clean database from scratch, with the same result. The migrations don't even get to start. Has anyone ever encountered something similar? The full traceback (I have simplified the paths) [standard:public] === Starting migration Traceback (most recent call last): File ":directory/./manage.py", line 22, in <module> main() File ":directory/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "$venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "$/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "$venv/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "$venv/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = … -
Why am I getting the error: "cannot read properties of null (reading "style") when I try to integrate Plaid link in JS?
My relevant code is as follows function useLink(token){ const handler = Plaid.create({ token: token, onSuccess: (public_token, metadata) => {}, onLoad: () => {}, onEvent: (eventName, metadata) => {}, recievedRedirectUri: window.location.href, }); } But everytime I try to use my link token to pull up link on the frontend, I get the following error from link-unitialize.js: Uncaught TypeError: Cannot read properties of null (reading 'style') I checked the Plaid website and couldn't find this listed as a common error, so I must be doing something very wrong. What is the most likely cause of this? -
Django - how to set user permissions after login via LDAP?
I'm starting a project in Django and I've already managed to get ldap authentication working, with django-auth-ldap. Now, I want that after the user logs in, django checks if this user exists in certain tables of my models, and if it does, give these users permission to access certain apps. For example, I have an app called 'alimentacao'. Only users registered in my model 'alimentacao.alunos' will be able to access "http://meu-projeto/alimentacao" As the user is created automatically if it doesn't already exist in the user model, I believe I would have to create a custom ldap authentication backend and check, after successful login, if the user exists in the table, and then set the permission to user. Neither the Django nor the django-auth-ldap documentation clearly explains how to create an authentication backend: in which folders the files need to be created, or how the application will call my custom method, or if I need to change any settings. I'm completely lost. -
using hyperlink inside a TextField
If one of my description model objects is being read as "This is a test". How do I attach a hyperlink to "test"? As in, when someone clicks on it, it takes them to test.com model description = models.TextField() admin class TestDescription(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': TinyMCE()}, } -
Django, how to get Choices human friendly text for a choice value with no model instance
Firstly yes I know about get_FOO_display(). It's great if you have a model instance, I don't in my situation. Im sure every django user at some point wonders why Django uses tuples instead of a dict to define the choices, but anyways, I have this model: class Review(models.Model): PENDING = '' APPROVED = 'A' DECLINED = 'D' SKIPPED = 'S' RESULT_CHOICES = ( (PENDING, 'Pending'), (DECLINED, 'Declined'), (APPROVED, 'Approved'), (SKIPPED, 'Skipped'), ) result = models.CharField('result', max_length=1, choices=RESULT_CHOICES, blank=True, default='') Now I don't have a model instance, but I do have a value, e.g. A, or D. How do I get the matching text value, i.e. Approved, or Declined etc. I could build a dict, and then look up the value, but surely theres a more "Built in django" way? Not looking for this kind of hammer approach: human_friendly = [ PENDING: 'Pending', DECLINED: 'Declined', APPROVED: 'Approved', SKIPPED: 'Skipped', ]['A'] -
How do I apply Django middleware everywhere except for a single path?
I'm using Python 3.9 with Django 3. I have defined this middleware ... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'directory.middleware.extend_token_response.ExtendTokenResponse' ] However, I don't want the middleware to apply to a certain URL. I have hard-coded this in the middleware like so class ExtendTokenResponse: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) if request.path != '/' + LOGOUT_PATH: # Code to be executed for each request before # the view (and later middleware) are called. is_expired = True try: token = request.auth print("req path: %s" % request.path) is_expired = is_token_expired(token) if token else True except Exception as err: print(err) if not is_expired: but this seems a little sloppy and I would think the middleware comes with somethign out of the box to configure that this wouldn't need to be applied to my "/logout" path. Is there a more elegant way to configure this? -
With Django pagination my tables pages isn't same as the first page
I'm using pagination for my table in Django. In every page 8 rows of my table is showing. But when I go to second page its height and width isn't the same. All table cells height and width is changing. How can I fix this? My html: (a simple table) <table class="table" border=1> <thead> <tr> <th>Full Name</th> <th>Company</th> <th>Email</th> <th>Phone Number</th> <th>Note</th> <th>ID</th> </tr> </thead> <tbody> {% for customer in customers %} <tr> <td>{{customer.full_name}}</td> <td>{{customer.company}}</td> <td>{{customer.email}}</td> <td>{{customer.phone_number}}</td> <td>{{customer.note}}</td> <td>{{customer.id}}</td> </tr> {% endfor %} My View class TableView(ExportMixin, SingleTableView): model = Customer table_class = CustomerTable template_name = 'pages/user_page.html' context_object_name = 'customers' paginate_by = 8 My Css .table{ margin-top:60px; position: fixed; top:250px; left:100px; bottom:250px; right:100px; width:900px; margin-left: 230px; }