Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create a Pagination with if and for loop django
I tried to do Pagination using for and if and it didn't work So how do I do that this an image that can show u front page image page 2 image front page code {% for post in posts %} {% if forloop.counter <= 2 %} <div style="background-color: #9999;" class="card mb-3" style="max-width: 100%;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="{% url 'post_detail' post.slug %}"><img style="height: 200px; width: 330px;" src="{{ post.mainimage.url }}" class="card-img" alt="..."></a> </div> <div class="col-md-6" id="ph"> <div class="card-body"> <h5 class="card-title">{{ post.title }} , {{ post.xnumber }}</h5> <p class="card-text">{{ post.version }}</p> <p>{{ post.category }}</p> <p class="card-text"><small class="text-muted">{{ post.date_added }}</small></p> </div> </div> </div> </div> <hr > {% endif %} {% empty %} <div class="notification"> <p>No posts yet!</p> </div> {% endfor %} page 2 code {% for post in posts %} {% if forloop.counter2 <= 30 %} <div style="background-color: #9999;" class="card mb-3" style="max-width: 100%;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="{% url 'post_detail' post.slug %}"><img style="height: 200px; width: 330px;" src="{{ post.mainimage.url }}" class="card-img" alt="..."></a> </div> <div class="col-md-6" id="ph"> <div class="card-body"> <h5 class="card-title">{{ post.title }} , {{ post.xnumber }}</h5> <p class="card-text">{{ post.version }}</p> <p>{{ post.category }}</p> <p class="card-text"><small class="text-muted">{{ post.date_added }}</small></p> </div> </div> </div> </div> <hr > {% endif %} {% empty … -
Map integration not wokring
The following are the two lines I put in the head tag of my html <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyC_Ii8L8wy40S8pB-eUBg13MlIOGYHXx6Y"></script> <script src="{% static "js/mapscript.js" crossorigin="anonymous" %}"></script> The below is the script I use to load map into my html. In my html I have a div tag with ID equal to map_canvas. var map; function initialize() { console.log("Loading map"); var mapOptions = { zoom: 12, center: new google.maps.LatLng(55.85361568022353, -4.288761402220929) }; map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions); } google.maps.event.addDomListener(window, 'load', initialize); The issue is that even if I added a API key and have a billing registered for google maps, map is not rendering after using the code above though this javascript code is hit. Can anybody give suggestions? -
AttributeError at /accounts/register/ Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'
i am having this issue when registering user through a register.html template this is the exact issue AttributeError at /accounts/register/ Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser' i created a custom user model and a custom manager which is listed here models.py file from django.contrib.auth.base_user import AbstractBaseUser from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager, PermissionsMixin from datetime import datetime from Etesting.settings import USE_I18N from django.utils import timezone from django.utils.translation import gettext_lazy as _ # Create your models here. class MyCustomUserManager(BaseUserManager): def create_user(self, email,username, password=None, **extra_fields): if not username: raise ValueError('There must be a username') if not email: raise ValueError('There must be an email') user=self.model( email=self.normalize_email(email), username=username, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password,**extra_fields): extra_fields.setdefault('is_admin',True) extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) return self.create_user(email, username, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): username=models.CharField(max_length=50, unique=True) email=models.EmailField(verbose_name='email', unique=True) first_name=None last_name=None is_admin=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) is_superuser=models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) USERNAME_FIELD='email' REQUIRED_FIELDS=['username'] objects = MyCustomUserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): """ Return True if the user has the specified permission. Query all available auth backends, but return immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have … -
ModuleNotFoundError: No module named 'pip._vendor.six'
I am doing some example from the book called Django for professionals. I am at the part where you have to run the django server with docker-compose command. However, I got an error like this: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) I realised that I needed to download psycopg2 with pip3 but then I got this error: from pip._vendor.six import iteritems ModuleNotFoundError: No module named 'pip._vendor.six' I don't understand why I received this error since I followed every step on the book carefully. I am using virtualenv as well so i decided to open a new terminal and downloaded it there. Download was a success however when I download it in virtual environment I get an error. What do you guys think is the problem and how can I solve it? -
Django comments - 'str' object has no attribute '_meta'
I am trying to implement a comment and reply system to my article application but I am receiving the following error: AttributeError: 'str' object has no attribute '_meta' Could you please let me know what am I doing wrong and how to fix this? I checked some answers but they were not related to this particular library. article_page.html {% extends 'base.html' %} {% load i18n %} {% load comments comments_xtd static %} {% block articleactive %}active{% endblock articleactive %} {% block body %} <div class="container"> <h1 class="py-3">{{ article.title }}</h1> <p>{{ article.content | safe }}</p> <br> <p class=" text-muted">{{ article.author }} | {{ article.date_published }}</p> <div class="container-fluid mt-4 comment-form"> {% render_comment_form for page %} </div> {% get_comment_count for page as comment_count %} {% if comment_count %} <hr> <div class="container-fluid mt-4 media-list"> {% render_xtdcomment_tree for page allow_feedback show_feedback %} </div> {% endif %} </div> {% endblock body %} setting.py INSTALLED_APPS = [ 'django_comments_xtd', 'django_comments', 'product', 'article', 'jazzmin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'crispy_forms', 'taggit', 'axes', 'django_otp', 'django_otp.plugins.otp_totp', 'django.contrib.sites' ] COMMENTS_APP = "django_comments_xtd" COMMENTS_XTD_CONFIRM_EMAIL = False # Set to False to disable confirmation COMMENTS_XTD_SALT = b"es-war-einmal-una-bella-princesa-in-a-beautiful-castle" COMMENTS_XTD_FROM_EMAIL = 'noreply@example.com' COMMENTS_XTD_CONTACT_EMAIL = 'helpdesk@example.com' COMMENTS_XTD_MAX_THREAD_LEVEL = 1 # Default value COMMENTS_XTD_LIST_ORDER = ('-thread_id', … -
from . import views ImportError: attempted relative import with no known parent package
i just start to use django, and i got error when try to import in the "from . import views" part, this is my code from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home') ] and i have error message, which is "ImportError: attempted relative import with no known parent package" can you show why it error, and the solution -
Exclude true Booleans from the List of Booleans
I am building a Blog App and I am trying to make a list accordingly of All Boolean Fields of a Profile Model and I am trying to exclude them if Boolean is true. And I successfully created a list But exclude is not working in list for exclude true Booleans models.py class Profile (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) first_boolean = models.BooleanField(default=False) second_boolean = models.BooleanField(default=False) third_boolean = models.BooleanField(default=False) views.py def page(request): Booleans_List = [] Booleans_Lista.append(request.user.profile.first_boolean) Booleans_Lista.append(request.user.profile.second_boolean) Booleans_Lista.append(request.user.profile.third_boolean) context = {'Booleans_List'} return render(request, 'page.html', context) This List is working Fine, But I am trying to exclude Booleans which are true and also I am trying use .first() in list. But I have no idea, how can I do it. Any help would be greatly Appreciated. Thank You in Advance -
Tastypie: The format indicated had no available deserialization method
I'm trying to send some zip files and some json data to a tastypie endpoint. Resources.py class MultipartResource(object): def deserialize(self, request, data, format=None): try: if not format: format = request.META.get('CONTENT_TYPE', 'application/x-www-form-urlencoded') if format == 'application/x-www-form-urlencoded': return request.POST if 'multipart' in format: data = request.POST.copy() data.update(request.FILES) zip = TestZipModel() zip.ADB = request.FILES['ADB'] jsonData = request.body.decode('utf-8') body_data = json.loads(jsonData) zip.save() return data except Exception as e: print("Error {}".format(e)) return super(MultipartResource, self).deserialize(request, data, format) # overriding the save method to prevent the object getting saved twice def obj_create(self, bundle, request=None, **kwargs): pass class ResponseZipRel(MultipartResource, ModelResource): class Meta: limit = 100000 queryset = TestZipModel.objects.all() resource_name = "ziprel" authorization = Authorization() Raspberry Pi which sends the files def sendLogs(): url = "http://43.197.102.4:8000/api/ziprel/" payload = {"param_1": "value_1","param_2": "value_2"} files = { 'json': (None,json.dumps(payload),'application/json'), 'ADB': (open('/home/pi/Desktop/ADB.zip','rb'),'application/zip')} r = requests.post(url,files=files) if __name__ == "__main__": sendLogs() I'm getting: {'error_message': "The format indicated 'multipart/form-data' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer.", I've tried setting the files to application/zip and application/octet-stream with no luck. I also tried sending the JSON as a parameter in the request, like this: r = requests.post(url,files=files, json={"testName": "test1", "testType": "thistestname"}) and got: Error 'utf-8' codec can't decode byte 0xdc … -
Django: It takes time for order_by() and count()
The following model object has about 300k rows in postgres, and I have set db_index=True for the published_at field. For some reason, order_by() takes a long time. (+100ms or so) Also, .count() takes a long time. (about 150ms). Why do these take so long even though the index is specified? class Video(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=300) thumbnail_url = models.URLField(max_length=1000) preview_url = models.URLField(max_length=1000, blank=True, null=True) embed_url = models.URLField(max_length=1000) embed_source = models.ForeignKey(EmbedSource, on_delete=models.CASCADE) duration = models.CharField(max_length=8) tags = models.ManyToManyField(Tag, blank=True, db_index=True) views = models.PositiveIntegerField(default=0, db_index=True) is_public = models.BooleanField(default=True) published_at = models.DateTimeField(default=timezone.now, db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ["-published_at"] def __str__(self): return self.title -
How to change the starting auto-generated-primary key id in a Django + PostgreSQL web application?
I have a web application build on Django using PostgreSQL database. In a few tables, I have auto-generated-IDs being used as primary keys. Due to some unexpected circumstances, I had to uninstall everything on the Linux server and again setup them on a different Linux server. I want to use all the data which I had stored earlier and taken dumps in csv files for each table before uninstalling. So, I've used copy function and and copied all columns data (including "id") into the new database. Now, when using the Django app which is trying to insert data into the tables, its throwing PRIMARY KEY ERROR saying that id already exists. So, what can I do now so that this Django+PSQL app uses id from some 1000 or 5000 rather than from 1 since the previous ones are already used? How to know this setup not to use 1 to 1000 as its already used. I don't think any screenshots are required for this. Kindly let me know if I have to make myself more clear. Thanks much in advance. -
Uncaught (in promise) Error: Network Error - Django and React
I am trying to make a axios get request to the backend built using DRF. I am getting the following error and the data does not load. import React, { useState, useEffect } from 'react' import Service from '../components/Service' import axios from 'axios' const ServicesScreen = () => { const [services, setServices] = useState([]) const [loading, setLoading] = useState(true) useEffect(() => { const getData = async () => { const { data } = await axios.get(`http://127.0.0.1:8000/api/services/`) setServices(data) setLoading(false) } getData() }, []) console.log(services) return ( <div> <Service header='Header' title='Carpenter' text='Text' /> </div> ) } export default ServicesScreen I have set the permissions at the backend in django settings. -
Is @transaction.atomic cheap?
This is mostly curiosity, but is the DB penalty for wrapping an entire view with @transaction.atomic a negligible one? I'm thinking of views where the GET of a form or its re-display after a validation fail involves processing querysets. (ModelChoiceFields, for example, or fetching an object that the template displays.) It seems to me to be far more natural to use with transaction.atomic() around the block of code which actually alters a bunch of related DB objects only after the user's inputs have validated. Am I missing something? -
Is Django blocking requests.post data in production platform?
From my Django webserver in production I have the below code snippet, where I am putting some data from an object into a postBody and posting the data to another server for it to be processed def sendOrderToRestaurant(session_id): order = Order.objects.filter(session_id = session_id).values() #Create a postBody and load the payload postBody = dict() postBody['order'] = order[0] postBody['order']['orderCreationDateTime'] = order[0]['orderCreationDateTime'].isoformat() postBody['order']['webhookDateTimePaymentReceived'] = order[0]['webhookDateTimePaymentReceived'].isoformat() #Extract the cartItems corresponding to the order session_id postBody['cartItems'] = list() cartItems = CartItem.objects.filter(cart_id = session_id) for item in cartItems: tmp = dict() tmp['quantity'] = int(item.quantity) tmp['productName'] = item.product.name tmp['productUnitPrice'] = float(item.product.price) tmp['DeliveryFee'] = float(item.restaurant.delivery_fee) tmp['bagFee'] = float(item.restaurant.bagFee) postBody['cartItems'].append(tmp) #Request post url = 'http://someservername.dk/submitOrder' response = requests.post(url, json = postBody, headers={"Content-Type":"application/json"}) return response.status_code, postBody I have verified in the log that postBody exists and have the right content that I expect. However when it was being posted to another server running on flask, nothing is received. @app.route('/submitOrder', methods = ['GET','POST']) def receiveOrder(): content = request.json logging.info('The received content') logging.debug(type(content)) logging.debug(content) #Print the content printKitchenThread = threading.Thread(target = printKitchen, args = (printer_ip, content,)) printKitchenThread.start() printHostThread = threading.Thread(target = printHost, args = (printer_ip, content,)) printHostThread.start() #Only print driver if it is a delivery if content['order']['delivery']: printDriverThread = threading.Thread(target = printDriver, … -
Name returning a number after serializing data
I have a table service : from django.db import models from users.models import CustomUser SERVICE_CHOICES = ( ('Carpenter', 'Carpenter'), ('Driver', 'Driver'), ('Ambulanve', 'Ambulanve'), ('Spa', 'Spa'), ('Barber', 'Barber'), ('Cleaning', 'Cleaning'), ('Cook', 'Cook'), ) class Service(models.Model): name = models.ForeignKey(CustomUser, on_delete=models.CASCADE, limit_choices_to={'is_worker': True},) service = models.CharField(choices=SERVICE_CHOICES,max_length=100) def __str__(self): return f'{self.service} - {self.name}' and a table CustomUser : from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): is_worker = models.BooleanField(default=False) is_customer = models.BooleanField(default=True) I am serializing the Service table below : from rest_framework import serializers from django.contrib.auth.models import User from .models import * class ServiceSerializer(serializers.ModelSerializer): class Meta: model = Service fields = '__all__' But when I add a service from the admin panel, the name shows a number in the browser and not the string. How do I change it to show a the name and not a number? -
Docker-compose (and django): Can't get environment variables onto the services
I'm trying to write a small docker(-compose) deployment solution for a small Django application. Currently, the django-compose file, named docker-compose.dev.yaml looks something like this: version: "3" services: backend: build: context: ./backend dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 env_file: - dev.env The file dev.env looks like this: DEBUG=1 SECRET_KEY=We9ZyuSKsP9Mgvsrt74gExF8baWbGL # not important that this leaks DJANGO_ALLOWED_HOSTS=localhost However, when django tries to start, I get the following: #11 0.634 ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") #11 0.634 AttributeError: 'NoneType' object has no attribute 'split' Basically, the environment variable is returning None, meaning the variables aren't getting onto the container. I tried, according to the docs, to do this: # ... environment: - DEBUG - SECRET_KEY - DJANGO_ALLOWED_HOSTS Without any luck. Any ideas? The repository behind the code is public, I invite you to try. My current test environment is Docker desktop on Windows 10. -
Apache server with django is saying: Access denied for user 'root'@'localhost'
I am trying to run a working Django server on Apache2. I've install and configured an Apache2 server with the following 000-default.conf: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin oreo@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog /home/chunao/WhiteBoard/error.log CustomLog /home/chunao/WhiteBoard/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # … -
How to render choices in a Django field based on a condition
I have a custom user model: from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): is_worker = models.BooleanField(default=False) is_customer = models.BooleanField(default=True) def __str__(self): return f'{self.username} - {self.is_worker}' And I have this model services : from django.db import models from users.models import CustomUser SERVICE_CHOICES = ( ('Carpenter', 'Carpenter'), ('Driver', 'Driver'), ('Ambulanve', 'Ambulanve'), ('Spa', 'Spa'), ('Barber', 'Barber'), ('Cleaning', 'Cleaning'), ('Cook', 'Cook'), ) class Service(models.Model): name = models.ForeignKey(CustomUser, on_delete=models.CASCADE) service = models.CharField(choices=SERVICE_CHOICES,max_length=100) def __str__(self): return f'{self.service} - {self.name}' In services model, I am using CustomUser model for the name. Whereas, I need only those names where is_worker = True. In my code, I am getting all the users irrespective of the status. How can I change it? -
How can I get date like(07.11.2021 ) from date name like (Monday,Tuesday...)
I' developing a django project and in my template user can select a day.As shown as bottom picture. And after day select post request is working.And in my views.py I can get the day name.Like(Monday,Tuesday,...).Using this knowledge, I want to get date of this week.For example coming value of request is Wednesday and I want to get what date is Wednesday in this week like (03.11.2021) -
Django choice field as model ForeignKey in FormSet
I have models which is Player and Position. Player is associated with position player is currently at. You can assign a player new position, which is why I need it to use it in some form. But in that form I see that Position is position Object (see image bellow), but I would like to put "Position.name" in there to see the name of choices instead that object, but I have no Idea how to do it. Thank you for your help. models.py class Position(models.Model): name = models.CharField(max_length=20) short = models.CharField(max_length=2) class Players(models.Model): name = models.CharField(max_length=200) positionId = models.ForeignKey(Position, on_delete=models.CASCADE, null=True, blank=True) forms.py class CompositionForm(ModelForm): class Meta: model = Players fields = ("positionId", ... many more ... ) table.html <table id="nominated-player-table" class="table table-bordered" style=""> {% for form in formset.forms %} {% if forloop.first %} <thead> <td colspan="15" style="background-color: dimgray; color: white; border-top-right-radius: 15px; border-top-left-radius: 15px; border: none"> Nominovaní hráči </td> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr> {% for field in form.visible_fields %} <td> {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field }} </td> {% … -
CSS acting differently in localhost
I'm working on a project. So first, i started with front-end. And then after finishing that, i loaded all the files in django app and started the localhost. But suddenly everything seems to be bigger. Most of the padding, margin, font-size, changes from small to big 1.front end designed locally is the first image. 2.frond end after loading into localhost is the second image Why is this happening, is there any solution for this. Do I have to redesign all on the perspective of localhost AGAIN? -
Update profile picture through clicking on picture itself Django
I'm trying to find some info online on how to update my user's profile picture on the profile page in the same way that social media applications do it, i.e. by clicking on the profile picture itself and getting asked for the file upload straight away. However, all I'm finding online is options to create a form to do that job, but then it's going to be an upload button that does the job, which is not the same. How do I get the image to be clickable, opening a file upload after I click it that would then update my model ImageField? -
Understanding flaky Django tests: Creation order affecting array order
I have a test in Django that looks something like this: class WebhookClientSerializerTestCase(TestCase): def test_serializes_agent_from_client(self): agent1 = factories.AgentUserFactory(email='dave@agently.com') agent2 = factories.AgentUserFactory(email='jim@agently.com') client = factories.ClientFactory(agents=[agent1, agent2]) schema = serializers.WebhookClientSerializer() # do some stuff data = schema.dump(client).data self.assertEqual(data['agents'][0]['email'], 'dave@agently.com') self.assertEqual(data['agents'][1]['email'], 'jim@agently.com') We create a entity called an Agent, then another, and run through some custom serializer logic. The serializer returns an array of serialized agent data. There are other tests defined within the same class. However, sometimes the agents come out in the wrong order. It fails with AssertionError: u'jim@agently.com' != 'dave@agently.com' I had assumed that when the entities were created, that it would be done sequentially. This test runs fine locally, but it fails in CI/CD sometimes, not always. We use the --parallel flag when running tests, but I don't see where or how the asynchronicity is messing with the order of the output array. Why does the order change, and how could I write this test more robustly? -
save() method for django_comments_xtd model
I am using Wagtail + Django_comments_xtd + Django. My_Django_App/models.py from wagtail.core.models import Page class PostPage(Page): ... from django_comments_xtd.models import XtdComment class PostComment(XtdComment): page = ParentalKey('PostPage', on_delete=models.CASCADE, related_name='rn_comments') def save(self, *args, **kwargs): if self.user: self.user_name = self.user.username self.page = PostDetail.objects.get(pk=self.object_pk) super(PostComment, self).save(*args, **kwargs) On Wagtail CMS, if I revise an existing post which has some comments already and publish the revised post again, I thought PostComment.save() should not be triggered any more. However, during my debug, I found it was triggered unexpectedly. I guess that I need to fine-tune PostComment.save() to achieve above intention. After some researches on StackOverflow, Identifying new Model Instance in Django Save with UUID pk In a django model custom save() method, how should you identify a new object? I realize that I might need to use PostComment._state.adding and force_insert within the save() to achieve my intention. Can anyone show me how should I fine-tune PostComment.save() ? -
django-filter: How to get the choices from related model?
Im trying to create a filter, and get the choices from the related model. Is it possible? My models: class Container(models.Model): description = models.CharField(max_length=255) class Period(models.Model): class PeriodType(models.TextChoices): LONG = 'long', 'Long period' SHORT = 'short', 'Short period' container = models.ForeignKey(to=Container, null=True, blank=True, on_delete=models.SET_NULL) type = models.CharField(max_length=15, choices=PeriodType.choices, null=True, blank=True) My viewset: class ContainerFilter(django_filters.FilterSet): type_of_period = django_filters.ModelChoiceFilter(Period.objects.all(), field_name='period__type', label='Type') class Meta: model = models.Container fields = ['type_of_period',] class ContainerModelViewSet(viewsets.ModelViewSet): queryset = models.Container.objects.all() lookup_field = 'id' filter_backends = [filters.SearchFilter, django_filters.rest_framework.DjangoFilterBackend] search_fields = ['description',] filter_class = ContainerFilter -
Django caches user object
Our websites sometimes has around 600 authenticated users trying to register for an event in a timeframe of 5 min. We have a VPS with 1 CPU and 1GB ram. On these moments the site slows down and gives a 502 error. For that reason I'm using per-site cache with FileBasedCache. This works excellent and stress tests work fine. But, when people login, they're redirect to their profile. This is the code: class UserRedirectView(LoginRequiredMixin, RedirectView): permanent = False def get_redirect_url(self): return reverse("users:detail", kwargs={"membership_number": self.request.user.membership_number}) the user is redirect to an url with their membership_number class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = "membership_number" slug_url_kwarg = "membership_number" Some users are reporting that they are redirected to someone else his/her profile after logging in. How does this work? How to prevent user specific parts of the website to be cached? e.g. users also see a list of events that are specific to the groups they are in. In other words, every user should see a different list. Any ideas? Best practices?