Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django markdown don't work in template
I'm using django markdown and no load in template, but if it works in django admin My Django version is 1.8.5 and django markdown latest I follow https://github.com/klen/django_markdown setup ( add django_markdown in settings and url is ok ) in model.py ( migrate is ok ) from django_markdown.models import MarkdownField class MyModel(models.Model): description = MarkdownField() python manage.py collectstatic is ok forms.py class BidForm(BaseBidForm, forms.ModelForm): class Meta: model = Bid fields = ('name', 'description') description = forms.CharField(widget=MarkdownWidget()) admin.py @admin.register(models.Bid) class BidAdmin(admin.ModelAdmin): formfield_overrides = {MarkdownField: {'widget': AdminMarkdownWidget}} template .html {% load django_markdown %} {% for field in form %} {% if field.html_name == 'description' %} <div class="col-md-7"> <div class="form-group"> <label for="{{ form.description.html_name }}">{% trans "Descripción" %} <span class="red">*</span> <small class="required">(obligatorio)</small></label><br> <textarea id="new" class="form-control {{ field.errors|yesno:'error,' }}" rows="3" name='{{ form.description.html_name }}' placeholder="{% trans "ejemplos" %}" value="{% if form.description.value %}{{ form.description.value }}{% endif %}"></textarea> {% markdown_editor "#new" %} {% markdown_media %} </div> </div> {% endif %} {% endfor %} -
Get the active logger in a management command
Django has good support for configurable logging, and for writing management commands. How, within a management command (i.e. a class inheriting from django.core.management.base.BaseCommand), can I get the active logger to modify its behaviour? What I want is to be able to specify, via a command-line parameter, the logging level to use for this invocation of a command. So that means I need: A new command-line parameter, --log-level. No problem, the BaseCommand.add_arguments method is where I do that. Access to the logger in use for this invocation of the command. This is what I don't know how to do. Modify the logger's logging level to that specified in the --log-level parameter. Do I do this using Python logging facilities, or Django-specific facilities? -
Django Installed App Error - No module named AgileInputConfigdjango.contrib
I have the Django Project Structure as follows and um including my app to INSTALLED_APPS as follows INSTALLED_APPS = [ 'agile_input.apps.AgileInputConfig' 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] once I run the migration um getting an error as ImportError: No module named AgileInputConfigdjango.contrib Um using the Django 1.9.1 . What could possibly go wrong here ? -
Django models class attribute and instance property?
I implement very simple hit-count models in Django. models.py from django.db import models from model_utils.models import TimeStampedModel from posts.models import Post class PostHit(TimeStampedModel): post = models.ForeignKey(Post, related_name='post_hits') num_of_hit = models.IntegerField() class Meta: verbose_name_plural = "Post hits" def __str__(self): return self.post.title def increase_hit(self): self.num_of_hit += 1 views.py from django.views.generic.detail import DetailView from django.core.exceptions import ObjectDoesNotExist from posts.models import Post, PostHit from posts.forms import CommentForm class PostDetailView(DetailView): model = Post def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) context['category'] = self.kwargs['category'] context['form'] = CommentForm() context['tracking_hit_post'] = self.tracking_hit_post() return context def tracking_hit_post(self): post = self.model.objects.get(pk=self.object.id) post_hit = PostHit.objects.filter(post=post).first() if post_hit: post_hit.increase_hit() else: post_hit = PostHit.objects.create( post=post, num_of_hit=1 ) print(post_hit.num_of_hit) return post_hit.num_of_hit Once PostHit instance created, it calls increase_hit() everytime I visit DetailVie. But it doesn't increase right way. First it prints 1. And when I refresh the page, it prints 2. At next refresh, it prints 2 again. It doesn't increase anymore after 2. What's wrong with my code? Did I misunderstand class attribute and instance property? -
'User' object has no attribute 'UserProfile'
I tried following the example at https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-the-existing-user-model on how to extend the user model. But I cannot retrieve the model data which I attached to the User. model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ip = models.IntegerField(default=0) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) getting my User object user = auth.authenticate(username=username, password=password) g = user.UserProfile.ip print(g) The user gets fetched properly, and I'm able to get all the data that are with the standard user. But user.UserProfile will result in: Internal Server Error: /Crowd/login/ Traceback (most recent call last): File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 35, in login g = user.UserProfile.ip AttributeError: 'User' object has no attribute 'UserProfile' [05/Sep/2016 04:32:46] "POST /Crowd/login/ HTTP/1.1" 500 69185 I checked my database and I can see that there's a row in UserProfile which has a relation with User. So UserProfile is getting created properly(I assume). -
Does JS work differently in Django in development vs. production?
I'm writing a gradebook app that I'm very happy with the the development environment. I outsourced one aspect of this build: a JS score entry module (JS and associated view and template). It works great on my local machine, but in the production environment, it won't save records to the DB (this should create and edit score objects). It behaves exactly as expected from the user's perspective (so it's loading), but doesn't ever update the DB. Any ideas on differences between the environments that could cause this? -
Abstract Forms Django : __init__() got multiple values for argument
I want to make an AbstractEditForm (Inherited from ModelForm) form, from which there are multiple forms that would be inheriting from it. But I am getting this error : Here is my forms.py # This is the abstract form that I want to inherit other forms from class AbstractEditForms(forms.ModelForm): def __init__(self, id_fields=None, ref_field=None, model=None, *args, **kwargs): self.id_fields = id_fields self.changed_fields = {} self.ref_field = ref_field self.model_ = model self.ref_id_changed = False self.check_ref_id() try: if 'id_fields' in kwargs.keys(): del kwargs['id_fields'] if 'ref_fields' in kwargs.keys(): del kwargs['ref_fields'] except KeyError as e: print('Error in AbstractionEditForms :', str(e)) super(AbstractEditForms, self).__init__(*args, **kwargs) # This is the form that I want to use class SchemeEditForm(AbstractEditForms): class Meta: model = SchemeModel exclude = ['created_on', 'financial_year'] widgets = { 'as_ref_id': forms.TextInput(attrs={'readonly': 'readonly', 'placeholder': 'Auto Generated ' }), 'admin_sanction_amount': forms.HiddenInput(), 'updated_on': forms.HiddenInput(), } views.py : def edit_scheme_form_view(request, pk=None): assert pk is not None, 'pk cannot be None, scheme edit form' instance = get_object_or_404(SchemeModel, pk=pk) id_fields = ['technical_authority', 'dept_name', ] model = SchemeModel ref_field = "as_ref_id" if request.method == 'GET': scheme_form = SchemeEditForm(None, id_fields=id_fields, ref_field="as_ref_id", model=model, instance=instance) context = { 'form': scheme_form } return render(request, 'Forms/forms/SchemeForm.html', context=context) if request.method == 'POST': scheme_form = SchemeEditForm(request.POST, id_fields=id_fields, ref_field="as_ref_id", model=SchemeModel, instance=instance) if scheme_form.is_valid(): … -
Django's runscript: No (valid) module for script 'filename' found
I'm trying to run a script from the Django shell using the Django-extension RunScript. I have done this before and but it refuses to recognize my new script: (env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript fill_in_random_variants No (valid) module for script 'fill_in_random_variants' found Try running with a higher verbosity level like: -v2 or -v3 While running any other script works fine: (env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript fill_in_variants Success! At least, there were no errors. I have double checked that the file exists, including renaming it to something else. I have also tried running the command with non-existent script names: (env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript thisfiledoesntexist No (valid) module for script 'thisfiledoesntexist' found Try running with a higher verbosity level like: -v2 or -v3 and the error is the same. Why can't RunScript find my file? -
Django: Unable to open a detail view by URL, which causes reverse argument errors in another view
Python 3.5.1 Django 1.10 Been tearing my hair out for hours on this, but have my Reverse Argument error pinned down to the actual problem. When I try to open a form to edit a particular record in my model, it only opens a blank (unconnected) form. Using the same logic, I am able to delete a record, so I'm sure this is something stupid-simple. But I'm too many hours into this, so I would appreciate a lifeline. From models.py class CmsSpaces(models.Model): sid = models.AutoField(db_column='SID', primary_key=True) section = models.CharField(db_column='Section', max_length=5) ...Many more columns... def __unicode__(self): return self.name def get_absolute_url(self): return reverse('cms_spaces:space_edit', args = (self.sid), kwargs=None) return reverse('cms_spaces:space_delete', args = (self.sid), kwargs=None) return reverse('cms_spaces:space_new', args = None, kwargs = None) class Meta: managed = False db_table = 'cms_spaces' From views.py def CmsSpaces_update(request, sid, template_name='space_edit.html'): space = get_object_or_404(CmsSpaces, sid=sid) form = space_form(request.POST or None, instance=space) if form.is_valid(): form.save() return redirect('space_list') return render(request, template_name, {'form':space_form}) def CmsSpaces_delete(request, sid, template_name='space_delete.html'): space = get_object_or_404(CmsSpaces, sid=sid) if request.method=='POST': space.delete() return redirect('space_list') return render(request, template_name, {'object':CmsSpaces}) From urls.py from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from cms_spaces import views urlpatterns = [ url(r'^space_list/$', views.CmsSpaces_list, name='space_list'), url(r'^space_new/$', views.CmsSpaces_create, name='space_new'), url(r'^space_edit/(?P<sid>[\w-]+)/$', views.CmsSpaces_update, name='space_edit'), … -
How can I keep only thumbnail image and remove original image in Django?
I'm using sorl-thumbnail to make thumbnail image in `Django. But the only thing that I needed is thumbnail image, not original image. So I override save() in my models, and add remove original files so that i t removes original file when it is about to be saved. But sorl-thumbnail create thumbnail-image only when the template thumbnail-image used is loaded, which means I have to keep the original file until then. So, it fails. Need some good idea. Thanks. -
JWT in Django server
I have a custom user model and i«m unable to use check_password() to authenticate in django. The goal is to have http-only cookies sent from the server. How can i make a stateless JWT cookie in a django server and send it in every request. Thanks. -
"AssertionError: Cannot apply DjangoModelPermissions" even when get_queryset is defined in view
I'm getting the following error even though my view is overriding get_queryset(). AssertionError: Cannot apply DjangoModelPermissions on a view that does not set `.queryset` or have a `.get_queryset()` method. Here's my view: class PlayerViewSet(viewsets.ModelViewSet): serializer_class = PlayerSerializer def get_queryset(self): try: quality = self.kwargs['quality'].lower() print("Getting Player for %s"%quality) return Player.objects.filter(qualities__contains=quality) except: # todo: send out a 404 print("No Players found for this quality :(") pass My settings.py: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } I don't understand what the issue is. Why doesn't DRF see my get_queryset method? -
Saving files to database by user input data
This is my first Django project, and I have hit an issue that i'm unsure how to fix. I have the website running good, and even accepting authenticated (django-allauth) user uploads. My latest problem is the name of the saved files. When the user uploads from using the model.py shown below, it uploads to 'media/uploads/uploadedconfigs/None' Here is the code in models.py. def UploadedConfigPath(instance, filename): return os.path.join('uploadedconfigs', str(instance.id), filename) class ConfigFiles(models.Model): HDConfig = models.FileField(_('High Detail'), upload_to=UploadedConfigPath) LDConfig = models.FileField(_('Low Detail'), upload_to=UploadedConfigPath) Printer = models.CharField(_('Printer Model'), max_length=100, blank=True, null=True, unique=False) Plastic = models.CharField(_('Plastic'), max_length=40, blank=True, null=True, unique=False) creator = models.CharField(_('Creator'), max_length=40, blank=True, null=True, unique=False) pub_date = models.DateTimeField(_('date_joined'), default=timezone.now) The fact that it's uploading to 'None' tells me that the variable filename is incorrect. I would like the files to be saved in the format shown below. 'media/uploads/uploadedconfigs/Printer/Plastic' So the question is how can I change my "def UploadedConfigPath" so that I can use these user input variables? -
Sending a message to a single user using django-channels
I have been trying out django-channels including reading the docs and playing around with the examples. I want to be able to send a message to a single user that is triggered by saving a new instance to a database. My use case is creating a new notification (via a celery task) and once the notification has saved, sending this notification to a single user. This sounds like it is possible (from the django-channels docs) ...the crucial part is that you can run code (and so send on channels) in response to any event - and that includes ones you create. You can trigger on model saves, on other incoming messages, or from code paths inside views and forms. However reading the docs further and playing around with the django-channels examples, I can't see how I can do this. The databinding and liveblog examples demonstrate sending to a group, but I can't see how to just send to a single user. Any suggestions would be much appreciated. -
compare two results (of many) from api data with django/python
I'm learning django/python/css/etc... and while doing this, I've decided to build an app for my website that can pull simple movie data from TMDb. What I'm having trouble with is figuring out a way to add a way for the user to select two different movies, and once selected, see the differences between them (run time, budget, etc). I've got grabbing the data from the API covered in that doing a search for a movie on my site returns expected results. But now I'm having a really tough time trying to figure out how to select 1 item from the results to "save" it, search again, select the second movie, and have the comparison show up. I know it's pretty vague, but any help getting me pointed in the right direction would be greatly appreciated! I'm not sure if it's relevant, but here's what I'm doing so far with the code: from django.shortcuts import render from django.conf import settings from .forms import MovieSearch import tmdbsimple as tmdb def search_movie(request): parsed_data = {'results': []} if request.method == 'POST': form = MovieSearch(request.POST) if form.is_valid(): search = tmdb.Search() query = form.cleaned_data['moviename'] response = search.movie(query=query) for movie in response['results']: parsed_data['results'].append( { 'title': movie['title'], 'id': … -
Tastypie, bundle data from other resource
How to make featured photo be the part of Kv resourse? If user checks one of the photo resourse as featured, this photo must become part of Kv resourse. Is it possible? class Kv(models.Model): short_desc = models.CharField(max_length=200, default='short desc') class Foto(models.Model): featured = models.BooleanField(default=False) photo = FilerImageField(null=True, blank=True, related_name="photo") class FotoResource(ModelResource): photo = fields.FileField(attribute='photo', null=True, blank=True) class Meta: queryset = Foto.objects.all() resource_name = 'foto' class KvResource(ModelResource): foto = fields.ToManyField(FotoResource, 'foto_set', full=True) class Meta: queryset = Kv.objects.all() resource_name = 'kv' -
maximum recursion depth exceeded on logout(request)
I'm trying to create the logout functionality on my page. But getting this recursion error, everytime I hit the link that points to the logout url. Below is the code, for what is suppose to be showing content and a logout functionality if the user is logged in. Otherwise show the login form. view methods def login(request): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) context = { } if user is not None: print('Correct user' else: print('Wrong user') return render(request, 'index.html', context) def logout(request): print('logged out') logout(request) return redirect('index') url urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^login/$', views.login, name='login'), url(r'^logout/$', views.logout, name='logout'), ] index.html {% if user %} <h3>Hello {{user.username}}</h3> <a href="{% url 'crowd:logout' %}">Logout</a> {% else %} <form action="{% url 'crowd:login' %}" method='post'> {% csrf_token %} <input class='logintext' type='text' placeholder='Username' name='username'> <input class='logintext' type='password' placeholder='Password' name='password'><br> <input class='loginbutton' type='submit' value='Login'> <a class='loginforgotpassword' href="{% url 'crowd:register' %}"> Forgot password?</a> <a class='loginregister' href="{% url 'crowd:register' %}"> Register</a> </form> {% endif%} console error: File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 48, in logout logout(request) File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 48, in logout logout(request) File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 48, in logout logout(request) File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 47, in logout print('logged out') RecursionError: maximum recursion depth exceeded [04/Sep/2016 23:35:59] … -
Listening for django channel events in an running event loop
I have a process running in python, detailed below, that starts an asyncio event loop and watches for a specific redis publish to connect to a websocket url. I'd like to have the listen_for_connect_events function respond to a message on a Django channel rather than a redis pubsub. I can think of two ways this might happen but haven't found a way to make either work" Can I 'subscribe' to a Django channel in much the same way that I'm currently subscribing to the redis pubsub and let the event loop wait for messages to be published? Is it possible to have a Django channel consumer function add a coroutine to an existing process' event loop? Connection code: loop = asyncio.get_event_loop() asyncio.ensure_future(listen_for_connect_events()) try: loop.run_forever() finally: loop.close() async def listen_for_connect_events(): redis_url = urlparse(settings.CHANNEL_LAYERS["default"]["CONFIG"]["hosts"][0]) redis = await aioredis.create_redis((redis_url.hostname, redis_url.port), password=redis_url.password) channels = await redis.subscribe('connect') channel = channels[0] while (await channel.wait_message()): connect_url = await channel.get(encoding='utf-8') asyncio.ensure_future(connect(connect_url)) async def connect(connect_url): async with websockets.connect(connect_url) as websocket: while True: socket_msg = await websocket.recv() msg = json.loads(socket_msg) Channel("messaging.channel").send(msg) -
testing jwt with factory boy
I want to be able to test djang-rest-framework-jwt so i can write some custom custom payload handlers. I am having issue logging in though via obtain_jwt_token. Heres a simple test that should return a 200 status code but I get a 400 error code AssertionError: {'non_field_errors': ['Unable to login with provided credentials.']} I can get it to pass if I use User.objects.create_user() and pass in a dict of username and password but would like to use factory boy to be in keeping with the rest of my tests. factories.py c lass UserFactory(factory.DjangoModelFactory): class Meta: model = User username = 'temp' email = 'temp@email.com' password = 'password' @classmethod def _create(cls, model_class, *args, **kwargs): """Override the default ``_create`` with our custom call.""" manager = cls._get_manager(model_class) return manager.create_user(*args, **kwargs) test.py class TestAuthentication: def test_jwt(self): user = UserFactory() request_factory = APIRequestFactory() data = { 'username': user.username, 'password': user.password } request = request_factory.post('/', data=data) response = obtain_jwt_token(request) assert response.status_code == status.HTTP_200_OK, response.data -
OperationalError: index teckno_thematique_ad621c37 already exists
I tried to migrade but à got an error. I did : python ./manage.py makemigrations teckno and python ./manage.py migrate --fake-initial django.db.utils.OperationalError: index teckno_thematique_ad621c37 already exists -
Filtering serializer response data
I have a ManyToMany relation with tag and items: class Tag(BaseModel): name = models.CharField(max_length=255) # ToDo Change max length description = models.TextField(blank=True, null=True) class Item(BaseModel): user = models.ForeignKey(settings.AUTH_USER_MODEL) image = models.ImageField(upload_to='items', blank=True) title = models.TextField(blank=False, null=True) message = models.TextField(blank=True, null=True) fav_count = models.IntegerField(default=0) tags = models.ManyToManyField(Tag, related_name='tags') I need all fields to be serialized, but i wish to only limit the response values. Example: What I'm receiving now: { "user": 2, "image": null, "title": "test3", "message": "testmessage", "fav_count": 0, "tags": [ { "id": 7, "name": "tag1", "description": null }, { "id": 8, "name": "tag2", "description": null } ] } But i only wish to receive the tag ids not the name and description... My simple view: if request.method == 'GET': items = Item.objects.all() serializer = ItemSerializer(items, many=True) return Response(serializer.data) Would i need to rebuild my response data to include/exclude or is there a better way to do this? (or if iv missed the terminology) -
django - can't view data on django admin page
Here are the models I am working with: class Customer(models.Model): customer_id = models.AutoField(primary_key=True, unique=True) full_name = models.CharField(max_length=50) user_email = models.EmailField(max_length=50) user_pass = models.CharField(max_length=30) def __str__(self): return "%s" % self.full_name class CustomerDetail(models.Model): phone_regex = RegexValidator(regex = r'^\d{10}$', message = "Invalid format! E.g. 4088385778") date_regex = RegexValidator(regex = r'^(\d{2})[/.-](\d{2})[/.-](\d{2})$', message = "Invalid format! E.g. 05/16/91") customer = models.OneToOneField( Customer, on_delete=models.CASCADE, primary_key=True, ) address = models.CharField(max_length=100) date_of_birth = models.CharField(validators = [date_regex], max_length = 10, blank = True) company = models.CharField(max_length=30) home_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True) work_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True) def __str__(self): return "%s" % self.customer.full_name Here is the forms.py: from django.forms import ModelForm from .models import CustomerDetail class CustomerDetailForm(ModelForm): class Meta: model = CustomerDetail fields = ['address', 'date_of_birth', 'company', 'home_phone', 'work_phone',] I have a view in my application (after user is logged in) called create_profile that asks the user for additional details and I used ModelForm instance to implement it. Here is the snippet from views.py: def create_profile(request): if request.POST: form = CustomerDetailForm(request.POST) if form.is_valid(): address = form.cleaned_data['address'] date_of_birth = form.cleaned_data['date_of_birth'] company = form.cleaned_data['company'] home_phone = form.cleaned_data['home_phone'] work_phone = form.cleaned_data['work_phone'] profdata = CustomerDetail(address = address, date_of_birth = date_of_birth, company = … -
Django django.contrib.sites where to put migration?
the django doc says to change the sites name and domain in the django.contrib.sites framework one should use a migration [1]. But they forgot to mention where I should put this migration. I tried to create a directory named "sites" and a directory named "django.contrib.sites". But no matter in which directory I put my migration, manage.py migration always says there is nothing to update. I also tried to run python manage.py makemigrations --empty sites, but then the migration is created in the lib directory: ve/lib/python3.5/site-packages/django/contrib/sites/migrations/0003_auto_20160904_2144.py. This may be correct behaviour, but then I cannot set my change under source control. In case something is wrong with my migration, here it is: from __future__ import unicode_literals from django.db import migrations, models def set_site_name(apps, schema_editor): Sites = apps.get_model('django.contrib.sites', 'site') site = Sites.objects.filter(id=1).first() if site != None: site.name = "name" site.domain = "name.com" class Migration(migrations.Migration): initial = True operations = [ migrations.RunPython(set_site_name), ] So my question is: where does django expect to find those migrations? Thank you very much in advance for your help. [1] https://docs.djangoproject.com/en/1.10/ref/contrib/sites/#enabling-the-sites-framework -
How to string break in Python Report Lab Sentence break into a new line (String Break)?
canvas.drawString(30,dec_and_return(abc.initial, abc.interval),'Date Of Release :- '+ str(movie.date_of_release)) canvas.drawString(30,dec_and_return(abc.initial, abc.interval),'Other Remarks :- '+ str(movie.other_remarks)) canvas.drawString(30,dec_and_return(abc.initial, abc.interval),'Movie Reviews :- '+ str(movie.reviews)) How To break that reviews string and continue the sentence to the next line? The Above image is for the sentence going out of bounds. How to continue the sentence in the next line? -
How do I set up token authentication properly with Django Rest Framework?
I am using DRF 1.10 and Python 3.5. I am trying to use DRF's rest_framework.authtoken.models.Token to authenticate a user on login. This is what I have: views.py class LoginView(views.APIView): serializer_class = LoginSerializer def post(self, request, **kwargs): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): user = User.objects.get(username=serializer.data['username']) token = Token.objects.create(user=user) response = {} response['user'] = serializer.data response['token'] = token.key return Response(response, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get("username").lower() password = attrs.get("password") user = authenticate(username=username, password=password) if user: attrs["user"] = user return attrs else: raise serializers.ValidationError( "Unable to login with credentials provided." ) On login I want to provide the user with a token and on log out I want to delete that token. The problem is that when I attempt to delete the token by finding the token with the token's key and the user that it is related to, I am unable to find the token. The logout view is here: class LogoutView(views.APIView): def post(self, request, **kwargs): try: token = request.META['HTTP_AUTHORIZATION'].split(" ")[1] invalidate_token = Token.objects.filter(key=token, user=request.user) invalidate_token.delete() return Response({ detail: "Logged out"}, status=status.HTTP_202_ACCEPTED) except: return Response({"error": ["Token does not exist!"]}, status=status.HTTP_400_BAD_REQUEST) I ran into problems when I tried to log …