Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Storing Base64 instead of UUID in Postgres
Can I store it in a string field. Basically, I will generate a unique id using uuid function and then convert it to base64 that looks like in google then store that in the database. I'm planning to use cassandra in the future so I'm not sure if there's a performance hit if I'll use string as primary key there. I just want to know what's the best practice for this. Thank you. -
Not able to insert data into database
This is an excerpt of my view.py def routineInput(request): if request.method == 'POST': today = datetime.now form = CreateRoutine(request.POST) if form.is_valid(): return HttpResponseRedirect('/todo/saved/') else: form = CreateRoutine() return render(request, 'todo/croutine.html', {'form': form}) So the idea is that I have a simple input form where I put a name into it and it should push this name into a table in my database. My code is coming thorough and it shows my /todo/saved page but my POST request doesn't seem to get sent to my table or my table is rejecting it or something. -
'User' object is not iterable in Django 1.11.8
I have a model that have a ManyToManyField for users, and I want to record logged in user when he/she submits the form in Choice model, but this code is stopping me from doing so. I used the login_required decorator to force user to login first (that's what I want actually). models.py: from django.db import models from django.contrib.auth.models import User QUESTION_CHOICES = ( ("choice_1", "Choice 1"), ("choice_2", "Choice 2"), ("choice_3", "Choice 3"), ) class Choice(models.Model): users = models.ManyToManyField(User) choices = models.CharField(max_length=256, choices=QUESTION_CHOICES, unique=True) vote = models.IntegerField(default=0) def __str__(self): return self.choices + " " + "-" + " " + str(self.vote) views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Choice @login_required def index(request): food = request.POST.get('sunday') user_v = None get_choices = Choice.objects.values('choices', 'vote') new_choices = list(get_choices) for q in new_choices: choice = q['choices'] vote_v = q['vote'] if food: if food == choice: if request.user.is_authenticated(): user_v = request.user print(user_v) # it prints out correctly after sucessful form submit vote_v += 1 model_conn = Choice.objects.get(choices=choice) model_conn.vote = vote_v model_conn.users = user_v # this is where I get an error model_conn.save() return render(request, 'index.html', {}) -
Django RF update_or_create
I am trying to update or create the following model: class Profile(models.Model): user = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE) canMakeEvent = models.BooleanField(default=False) with the serializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' and view: def post(self, request): answer, created = Profile.objects.update_or_create( user=request.user, canMakeEvent = request.data['canMakeEvent']) return Response() I understand the response isn't correct but the code to update_or_create is what I'm worried about primarily. The console outputs the following: UNIQUE constraint failed: event_profile.user_id -
How can I apply for loop in django template for creating array of same images?
I am in need of code in django template without javascript to display the length of same images based on number of votes. My current code is this: <div id="Results"> <h1>{{question.question_text}}</h1> {% for choice in question.choice_set.all %} <div id="votes"><img style="border-radius: 2px; border-width: 2px; border-style: none solid solid none; border-color: darkblue;" src='{{choice.image2.url}}'/> <div style=" float: right; width: 88%;"> <b>{{choice.choice_text}}</b> {{choice.votes}} vote{{choice.votes|pluralize}} </div> </div> {% endfor %} </ul> <p id="info">Your Vote Has Been Stored!!</p> <br> </div> Help me generate code with algorithm: increment for loop based on choice.votes. //for loop from i=0; i<{{choice.votes}}; i++ display of some image in array. // some image -
How to use models app in another app in django?
I'am looking a solution in my case. I have a website witch contains the main app calling 'bajki'. I've create a 2nd app calls 'ustawienia'. In 'ustawienia' I want to changing the thinks in <head> and footer section like: title, meta description, name of footer(like standard settings in populars cms). So I've create a class in models.py in 'ustawienia' app: # -*- coding: utf-8 -*- from django.db import models class Ustawienia(models.Model): title = models.CharField(max_length=75, verbose_name="Tytuł strony(title)") description = models.TextField(max_length=280, verbose_name="Opis META(description)") logo = models.CharField(max_length=150, verbose_name="Nazwa LOGO") footer = models.TextField(verbose_name="Opis stopki") class Meta: verbose_name = "Ustawienia Strony" verbose_name_plural = "Ustawienia Strony" def __str__(self): return self.title After I want to import models to main app calls 'bajki' In app 'bajki' views.py I've create: from ustawienia.models import Ustawienia def ustawienia(request): ustawienia = Ustawienia.objects.all() context ={'ustawienia': ustawienia,} return render(request, 'bajki/index.html', context=context) And in main app 'bajki' I created a url in urls.py from django.urls import path from bajki import views urlpatterns = [ path('', views.ustawienia, name="ustawienia"), ] In project url I've create something like : from django.contrib import admin from django.urls import path, include urlpatterns = [ ... path('', include('ustawienia.urls')), ] On the end I want to show in <head> section the site title … -
perform_destroy() in ManyToMany for selected models to remove() _ Django Restframework
suppose we have Model A. Model A has ManyToMany relation with model B.I need to delete selected object deleted in ManyToMany. models.py class B(models.Model): ...... class A(models.Model): title = models.Charfield(....) subscription = Models.ManyToManyField(B, related_name="subscribers", blank=True) Views.py class SubscribeAView(RetrieveUpdateDestroyAPIView): queryset = A.objects.all() serializer_class = ASerializer def perform_destroy(self, instance): subscribe = instance.subscription subscribe.remove() this method will delete all relations.but I need to tell delete the selected subscription from request.user -
Django: Pass GET argument to password rest email
I'm fairly new to django and I'm currently rewriting the django login views so I can move all the authentication process to a dedicated django app where I can redefine the templates. So currently I have an accounts app which url.py looks like that: from django.contrib.auth import views as auth_views from django.urls import path from . import views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.login, {'template_name': 'accounts/login.html'}, name='login'), path('logout/', auth_views.logout, name='logout'), path('password_reset/', auth_views.password_reset, {'template_name': 'accounts/password_reset_form.html', 'email_template_name': 'accounts/password_reset_email.html', 'subject_template_name': 'accounts/password_reset_subject.txt', 'post_reset_redirect': 'done/'}, name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='accounts/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.password_reset_confirm, {'template_name': 'accounts/password_reset_confirm.html', 'post_reset_redirect': '/accounts/reset/done/'}, name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view( template_name='accounts/password_reset_complete.html'), name='password_reset_complete') ] And a accounts/password_reset_email.html which looks like this: {% autoescape off %} To initiate the password reset process for your {{ user.get_username }} account, click the link below: {{ protocol }}://{{ domain }}{% url 'accounts:password_reset_confirm' uidb64=uid token=token %}?origin_page={{ origin_page }}" ... Sincerely, The Team {% endautoescape %} What I want to do is to recover the origin_page argument so when the user click on the reset link from the email he get redirected to the right webpage after his password is reset. So far I tried to do this in password_reset_form.html: {% block content %} <p>Forgotten your password? Enter your email address … -
Django Rest Framework: Angular (Ionic) vs Postman requests validation error
I'm writing an app with Ionic and a server API with DRF. I want to create objects but make sure the user has one active instance of this object (in the model there is a boolean: done; see the serializer, it will make sense :) ). I have a postroute setup to create objects using generic views (Don't mind the custom permission). class WaitercallCreate(CreateAPIView): serializer_class = WaitercallCreateSerializer permission_classes = (IsAuthenticated, IsOrderOwnerAndFresh) In the serializer of the object there is a validate method: class WaitercallCreateSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.email') waitercall_id = serializers.ReadOnlyField(source='pk') class Meta: model = Waitercall fields = ('waitercall_id', 'order', 'user', 'done') read_only_fields = ('waitercall_id', 'user', 'done') def validate_done(self, value): qs = self.context['request'].user.waitercalls.exclude(done=True) if qs.exists(): raise serializers.ValidationError("There is already a pending waitercall for this user!") return value Now when I call the route using Postman, everything works as expected. The first creation comes through. If I hit the route and the done boolean hasn't been set to true by the other operations of the server, I get the correct validation error message. But, when I implemented the function in my app and called the route multiple times, the server creates an object for each call. Here is my function: makeWaitercall(type) { … -
Basic Entity Management System
How can I design an Entity Management system in Django which can be able to adapt to any kind of entity with minimal code changes (e.g. a product in a catalog, patient information in healthcare etc.). Adding, removing, modifying the attributes of an entity should be simple It should allow for nested attributes (sub-entities) e.g Patient -> Consulting doctor Each attribute or sub-entity in the entity can have a set of business rules -
Django rest framework - DefaultRouter - One-to-One Nested Relationship
I need to represent a nested RESTful resource via Django Rest Framework. I have a two Django models: User and Profile, with a 1 to 1 relationship between them. I want to expose the following API structure: GET /api/users/<user_pk>/ PATCH /api/users/<user_pk>/ And also endpoints that deal with the user's profile, such as: GET /api/users/<user_pk>/profile/ PATCH /api/users/<user_pk>/profile/ Another constraint, is that I would like to use drf DefaultRouters, in order to keep the overall project implementation homogeneous, but I got aware that DefaultRouters only provides not satisfactory approaches, for instance: GET profile-list not needed, since I need only one object, not a list; GET profile-detail /api/users/<user_pk>/profile/<profile_id>/ is non-sense to introduce the profile_id. So, what's the drf's DefaultRouter Best Practice, or better approach, for this 1to1 nested relationship? -
django(v2.0.1) -- _str_() method shows Object but not notes in self.text(python3.5)
My models.py is like this: enter image description here My python's version is 3.5.x and django's version is 2.0.1, and when I went to admin's page, I got this page: enter image description here -
How to update user profile in Django
I want to let my student to update his profile after he logged in, but I don't seem to be able to code the profile update properly. This is my code: class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) <form method="POST" action="{% url 'profile_edit' %}" class="" > {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button>q </form> def profile_edit(request): user = request.student form = StudentForm(request.POST or None, initial={'name': user.name, 'surname': user.surname}) if request.method == 'POST': if form.is_valid(): user.student.name = request.POST['name'] user.student.surname = request.POST['surname'] user.save() return HttpResponseRedirect('index') context = { "form": form } return render(request, "registration/profile_edit.html", context) -
Iterate over all Django App models if Meta.managed = True
I want a script that iterates over all models for a given app that are managed=True and deletes the data. My non-managed models are views, etc that I don't want to touch. I am doing the following. It works. I want to know if there is a better or more pythonic way to do the same thing. Would it be sensible to define other Meta options in each model if I want to include or exclude them in such a method? from django.apps import apps def deletedata(): if app.upper() in [x.verbose_name.upper() for x in apps.get_app_configs()]: appmodels = apps.get_app_config(app).get_models() for appmodel in appmodels: if appmodel._meta.managed: appmodel.objects.all().delete() def main(): deletedata("foo") if __name__ == "__main__": main() -
Cannot find which model is getting error in Django
I have following model and after Migrate, I tried to add data through Admin page. However, I got the error NOT NULL constraint failed: HVAC_chiller.basicinfo_ptr_id. Referring to other stackoverflow, I understood problem. However, I cannot find any model which has attribute ptr. Does anyone know which attribute I should revise? models.py class BasicInfo(models.Model): title = models.CharField(max_length=100) manufacturer = models.CharField(max_length=50, blank = True) used_project = models.CharField(max_length=50, null=True,blank=True) cost=models.IntegerField(null = True, blank = True) url=models.URLField(null=True,blank=True) comment=models.TextField(null=True,blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class VRV(BasicInfo): InletT = models.FloatField(blank=True) OutletT = models.FloatField(blank=True) Capacity = models.IntegerField(blank=True) # Reference capacity COP = models.FloatField(blank=True) # Reference COP class CapacityFunction(models.Model): name=models.CharField(max_length=100, blank = True) c1=models.FloatField() c2=models.FloatField() c3 = models.FloatField() c4 = models.FloatField() c5 = models.FloatField() c6 = models.FloatField() minX= models.FloatField(blank=True) maxX = models.FloatField(blank=True) minY = models.FloatField(blank=True) maxY = models.FloatField(blank=True) def __str__(self): return self.name class EIRofTemp(CapacityFunction): pass class EIRofPLR(models.Model): name = models.CharField(max_length=100, blank=True) c1=models.FloatField() c2= models.FloatField() c3 = models.FloatField() c4 = models.FloatField(blank=True,null=True) minX = models.FloatField(blank=True) maxX = models.FloatField(blank=True) def __str__(self): return self.name class Chiller(VRV): CONDENSER_CHOICES = ( ('WaterCooled','WaterCooled'), ('AirCooled', 'AirCooled'), ('EvaporativelyCooled','EvaporativelyCooled') ) Condenser=models.CharField(max_length=15,choices=CONDENSER_CHOICES,default='Water') CHWFlowRate=models.FloatField(blank=True,null=True) CWFlowRate=models.FloatField(blank=True,null=True) minPLR=models.FloatField(blank=True,null=True) maxPLR=models.FloatField(blank=True,null=True) optimumPLR=models.FloatField(blank=True,null=True) minUnloadRatio=models.FloatField(blank=True,null=True) CapacityFunction=models.OneToOneField(CapacityFunction,blank=True,null=True,on_delete=models.CASCADE,related_name='cap') EIRofTemp=models.OneToOneField(EIRofTemp,blank=True,null=True,on_delete=models.CASCADE,related_name='eirtemp') EIRofPLR = models.OneToOneField(EIRofPLR, blank=True,null=True, on_delete=models.CASCADE,related_name='eirplr') -
Unable to install latest version of Django using pip
I am trying to install latest Django version 2.0.1 as mentioned on https://www.djangoproject.com/download/ that this is the latest official release but when I run command pip install Django==2.0.1 I get error. Error is shown in Image below. How can I install latest version? -
django-markdown can not support bold or italic?
I use the django-markdown module to make the comments support the markdown, but there is a problem. The bold and italic are not supported. Others, such as pre, title and so on, work well. why? django user-define templatetags from django import template import markdown register = template.Library() @register.filter def markdown_change(content): content = markdown.markdown(content,extensions=['markdown.extensions.extra','markdown.extensions.codehilite','markdown.extensions.toc',]) return content template <p>{{comment.content|markdown_change|safe}}</p> views.py def contact(request): if request.method == 'POST': if request.user.username: form = CommentForm(request.POST) if form.is_valid(): form.save() form = CommentForm() comment_list = Comment.objects.all().filter(public = True).order_by('id').reverse() if len(comment_list) > 5: data,comment_list=comment_paginator(request,comment_list) else: data='' response = True context = {'form':form,'comment_list':comment_list,'response':response,'data':data} return render(request,'contact.html',context=context) else: form = CommentForm() comment_list = Comment.objects.all().filter(public = True).order_by('id').reverse() if len(comment_list) > 5: (data,comment_list)=comment_paginator(request,comment_list) else: data='' context = {'form':form,'comment_list':comment_list,'data':data} return render(request,'contact.html',context=context) -
How can I decouple my models?
Quick view: two Profile objects make up a Pair object. A Chat object has a FK to a Pair object and acts as the gateway to the chat-room between the two Profiles. A Message object references two Profile objects. Problem: My code is in such a way that the integrity of a site-feature is contingent on the objects of two models having matching Primary Keys. Given a model Pair(denoting a "pair" of Profiles), and model Chat(related_name="chat_room"), here is where I believe the coupling takes place: utils.py: def get_room_or_error(room_id, user): """ Tries to fetch a chatroom for a Pair(of users) object. """ if not user.is_authenticated(): raise ClientError("USER_HAS_TO_LOGIN") # Find the room they requested (by ID) try: room = Pair.objects.get(pk=room_id).chat_room # HERE except Pair.DoesNotExist: raise ClientError("ROOM_INVALID") if room.staff_only and not user.is_staff: raise ClientError("ROOM_ACCESS_DENIED") return room # the arg. being passed in, room_id, is the PK of a Pair object retrieved from a template And the models to provide background: user_profile.models.py: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='is_profile_to') class Pair(models.Model): requester = models.ForeignKey(Profile, related_name='is_requester') accepter = models.ForeignKey(Profile, related_name='is_accepter') chat.models.py: class Chat(models.Model): pair = models.OneToOneField(Pair, related_name='chat_room') class Message(models.Model): room = models.ForeignKey(Chat, related_name='messages', null=True) # Currently unused... recipient = models.ForeignKey(Profile, related_name='is_recipient', null=True) sender … -
Django Rest Auth with Facebook login?
I have seen a lot of answers online but never got any clarity about how to move forward. I have configured django-allauth and django-rest-auth as per the documentation and have also added appId and the accessKey from facebook as per the documentation. I don't understand what this error is all about? "non_field_errors": [ "Incorrect input. access_token or code is required." ] It works fine with the normal login. But what configuration am i missing to make it login via JWT tokens? -
How to save a ModelForm that has conditionally-declared fields in __init__ but not in the Meta class?
I have a ModelForm that I can't save properly: class FooForm(forms.ModelForm): foobar = forms.IntegerField(required=True) def __init__(self, *args, **kwargs): baz = kwargs.pop('baz', None) super(FooForm, self).__init__(*args, **kwargs) if baz: self.fields['baz'] = forms.IntegerField(required=False) class Meta: model = FooBar fields = ('foobar',) Running the debugger when I try to save shows that baz is present in fields and cleaned_data, but unless I declare it in the Meta.fields then it doesn't save this field. How do I proceed in this situation? I don't know if I need baz in my fields until the form in initialized - how can I express this condition in the Meta class? -
traefik + nginx + django with docker
I try to deploy a Django server with Gunicorn and Nginx (for static files). When I test the Nginx server without traefik, all work fine. But when i put behind traefik, it give me a "Gateway Timeout" error. And I don't know why the link doesn't work between traefik and nginx... My config files : docker-compose.yml: version: '2' services: gunicorn: restart: always build: ./web links: - postgres:postgres - redis:redis volumes: - /usr/src/app - /usr/src/app/static env_file: .env expose: - "8000" environment: DEBUG: 'false' labels: - "traefik.enable=false" command: /usr/local/bin/gunicorn karibox.wsgi:application -w 2 -b :8000 nginx: restart: always image: nginx ports: - "80" volumes: - /www/static - ./nginx/sites-enabled/django_project:/etc/nginx/conf.d/mysite.template volumes_from: - gunicorn links: - gunicorn:gunicorn labels: - "traefik.backend=karibox" - "traefik.frontend.rule=Host:karibox.example.com" command: /bin/bash -c "envsubst '$$NGINX_HOST $$NGINX_PORT' < /etc/nginx/conf.d/mysite.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'" networks: web: external: name: traefik_webgateway Nginx sites enabled server { listen 80; server_name karibox.example.com; charset utf-8; location /static { alias /data/web/mydjango/static; } location / { proxy_pass http://gunicorn:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } log_format logi '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"'; -
create a list ordered by a queryset
views.py def appelli(request, corso_id): corsi = Corso.objects.filter( pk=corso_id) fasca = Corso.objects.get( pk=corso_id) appello=[ list(Iscrizione.objects.filter(corso1_id=fasca)), ...] return render(request, 'corsi/appello.html', {'appello':appello}) in the html use {{appello.0}} and I render this: [<Iscrizione: VFEW>, <Iscrizione: VFFF>] how can delete "Iscrizioni" and make a ordinate list? -
IntegrityError NOT NULL constraint failed on updating custom user in Django
I tried to create my own user model in Django. The user creation form work as properly but not when I tried to update it. When I tried to update a data by admin (for example in this case updating email) in Django administration it always return me an IntegrityError: NOT NULL constraint failed: accounts_user.password. Here is my UserAdmin: from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .forms import UserAdminPostForm, UserAdminUpdateForm from .models import User class UserAdmin(BaseUserAdmin): form = UserAdminUpdateForm add_form = UserAdminPostForm list_display = ('email', 'created', 'admin') list_filter = ('admin',) fieldsets = ( ('Account', {'fields': ('email', 'password')}), ('Profile', {'fields': ()}), ('Permissions', {'fields': ('active', 'staff', 'admin',)}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'staff', 'admin',)} ), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () admin.site.register(User, UserAdmin) And this is my Form: from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User class UserAdminPostForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password Confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email', ) def confirm_password(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def … -
Celery 4.1 on Django. Do I still need celerycam? Flower?
So, I am running celery 4.1 on Redis with the results being stored in postgresql. Celery is basically used as a backend to launch fire and forget batches from the web front end. A batch runs with some parameters and updates a database, no data is really returned back to the launching page, except a 200 or 202 status stating the batch was launched successfully. On Celery 3.1, I would never see TaskState in admin, unless celerycam was running. As I am putting through the Celery 4 through its paces, I do see TaskResults appear under /admin/django_celery_results/taskresult/ despite only running celery -A websec worker -l info. So, should I still use celerycam for something? Is Flower needed to replace it? I am hesitant about adding more moving parts to this configuration without a clear rationale/need for doing so. Yes, I won't be getting Flower's nice little status web pages and the like, but honestly I've been OK just with 3.1s TaskStates so far. -
Django Rest Framework - Throttling not working in development environment
I was writing tests for throttling when I found out that throttling doesn't seem to be working properly in development env (It seems to be working in production). None of the requests is getting throttled (anon and user). This is the REST settings. REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': ( 'rest_framework.pagination.LimitOffsetPagination'), 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_expiring_authtoken.authentication.ExpiringTokenAuthentication', ], 'TEST_REQUEST_DEFAULT_FORMAT': 'json', 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle', 'accounts.throttles.ResendEmailThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'anon': '100/minute', 'user': '100/minute', 'resend_email': '3/hour', }, 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } Weird thing I noticed was that when I kept the limit to 0/minute, it starts throttling the requests. This is the test code. class AccountThrottlesTestCase(BaseAPITestCase): def setUp(self): super(AccountThrottlesTestCase, self).setUp() def test_resend_email_throttles(self): url = reverse_lazy('accounts:resend_email') for i in range(0, 3): response = self.client.post(url) self.assertEqual(response.status_code, status.HTTP_200_OK) response = self.client.post(url) self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS) Throttles not working. FAIL: test_resend_email_throttles (tests.unit.accounts.test_throttles.AccountThrottlesTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/rustbucket/evalai/tests/unit/accounts/test_throttles.py", line 39, in test_resend_email_throttles self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS) AssertionError: 200 != 429 ---------------------------------------------------------------------- Ran 286 tests in 15.994s Why is the throttling behaving funny?