Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djano Array agregate on multiple fields
I am using postgres as my backedn in django Application I have 4 models in my app class sprint(models.model): sprintname = models.CharField(max_length=100) ..... class testcases(models.model): testcasename = models.CharField(max_length=100) sprint = models.ForiegnKeyField(sprint) ....... class tags(models.model) tagname = models.CharField(max_length=100) testcase = models.ForiegnKeyField(testcases) class sprinttestcases(models.Model): sprint = models.Foriegnkey(sprint) testcase = model.Foriegnkey(testcase) tag = models.ForiegnKey(tags) Using django templates , I am outputing these values in Ui on a sprint basis like below . Here thhe testcases and tags will be in drop downs How to write django query to get data like this Tried till these , but not sure on how to proceed q= SprintTestcases.objects.filter(something).\ values('sprint_id','testcase_id').annotate(tmlist = ArrayAgg('tag')) -
Render SVG in python Django template
I am trying to render dynamically made SVGs in Django's templates. I am using this svgwrite library to generate a SVG that is returned as an object. What I get in the browser is the object name, but not actual SVG rendered, not getting actual XML os the SVG. How to fix that? In views: import svgwrite def makesvg(): dwg = svgwrite.Drawing('test.svg', profile='tiny') dwg.add(dwg.line((0, 0), (10, 0), stroke=svgwrite.rgb(10, 10, 16, '%'))) dwg.add(dwg.text('Test', insert=(0, 0.2), fill='red')) dwg.save() return dwg In template: <div id="main-div"> <image>{{svg}}<image> </div> Output: <div id="main-div"> <img>&lt;svgwrite.drawing.Drawing object at 0x7f766dcc0b90&gt;<img> </div> -
Django: static file: How make it downloadable
Django, I have a file in static folder and i want to have a download button in my html, onclicking it should download that file I think the headers have to be changed to attachment instead of inline. Something like the specific static file response ["Content-Disposition"]= "attachment; filename=something.someext" So how can i do this in Django. Or what is the best way to do this. Its a fixed file and no need for me to get any information from user or database. -
Django not creating other field, only the date field is created
I have a model but its not creating the other fields except for datefield whenever i do makemigrations from django.db import models from datetime import datetime from django.utils import timezone now = timezone.now() class User(models.Model): user_fname = models.CharField(verbose_name='First Name', max_length=200), user_lname = models.CharField(verbose_name='Last Name', max_length=200), user_email = models.EmailField(unique=True, max_length=200, verbose_name='Email'), user_position = models.CharField(verbose_name='Position', max_length=200), pub_date = models.DateField(default=now) def __str__(self): return self.user_email -
Django - How to prevent rename of filenames for FileFields
I'm trying to make an application with Django that stores fitness exercises with two fields for uploading images. The problem I have is that everytime I change, update, overwrite one of this two image file, the other is renamed by Django itself. Not only, the field that get renamed duplicate the image with another filename. I searched for similar problem but I wasn't able to find the solution. Here my files: models.py from django.core.files.storage import FileSystemStorage from django.db import models from io import BytesIO from PIL import Image import os from django.core.files import File from django.urls import reverse from django.db.models.signals import post_delete, pre_save from django.dispatch import receiver from django.db import models def compress(image): im = Image.open(image) # create a BytesIO object im_io = BytesIO() # save image to BytesIO object im.save(im_io, 'JPEG', quality=70) # create a django-friendly Files object new_image = File(im_io, name=image.name) return new_image def content_file_name1(instance, filename): ext = filename.split('.')[-1] filename = "A_%s.%s" % (instance.id, ext) return os.path.join('exercises', filename) def content_file_name2(instance, filename): ext = filename.split('.')[-1] filename = "B_%s.%s" % (instance.id, ext) return os.path.join('exercises', filename) # Create your models here. .... class Exercise(models.Model): id = models.AutoField(primary_key=True) exercise_name_eng = models.CharField(max_length=255, blank=False) exercise_name_it = models.CharField(max_length=255, blank=False) primary_muscle_group = models.ForeignKey(MusclesGroup, on_delete=models.CASCADE, related_name='primary_muscle', blank=True, … -
How can I get a pk value from ListView and use it?
My code status is Current. If you look at the code, the status is ListView = > DetailView = > DetailView. I want ListView => ListView => DetailView. I want to show only the objects that are referenced by Forey key, not DeatilView. I'm sorry that I can't speak English. models.py class Study(models.Model): study_title = models.CharField(max_length=50, null=False) study_image = models.ImageField(upload_to='images/', blank=True, null=True) def __str__(self): return self.study_title class Studylist(models.Model): post = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='post_name') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) profile_image = models.ImageField(upload_to='profile/', blank=True, null=True) post_title = models.CharField(max_length=50, null=False) post_content = models.TextField(null=False) content_image = models.ImageField(upload_to='content_image/', blank=True, null=True) created_date = models.DateTimeField(auto_now=True) updated_date = models.DateTimeField(auto_now=True) def __str__(self): return self.post_title views.py class StudyView(ListView): model = Study context_object_name = 'study_list' template_name = 'studyapp/list.html' paginate_by = 6 def get_context_data(self, **kwargs): context = super(StudyView, self).get_context_data(**kwargs) paginator = context['paginator'] page_numbers_range = 5 # Display only 5 page numbers max_index = len(paginator.page_range) page = self.request.GET.get('page') current_page = int(page) if page else 1 start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range end_index = start_index + page_numbers_range if end_index >= max_index: end_index = max_index page_range = paginator.page_range[start_index:end_index] context['page_range'] = page_range return context class StudyListView(DetailView): model = Study context_object_name = 'target_study_list' template_name = 'studyapp/studylist.html' class StudyDetailView(DetailView): model = Studylist context_object_name = 'target_study_detail' … -
DJANGO : Type Error 'an integer is required' AND Type Error 'bool' object is not callable
I am new to DJANGO and have limited experience in coding. I am working through a DJANGO tutorial which involves building a cart. I receive: a type error integer is required on the front end; and a type error bool object no callable in the admin portal when I attempt to manually create the cart. I think the code is a little out of date from the tutorial, but my limited experience means any change I have attempted leads to further errors. The code is as follows: cart/models.py from django.db import models from django.conf import settings from store.models import product, customer from django.contrib.auth.models import User #User = settings.AUTH_USER.MODEL# if included it throws an error 'settings not defined' class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.getqueryset().filter(id=cart_id) if qs.count()==1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj-save() else: cart_obj = cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user = None): user_obj = None if user is not None: if user is authenticated(): user_obj = user return self.model.objects.create(user=user_obj) class cart(models.Model): user = models.ForeignKey(User, related_name = "user", blank = True, null=True, on_delete=models.CASCADE) product = models.ManyToManyField('store.product') total = models.DecimalField(default = 0.0, … -
Django error when trying to access contact form
Can somebody please prevent me from imploding?!!! I'm trying to create a contact form for my school project, but get this error and have no idea what it means. I've tried googling and couldn't make sense of what the problem is. Error: Traceback (most recent call last): File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /contact/ Exception Value: init() takes 1 positional argument but 2 were given admin.py from django.contrib import admin from .models import Contact class ContactAdmin(admin.ModelAdmin): list_display = ['firstname', 'lastname', 'email', 'subject'] list_per_page = 20 admin.site.register(Contact, ContactAdmin) forms.py from django import forms class ContactForm(forms.Form): firstname=forms.CharField() lastname=forms.CharField() email = forms.EmailField() subject = forms.Textarea() models.py from django.db import models class Contact(models.Model): firstname=models.CharField(max_length=200) lastname=models.CharField(max_length=200) email=models.EmailField(null=False) subject=models.TextField() def __str__(self): return f'{self.lastname}, {self.firstname}, {self.email}' urls.py from django.urls import path from .views import ContactView urlpatterns = [ path('', ContactView, name='contact'), ] views.py from django.shortcuts import render from .models import Contact from django.views.generic import View from .forms import ContactForm from django.contrib import messages class ContactView(View): def get(self, *args, **kwargs): form = ContactForm() context = {'form': form} return render("contact.html", context) def post(self, *args, **kwargs): form = ContactForm(self.request.POST) if … -
Django - How to pass data (arguments?) with redirect function
I have a django view where a user uploads a large file. I scrape a ton of information from this file and hold it in memory. I don't want to save this information to the database because it takes too long and I don't need to save it. But I want to continue to use this data in the next view. How do I send along this data using redirect? def view_one(request): if request.method == 'GET': return render(request, 'view_one.html') if request.method == 'POST': uploaded_file = request.FILES['my_file'] info, data = scrape_my_file_for_info_and_data(uploaded_file) return redirect('path_to_view_two', info, data) def view_two(request, info, data): do_stuff_with_info(info) do_stuff_with_data(data) I keep getting errors that I am missing positional arguments 'info' and 'data'. I've tried doing: return redirect('path_to_view_two', info=info, data=data) return redirect(view_two(info, data)) But this doesn't work either. I can't find an example online of how to properly do this and I can't make heads or tails out of the django documentation. Seems there should be an easy way to do this, I just haven't landed on it. Thanks for reading my question! -
Django ModelMultipleChoiceField iterate over elements and check if initialy selected
I have a Django Form with ModelMultipleChoiceField that has some initial vales set. Everything works fine. Then in the template, instead of just printing {{ my_form.multiple_field }}, I iterate over the elements so I can style the whole form as a button group. <div class="btn-group-vertical" data-toggle="buttons" style="width: 90%"> {% for checkbox in filter_opts.categorias_producto %} <div class="btn btn-light btn-sm"> <a style="text-align: left; font-size: 12px;"><span style="display: none;">{{ checkbox.tag }}</span> {{ checkbox.choice_label }}</a> </div> {% endfor %} </div> I want to know how to detect if the element is selected and show the button as selected but I can´t find the way. Any clues welcome. Thanks in advance. -
How to change CSS that Django template uses with a button?
I am trying to implement accessibility option on my page that would change CSS to different file when accessibility button would be clicked. For now, all my templates extends base_generic.html, where style.css is loaded. When accessibility button would be clicked, I wish for it to change to use style_access.css for that user. How can I accomplish that? -
Django migrations applied mid async celery process
I'm not sure this is the correct format for such a question, but worth a shot. Let's assume the following scenario: Django web application with multiple celery workers (running as docker images) Shared DB Once new code is deployed (with migrations applied) - if a worker is executing, it is allowed to finish the task (but no longer receiving any new workload) and then terminated; idle workers are terminated and recreated with new code The running worker is often out of sync with new DB schema - leading to task failures Question is: What would be the right approach to tackle this workflow? Letting running tasks finish is preferred since tasks may be long and painful to restart a couple of times a day... Any thoughts or existing resources would be appreciated. -
Django updates model instead of inserting when calling save()
Im trying to make a web app that has per user models. When logging in as a user with no current models it creates a new model for that user. The problem is that instead of inserting a new model it updates the existing model. The model has 3 fields, user, name and value. upon logging in the logic checks to see if there is model values with the users name in it and if there isn't then it creates a new model, or should. But currently it just updates all rows to associate them with the user that just logged in. This is my code for creation of a new model which is called when a user that has no model associated with it logs in and when a user wants to reset there model. #if there is no models associated with user/ recreate the model is called Board.object.filter(user=user).delete(); #create the new model for row in page_data.get("rows"): for name, value in row.items(): Board(user=user, name=name, value=value).save() -
Why is my Django project getting " An appropriate representation..." error?
I have a Django project where I'm trying to get a request and get data from it. When I do: request_text = 'http://asdfasdf.mx/api/rol/?blabla=2' r = requests.get(request_text) dict = json.loads(r.text) I get the An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security. error. If I access the request through my web browser, I see the results with no problem, however. I have used this code with many other requests, and I had never seen this error until today. -
The event popstate is not working in Google Chrome
I've been searching for a solution about the problem I've mentioned at the Title. Nevertheless I wasn't able to find a solution, so I decided to ask :) I don't why, but my code works perfectly fine in "Firefox", but when It comes to google, the "popstate" event is not working. There's a curious thing, though. If I paste directly the JS code that contains the "popstat", in the "Console" of Chrome. It f@***ng works. So, I don't know why this is happening. Below is my JS code: <!-- JAVASCRIPT PRINCIPAL (DEBE ESTAR CONTENIDO EN LA PÁG PRINCIPAL, COMO EN CUALQUIER PÁGINA HIJO). --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="/static/core/js/vendor/jquery-1.11.2.min.js"><\/script>')</script> <script src="/static/core/js/vendor/bootstrap.min.js"></script> <script src="/static/core/js/plugins.js"></script> <script src="/static/core/js/main.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { // navigation click actions $('.scroll-link').on('click', function(event){ event.preventDefault(); var sectionID = $(this).attr("data-id"); scrollToID('#' + sectionID, 750); }); // scroll to top action $('.scroll-top').on('click', function(event) { event.preventDefault(); $('html, body').animate({scrollTop:0}, 'slow'); }); // mobile nav toggle $('#nav-toggle').on('click', function (event) { event.preventDefault(); $('#main-nav').toggleClass("open"); }); }); // scroll function function scrollToID(id, speed){ var offSet = 0; var targetOffset = $(id).offset().top - offSet; var mainNav = $('#main-nav'); $('html,body').animate({scrollTop:targetOffset}, speed); if (mainNav.hasClass("open")) { mainNav.css("height", "1px").removeClass("in").addClass("collapse"); mainNav.removeClass("open"); } } if (typeof console === "undefined") { … -
Perform arithmetic operations on Django Subquery value
In our system, there are "Car" objects that are associated with "User" objects. With a subquery, I want to count a specific set of Car objects, perform an arithmetic operation on the result and update the User object with that value. The problem is that subqueries are expressions, not integers and I therefore can't handle them as integers. The code below does not work but you can see what I want to achieve. How should this be done? def get_car_data(): since = timezone.now() - timedelta(days=3) car_count = Subquery( Car.objects.filter( car__user=OuterRef("user"), car__user__blocked=False, created__gte=since, ) .values("car__user") .annotate(count=Count("car__user")) .order_by() .values("count") ) return { "car_count": Coalesce(car_count, 0, output_field=IntegerField()) } def calculate_values(bonus): data = get_car_data() # THIS DOES NOT WORK User.objects.update(car_bonus_counter=data["car_count"] * bonus + 100) -
LiveReload exception: <urlopen error [Errno 111] Connection refused>
Whenever i run my django project i get throw this issue, it doesn't disconnect but this error happen -
Django model field similar to forms.MultipleChoiceField
I'm trying to create StackedInline admin model that contains all users from selected group. The idea is to have dropdown field with all of my Groups and when it's changed with JavaScript "on" method to manipulate the "Users" field. Unfortunately I can't find what type of field to use in my UserChoosing model. I want it to look like this and to be able to choose multiple users. Please give me an idea what field to use or maybe how to create and connect FormModel with MultipleChoiceField. Thank you in advance! -
How to dynamically compose an OR query filter in Django to delete pairs of objects from ManyToManyFields?
if i want to implement this for delete multiple object from many to many field i need to create a dynamic filter like the below one. PizzaToppingRelationship = Pizza.toppings.through PizzaToppingRelationship.objects.filter( Q(pizza=my_pizza, topping=pepperoni) | Q(pizza=your_pizza, topping=pepperoni1) | Q(pizza=your_pizza2, topping=mushroom) ).delete() However, I want to create this query filter from a list of objects. How to do that? e.g. [{"pizza": my_pizza, "topping": pepperoni}, {"pizza": your_pizza, "topping": pepperoni1}, {"pizza": your_pizza2, "topping": mushroom}] -
Method Not Allowed: /accounts/send_invite/
I have two views that I use to send and remove a friend request on my django project. The thing is the methods used to work before and I could add friends on the site but now I've been getting 405 errors and I have absolutely no idea what's the root cause. If someone could just point me in the right direction id be very thankful. I'll put the views, templates and signals to show but I don't think the problem lies within the logic of the code because it worked before. def remove_from_friends(request): if request.method=='POST': pk = request.POST.get('profile_pk') user = request.user sender = UserProfile.objects.get(user=user) receiver = UserProfile.objects.get(pk=pk) rel = Relationship.objects.get( (Q(sender=sender) & Q(receiver=receiver)) | (Q(sender=receiver) & Q(receiver=sender)) ) rel.delete() return redirect(request.META.get('HTTP_REFERER')) return redirect('accounts:profile') def send_invitation(request): if request.method=='POST': pk = request.POST.get('profile_pk') user = request.user sender = UserProfile.objects.get(user=user) receiver = UserProfile.objects.get(pk=pk) rel = Relationship.objects.create(sender=sender, receiver=receiver) return redirect(request.META.get('HTTP_REFERER')) return redirect('accounts:profile') The urls: path('send_invite/', send_invitation, name='send_invite'), path('remove_friend/', remove_from_friends, name='remove_friend'), The template <div class="card-body"> <p class="card-text">{{obj.bio}}</p> <a href={{obj.get_absolute_url}} class="btn btn-primary btn-sm">See Profile</a> {% if obj.user not in rel_receiver and obj.user not in rel_sender %} <form action="{% url 'accounts:send_invite' %}" method="POST"> {% csrf_token %} <input type="hidden" name="profile_pk" value={{obj.pk}}> <button type="submit" class="btn btn-success btn-sm mt-2">Add to … -
Can't login to Django admin panel after successfully creating superuser using Django custom user model
After I create superuser in command line, it says the superuser is created successfully, but when I try to log in it says "Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive." I tried to delete all migrations and database and try again but it did not help. Here is my model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db.models.deletion import CASCADE from django.utils import timezone from django.utils.translation import gettext_lazy # Create your models here. class UserAccountManager(BaseUserManager): def create_user(self, Email, Password = None, **other_fields): if not Email: raise ValueError(gettext_lazy('You must provide email address')) email = self.normalize_email(Email) user = self.model(Email=email , **other_fields) user.set_password(Password) user.save(using=self._db) return user def create_superuser(self, Email, Password = None, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) return self.create_user(Email=Email, Password = Password, **other_fields) class Customer(AbstractBaseUser, PermissionsMixin): Email = models.EmailField(gettext_lazy('email address'), max_length=256, unique=True) Name = models.CharField(max_length=64, null=True) Surname = models.CharField(max_length=64, null=True) Birthday = models.DateField(auto_now=False, null=True,blank=True) PhoneNumber = models.CharField(max_length=16, unique=True, null=True, blank=True) Address = models.CharField(max_length=128, blank=True) RegistrationDate = models.DateTimeField(default=timezone.now, editable=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'Email' REQUIRED_FIELDS = [] def __str__(self): return self.Name + " " + self.Surname … -
How do log JSON as default data in Django?
I am trying to log to a dictionary to logDNA. An idea log would look like this: logging.debug({'message': 'testing json', 'user': 490, 'status': 200}) My filters and formatters in my Django log settings look like this: 'filters': { 'meta_data': { '()': 'middleware.log_meta_data.filters.MetaDataFilter' } }, 'formatters': { 'logdna': { 'format': '%(meta_data)s' } }, And my MetaDataFilter looks like this: class MetaDataFilter(logging.Filter): def filter(self, record): if not hasattr(record, 'meta_data'): record.meta_data = {} record.meta_data['message'] = record.msg # Log a unique ID to each log request default_request_id = getattr(settings, LOG_REQUESTS_NO_SETTING, DEFAULT_NO_REQUEST_ID) record.meta_data['request'] = getattr(local, 'request_id', None) # Add the user_id from middleware record.meta_data['user'] = getattr(local, 'user_id', None) # Add the script name if len(sys.argv) > 1: record.meta_data['service'] = sys.argv[1] return True This issue is, most of my codebase has logging that looks like this: logging.info("This is a log"). So under this current setup, logDNA receives a stringified dictionary that looks like this: {'message': "this is a log", 'user': 20, 'status_code': None}' instead of the actual dictionary. Is there a way to tell Python that when logging to LogDNA, log meta_data as a dictionary, not as a string encoded dict? Something like above but with the wrapped single quotes removed, i.e: 'formatters': { 'logdna': { … -
How to translate field's title in password reset form?
I used contrib.auth in order to implement reset password function. Here is my code: <form method="post"> {% csrf_token %} {% for field in form %} <div class="form-group row" aria-required={% if field.field.required %}"true"{% else %}"false"{% endif %}> <label for="{{ field.id_for_label }}" class="col-md-4 col-form-label text-md-right">{{ field.label }}{% if field.field.required %}<span class="required">*</span>{% endif %}</label> <div class="col-md-6"> {{ field }} {% if field.help_text %} <small id="{{ field.id_for_label }}-help" class="form-text text-muted">{{ field.help_text|safe }}</small> {% endif %} </div> </div> {% endfor %} <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary"> cambiar contraseña </button> </div> </form> And it looks like this [![enter image description here][1]][1] But I want to translate into my language fields 'New Password' and 'New password confirmation'. Is it possible? [1]: https://i.stack.imgur.com/7GgAJ.png -
(Django) Efficiently get related objects from a ManyToManyField, sorted and limited to a count
I have a database of > 50k Persons. Each Person can own multiple Items, and each Item can be owned by multiple Persons. Person contains field Items, which is of type ManyToManyField(). I need to get 100 Person objects, sorted by number of Items owned. Also for each Person I need 10 Items, sorted by a "rarity" field (just a number). The problem is that the first part of the query (getting the Person objects) is really fast, and the second part takes 100 times longer, which makes sense because I can see it makes a separate query for each Person. Here is my code: persons = Person.objects.all().order_by('-items_count')[:100] for person in persons: items = person.items.all().order_by('rarity')[:10] # Do stuff, build a response object items_count is a precomputed field with number of Items owned. I know I can annotate it on the fly, I was just experimenting to optimize the query. The whole thing takes over a second. Is there a way to combine both queries into one, or change my models somehow to optimize this? Here are my models: class Item(models.Model): name = models.CharField(max_length=50) # Other fields... class Person(models.Model): name = models.CharField(max_length=50) items = models.ManyToManyField(Item, related_name='owners') # Other fields... -
How to route specific urls in a django app?
I would like to know if there is a way to include only specific url endpoints in my Django urls.py. Lets say i have a app called auth with this auth/urls.py urlpatterns = [ url(r'^password/reset/$', PasswordResetView.as_view(), name='rest_password_reset'), url(r'^password/reset/confirm/$', PasswordResetConfirmView.as_view(), name='rest_password_reset_confirm'), url(r'^login/$', LoginView.as_view(), name='rest_login'), url(r'^logout/$', LogoutView.as_view(), name='rest_logout'), url(r'^user/$', UserDetailsView.as_view(), name='rest_user_details'), url(r'^password/change/$', PasswordChangeView.as_view(), name='rest_password_change'), ] Now I have a urls.py like that: urlpatterns = [ path('/', include('dj_rest_auth.urls')) ] this includes all endpoints from auth/urls.py. Is there a way to select (in urls.py) which URL to include? Lets say I only want login and logout to be included on my urls.py. urlpatterns = [ path('/', include('dj_rest_auth.urls.rest_login')), path('/', include('dj_rest_auth.urls.rest_logout')) ] Something like that, how can I make it work?