Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save information in two different tables in Django?
I have a django application where I can open a form with fields (client and services) rendered (form) and save it in a single table. I decided to separate the customer data in another table, so as not to have the same customer saved more than once in the services table. It turns out that I don't know how to apply this reasoning in practice. Below is the view responsible for the n ew registration. @login_required def NovaOS(request): if request.method == 'POST': form = OrdemServicoForm(request.POST) if form.is_valid(): OS = form.save(commit=False) OS.user = request.user OS.save() return redirect('/os/list/') else: form = OrdemServicoForm() return render(request, 'serviceorders/addos.html', {'form': form}) I have already created the necessary information in forms.py and models.py. forms.py class ClienteForm(forms.ModelForm): class Meta: model = Clientes fields = '__all__' widgets = { #Dados do cliente 'STATUSCliente': forms.Select(attrs={'class': 'form-control', 'placeholder': 'Status'}), 'cliente_razaosocial': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Razão Social', 'autofocus': True}), 'cliente_cpfcnpj': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'CPF/CNPJ'}), 'cliente_rgie': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'RG/I.E.'}), 'cliente_email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'E-mail'}), 'cliente_telefone_fixo': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Tel. fixo', 'data-mask':"(00)0000-0000"}), 'cliente_telefone_celular': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Tel. celular', 'data-mask':"(00)00000-0000"}), 'cliente_endereco': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Endereço'}), 'cliente_endereco_num': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Número'}), 'cliente_endereco_CEP': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'CEP'}), 'cliente_endereco_Bairro': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Bairro'}), 'cliente_endereco_Cidade': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Cidade'}), … -
What do I need to do to fix a 404 error in django
I'm new to studying Django and I'm doing a task and I have to display a message with the url "http://127.0.0.1:8000/blog/". But when I search with this url, the error "Page not found (404) is displayed Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Using the URLconf defined in project1.urls, Django tried these URL patterns, in this order: admin/ The current path, blog/, didn’t match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.", Could anyone offer me help? A message chosen by the teacher would have to appear, but I only have the error as a response. -
django rest framework serializer.data throws error about attribute in manytomany relationship
I have the following models: class MenuItem(models.Model): class Category(models.TextChoices): PIZZA = "pizza" SIDE = "side" OTHER = "other" name = models.CharField(max_length=40) description = models.TextField(max_length=150) price = models.FloatField(default=0.0) category = models.CharField(max_length=50, choices=Category.choices, default=Category.OTHER) class Order(models.Model): class OrderStatus(models.TextChoices): NEW = "new" READY = "ready" DELIVERED = "delivered" customer = models.CharField(max_length=50) order_time = models.DateTimeField(auto_now_add=True) items = models.ManyToManyField(MenuItem, through='OrderItem') status = models.CharField(max_length=50, choices=OrderStatus.choices, default=OrderStatus.NEW) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() And the following serializers: class MenuItemSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=40) description = serializers.CharField(max_length=150) price = serializers.FloatField(default=0.0) category = serializers.CharField(max_length=50) def create(self, validated_data): return MenuItem.objects.create(**validated_data) class OrderItemSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) menu_item_id = serializers.PrimaryKeyRelatedField(queryset=MenuItem.objects.all(), source='menu_item', read_only=False) quantity = serializers.IntegerField(min_value=0) class OrderSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) customer = serializers.CharField(max_length=50) order_time = serializers.DateTimeField(read_only=True) items = OrderItemSerializer(many=True) def create(self, validated_data): order_items_data = validated_data.pop('items') order = Order.objects.create(**validated_data) for order_item_data in order_items_data: quantity = order_item_data.pop('quantity') menu_item = order_item_data.pop('menu_item') OrderItem.objects.create(order=order, quantity=quantity, menu_item=menu_item) return order And then in views: @csrf_exempt def order(request): if request.method == 'POST': data = JSONParser().parse(request) serializer = OrderSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) print(serializer.errors) return JsonResponse(serializer.errors, status=400) An example request looks like: echo -n '{"customer": "John Doe", "items": [{"menu_item_id": 1, "quantity": 2}, {"menu_item_id": 2, "quantity": 1}]}' | http POST http://127.0.0.1:8000/order … -
How to quickly revert a Django migration?
I wrote a trivial new app in Django and after I ran ./manage.py migrate myapp, I realized I wanted to add some new fields. Since it's a new app, I want to update my original migration and not create a second migration, so I ran .manage.py migrate myapp zero to completely revert all migrations for the app. However, even though it took Django about 5 seconds to initial apply my single migration, after 30 minutes of processing, it still hasn't been able to revert the migration. I've killed all other connections to my local database, so I don't think it's waiting for anything. Yet top says Django's manage.py is hogging about 75% of my CPU. My app only has three simple models, with a FK relation between them in a Parent<-Child<-Grandchild relationship, and there are no records in any of the tables. I'm using a PostgreSQL backend. Why is Django so inefficient at removing a migration for tables with no records? -
UserAdmin save_model not triggering on password change
I want to end the users session when ever the password is changed through the admin site (see screenshot). I did a research and it suggests to override the save_model and write the custom logic to end the session @admin.register(User) class UserAdmin(UserAdmin): def save_model(self, request, obj, form, change): print("HERE") ... The problem is that for some reason save_model never triggers (tried debugging as well). Both User and UserAdmin are properly registered, otherwise I wouldn't even be able to access the Change Password page. Version: Django 4 -
TypeError: update() got an unexpected keyword argument 'slug' in flask
i have this flask code views.py @bp.route('/\<slug\>/update', methods=('GET', 'POST')) @login_required def update(\*args): slug = request.view_args\['slug'\] print(f"this is the slug: {slug}") if not g.user\['is_admin'\]: abort(404) db = get_db() post = db.execute("""--sql SELECT \* FROM posts WHERE slug = ?""", (slug,)).fetchone() tags = get_tags(post['id']) if request.method == 'POST': title = request.form['title'] new_slug = slugify(title) image = request.files['image'] body = request.form['body'] publish = request.form['publish'] tags = request.form['tags'] user_id = g.user['id'] # handle errors error_fields = form_errors('title', 'body', 'tags') errors = validate(error_fields, title, body, tags,) if title and body and tags: if image: filename = save_image(image) db.execute("""--sql UPDATE posts SET image = ? WHERE slug=?""", (filename, slug)) # Editd post query = """--sql UPDATE posts SET title = '%s', slug = '%s', body = '%s', publish = '%s' WHERE slug = '%s' """ % (title, new_slug, body, publish, slug) db.execute(query) db.commit() update_tags(tags.split(','), post['id']) flash('Post was Successfuly Updated', category='success') return redirect(url_for('blog.detail', slug=new_slug)) return render_template('blog/form.html', errors=errors, post=post, tags=tags, title='Edit Post') return render_template('blog/form.html', errors=None, post=post, tags=tags, title='Edit Post') what i am trying to archive is that i have this blog website and i want to be able to edit a blog post each time i call this function and this is my layout.html <!DOCTYPE html> <html lang="en"> … -
Django Rest Framework - unable to add 'url' to HyperlinkedModelSerializer fields
I have what feels likes a stupid simple question, but the docs don't seem to address my issue at all. I'm using django-rest-framework as a backend for a react app, so I want the model list view to also include the url to the details view, so my view set looks like this: from ..models import BoardModel from ..serializers import BoardSerializer from rest_framework import viewsets class BoardViewSet(viewsets.ModelViewSet): queryset = BoardModel.objects.all().order_by('file_name') serializer_class = BoardSerializer and the serializer looks like this: from .models import BoardModel from rest_framework import serializers class BoardSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = BoardModel fields = ['url', 'slug', 'file', 'processed_file', 'file_name', 'keypoints'] extra_kwargs = { 'url': {'lookup_field': 'slug'}, } and for good measure, the model: from django.db import models from .validators import validate_img_ext, validate_keypoints_schema def validate_file(v): validate_img_ext(v, [ '.png', '.jpg', '.jpeg' ]) # Create your models here. class BoardModel(models.Model): file = models.FileField(validators=[validate_file]) file_name: 'models.CharField' = models.CharField(blank=True, max_length=75) processed_file = models.FileField(blank=True, validators=[validate_file]) keypoints: 'models.JSONField' = models.JSONField(null=True, blank=True, validators=[validate_keypoints_schema]) slug: 'models.SlugField' = models.SlugField(blank=True, unique=True) and URLs with router: from rest_framework import routers from .views import board app_name = 'boardcanvas' router = routers.DefaultRouter() router.register(r'boards', board.BoardViewSet) urlpatterns = router.urls I know the routes are loading correctly, because I can see the boardmodel-detail route listed … -
Django filter not using correct template
I am working on a Django web application. The app includes a filter that is calling the wrong template--even though 'template_name' is set in both the view and the filter. I don't understand why the template_name attribute is being ignored. Here's the code: in urls.py: path('curation/', views.SubjectsCurationView.as_view(), name='subjects_curation'), in views.py: class SubjectsCurationView(LoginRequiredMixin, FilterView): template_name = 'subjects_curation.html' filterset_class = filters.CurationFilter in filters.py: class CurationFilter(django_filters.FilterSet): template_name = 'subjects_curation.html' projects = django_filters.ModelMultipleChoiceFilter( queryset=Project.objects.all(), field_name='projects', widget=forms.CheckboxSelectMultiple() ) class Meta: model = models.Subject fields = [ 'projects', ] @property def qs(self): queryset = super().qs return queryset The template that does get called, subjects_filter.html, is different from the subjects_curation.html template that is specified here. I tried changing the order of the url entries in case lazy matching was part of the problem, but that made no difference. Joe White Dana-Farber CI -
What is the best way to implement Django-Oscar Shipping Methods as model instances?
I am struggling to understand some concepts that django-oscar implements, regarding shipping, and hope that someone on here can give me some clarity. I'm trying to understand why the shipping methods are hard-coded classes versus dynamic models, and if I create models for the shipping methods, will it break the get_available_shipping_methods() method? I have looked through the docs and there are examples explaining how to create new shipping methods by subclasses, but this is not what I am looking for. I am using django-oscar as the foundation for a marketplace, therefore there will be multiple sellers/shops. I want them to be able to define their own shipping methods, as well as use the "built-in" Shipping methods used to calculate multiple shipping carrier rates. -
Equivalent of laravel chunk and pluck code in Python django
Can somone help me to convert this ( PHP - Laravel ) code to ( Django - Python ) which migrate records from an existing table in chunks, also would appreciate the use of wherein to reduce the number of queries and to reduce RAM usage. $limit = 100; $query = (new Log) ->select(['id', 'created_at']) ->latest(); $query->chunk($limit, function ($chunk) { $ids = $chunk->pluck('id')->toArray(); $existing_ids = DB::table('logs_new_table') ->whereIn('log_id', $ids)->pluck('log_id'); // Remove the existing IDs from the array $non_existing_ids = collect($ids)->diff($existing_ids)->toArray(); // Gets the non-existing ids $logs = (new Log_event) ->findMany($non_existing_ids); foreach ($logs as $log) { try { Log::debug(__METHOD__ . " processing log id: {$log->log_id}"); } catch (\Exception $e) { Log::warning(__METHOD__ . " failed to migrate log: {$e->getMessage()}"); } } }); -
Django user object can't retrieved from database
views.py def profile(request,link): user = User.objects.get(username=link) print(user.email) return render(request,'profile.html',{'user':user}) urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('login',views.loginUser,name='login'), path('signup',views.signup,name='signup'), path('profile@<str:link>',views.profile,name='profile'), path('courses',views.courses,name='courses'), ] When I trying to retrive user object it raising an error 'Dosen't exist' or 'user have no atribute username', and lot sof error. I also used filter as well but that gave a quaryset and I couldn't sent in html template as a object. -
i want to put the form boxes in-line instead of stacked
code and result. I would like to know how to display the date form in-line instead of stacked. thank you in advance! :) im using bootstrap and django so i tried solving the problem with bootstrap or even the django templating but couldnt get nowhere. -
How does CSRF Token work for a sign up request
I am just getting to learn Django, and CSRF Token seems to be an important aspect in terms of preventing cross-site request forgery. However, I am a little bit confused about its role in a sign up function. From my understanding, the CSRF Token is sent from the backend server to the frontend server after the user sends an initial request from the frontend server. Then in proceeding request to the backend server, the backend server checks if there is a valid CSRF token from the frontend and send a response accordingly. However, if a user is signing up or logging in for the first time, without any cookies on the browser whatsoever, is it possible (or necessary) to check for CSRF token in a Django signup/signin view function? If it is necessary, what is the mechanism, assuming separate backend and frontend server, behind validating CSRF token in such scenario? -
django htmx cannot get element name for the second time
In my views.py, I have 2 functions using "customer = request.GET.get('drf_customers')" In list_drf_customer_branch() it works, but in list_customer_products() it returns null Is there something wrong with my approach? views.py: def list_drf_customer_branch(request): template_name = "poc/partials/drf_customer_branch.html" customer = request.GET.get('drf_customers') # this works, returns id if customer == "": drf_customer_branch = None else: drf_customer_branch = models.CustomerBranch.objects.filter( customer=customer).order_by("description") context = {} context["drf_customer_branch"] = drf_customer_branch context["is_htmx_branch"] = True return render(request, template_name, context=context) @login_required def list_customer_products(request): template_name = "poc/partials/drf_customer_products.html" context = {} context["form"] = forms.DrfDetailForm customer = request.GET.get('drf_customers') # this doesnt work, returns None if customer == "": customer_products = None else: customer_products = models.CustomerProduct.objects.select_related("product__brand", "product__brand_category", "customer").filter( customer=customer).order_by("product__brand", "product__description") context["drf_customer_products"] = customer_products return render(request, template_name, context=context) forms.html <div id="id_drf_customers" class="mb-3"> {% include 'poc/partials/drf_customers.html' %} </div> <div id="id_drf_customers" class="mb-3"> {% include 'poc/partials/drf_customer_branch.html' %} </div> <div id="id_drf_customer_products" class="mb-3"> {% include "poc/partials/drf_customer_products.html" %} </div> partials/drf_customers.html <select name="drf_customers" class="select form-select" id="id_drf_customers" hx-get="{% url 'poc:drf_customer_branch' %}" hx-trigger="change" hx-target="#id_drf_customer_branch" required > <option value="" selected disabled>Select Customer/Outlet</option> {% for i in drf_customers %} <option value="{{i.customer_id}}">{{i.customer_name}}</option> {% endfor %} </select> -
Error coming while form submission in my Django project
As a new learner, I am trying to learn create a Django website. It is a simple Disaster Mangement website which has some features and it's also not complete yet. I have created some routes for registering volunteers and organizations, but when I am trying to create a new user for my model, the sign-up form is not getting submitted but it just gets reloaded. I tried changing different fields in my model and also tweaked with the form, but it seems I am unable to figure out the error. I would be thankful if you could help me so that my model registers new users that I create. I am posting the GitHub link of my project here. Also suggest if I should start from scratch again. https://github.com/Tapananshu-17/WoC6.0-Django-DMS-Tapananshu -
I have problem when I try to put my project developed by django in a conteiner docker:
this is my dockerfile FROM python:3.10 # Establece el directorio de trabajo en /app WORKDIR /app # Copia el archivo requirements.txt al contenedor en /app/ COPY requirements.txt /app/ # Crea y activa el entorno virtual RUN python -m venv venv RUN /bin/bash -c "source venv/bin/activate" # Instala las dependencias RUN pip install --no-cache-dir -r requirements.txt # Copia el contenido del directorio actual al contenedor en /app/ COPY . /app/ # Indica que la aplicación se ejecutará en el puerto 9005 EXPOSE 9005 # Define la variable de entorno para Django ENV DJANGO_SETTINGS_MODULE=Arriendos_Backend.settings # Instala Gunicorn RUN pip install gunicorn CMD ["gunicorn", "-c", "gunicorn_config.py", "Arriendos_Backend.wsgi:application"] like you noticed Im trying to build the project with gunicorn but the HTML doesn´t work enter image description here I try to take off the static files but the problem is still present -
ArrayField custom widget similar to JSONFieldWedget
I want to display the content of an ArrayField in a Django admin panel similar to how a JSONField is displayed using JSONFieldWidget My model's array field is a bit long to use something like: django-better-admin-arrayfield I will not be saving or updating anything via Django admin panel. -
can you remove old migrations file after changing models location django
I am currently refactoring a django project. It had a few apps with unrelated models (ex: customer in the product app) that I decided to consolidate into a single core app. I use the third method shown in this article: https://realpython.com/move-django-model/#the-django-way-rename-the-table. Everything worked well and I didn't lose any data, but now I have some empty apps that have a lot of migrations files. I would like to delete those apps to have a cleaner project structure. Would deleting the migrations break everything? I do have multiple backups of the database in case something goes wrong. -
All messages sent at once at the end of all iterations django layers
I want to send messages to client side by websocket one by one. Instead they are sent at the end of all iterations at once. I use AsyncWebsocketConsumer, so it should be fine. Another important things is that i need to access my consumer method to send data outside of TaskStatusConsumer class, so I use channel groups. My consumers.py file: class TaskStatusConsumer(AsyncWebsocketConsumer): async def connect(self): path = [el for el in self.scope['path'].split('/') if el] self.id_config = path[-1] self.group_name = f"task_{self.id_config}" await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.group_name, self.channel_name ) async def websocket_receive(self, event): for fr in range(1, 3): print(f'start fr {fr}') await send_task_status(self.id_config, 'pending', fr) print(f'end fr {fr}') time.sleep(1) async def task_status(self, message): print('start task status') data = { 'task_id': message['type'], 'status': message['status'], } await self.send(json.dumps(data)) print('end task status') Function that sends task status to group: async def send_task_status(id_config, status, iteration): channel_layer = get_channel_layer() print(f'start send task status') await channel_layer.group_send( f"task_{id_config}", { 'type': 'task_status', 'status': status, 'iteration': iteration } ) print(f'end send task status') So at this picture you can see that sending messages to client starts after sending data to group: -
In the latest vers Django 5.0.1 i can't use files in the Static folder. The settings are correct, maybe there is a conflict with the template folder?
In the latest version of Django 5.0.1, I'm having problems using css and js contained in a Static folder. I have already read several similar questions (be careful, they are old) and I also read the official Django documentation, none of them were able to help me. My code seems to be set up correctly, but it doesn't work. It means that perhaps the problem is something else, perhaps there is a conflict with the template folder (explained later). The static folder is located in this path App1/static. So the css I would like to use is located in App1/static/css/style.css So I'm using: <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> PROBLEM: The css does not apply when i open the web page. Furthermore, if I try to click on the link above the css, I receive a joke that says "It was not possible to open 'style.css' %} and asks me to create the file. The path of the file that will be created will be App1 > templates > {% static 'css > style.css' %}. Why in templates? MY SETTINGS ARE INDEX.HTML I'm using {% load static %} at the beginning of index.html I show you my 2 attempted … -
Adding dynamic url in a reverse function in django
I'm building a blog app, and when posting a comment, and a reply to a comment, the page redirects to the top of the post page, I want it to redirect into the comment\reply that was posted, or scroll into it if you will. for example, when posting, I want it to go to http://127.0.0.1:8000/post/first#comment-12 to implement something like this: return HttpResponseRedirect(reverse(f'post_page#comment-{str(comment.id)}', kwargs={ 'slug': slug })) views.py if request.POST: comment_form = CommentForm(request.POST) if comment_form.is_valid: if request.POST.get('parent'): parent_id = request.POST.get('parent') parent = Comments.objects.get(id=parent_id) if parent: comment_reply = comment_form.save(commit=False) comment_reply.parent = parent comment_reply.post = post comment_reply.save() else: comment = comment_form.save(commit=False) post_id = request.POST.get('post_id') post = Post.objects.get(id=post_id) comment.post = post comment.save() return HttpResponseRedirect(reverse('post_page', kwargs={ 'slug': slug })) urls.py urlpatterns = [ path('', views.index, name='index'), path('post/<slug:slug>', views.post_page, name='post_page') ] -
Trying to get the esm-bundler to render my templates in-browser
I'm looking for some advice on using the runtime compiler to render Vue 3 elements in the browser with Django 5.0.1. Django handles the backend and uses static html files to display the information to the user. With Vue 2, I was able to set runtimeCompiler: true, but this isn't supported with Vue 3 and Vite. I followed this discussion in the Vite repo on GitHub as it describes the problem I'm having, but after making all the necessary changes, the Vue components don't get rendered in the browser. If I inspect the element in the developer console, I can see the element that should be displayed on the screen, it's nested in a #document_fragment element. I seem to be missing a step that I can't seem to find in the documentation. Can anyone share any insight as to what I am missing or share any resources that might give me the information I need? Any resources I've found so far were either Vue 2 related or didn't solve my issue. I've included all the relevant code snippets but if you need to see anything else please let me know. Thanks in advance! Element in the developer console: <template> #document_fragment … -
How to conficure django LOGGING with azure-log-analytics?
I have a Django app, I want to log to azure log analytics LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { 'azure_log_analytics': { 'level': 'DEBUG', 'class': 'azure.loganalytics.handlers.LogAnalyticsHandler', 'workspace_id': os.environ.get('LOG_ANALYTICS_WORKSPACE_ID', None), 'workspace_key': os.environ.get('LOG_ANALYTICS_WORKSPACE_KEY', None), }, }, "loggers": { "API": { "handlers": ["azure_log_analytics"], "level": "INFO", "propagate": False, }, } } ValueError: Cannot resolve 'azure.loganalytics.handlers.LogAnalyticsHandler': No module named 'azure.loganalytics.handlers' -
Pagination with Django and Nuxt 3
I use Django for backend and nuxt3 for frontend My problem is that: Error when I use pagination in Django: Failed to load resource: the server responded with a status of 500 (Internal Server Error) But without activating pagination, it shows my content without any problem I want to work without page refresh and ajax pagination Thank you my code : index.vue <template> <h1>test</h1> <div v-for="portfolio in portfolios" :key="portfolio.id"> <h1>{{ portfolio.title }}</h1> </div> <div class="pagination"> <ul class="inline-flex"> <li> <button class="c-pointer"> <svg><use href="#arrowbefore"></use></svg> </button> </li> <li> <button class="c-pointer"> <svg><use href="#arrownext"></use></svg> </button> </li> </ul> </div> </template> <script setup> const { public: {apiURL} } = useRuntimeConfig(); const { data: portfolios, refresh } = await useFetch(`${apiURL}/portfolio`); </script> views.py class PortfolioApiViewPagination(PageNumberPagination): page_size = 1 class PortfolioApiView(generics.ListCreateAPIView): queryset = Portfolio.objects.all() serializer_class = PortfolioSerializer pagination_class = PortfolioApiViewPagination settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 8 } Please tell me the best solution -
Django: Basic auth on only certain URL paths?
I would like to password-protect only certain parts of my Django app with basic-auth. I'd like to protect all URLs except anything under /api. I'm trying to use the django-basicauth package to do this. I've configured it as follows. My app has three parts: /api /candc /places In candc/localsettings.py I've added: BASICAUTH_USERS = { "myuser": "mypass" } The candc/urls.py file looks like this: urlpatterns = [ path('', include('places.urls')), path('api/1.0/', include('api.urls')), ] Then in my places/views.py file, I've added decorators to the URLs I want to protect, like this: from basicauth.decorators import basic_auth_required @basic_auth_required( def index(request): template = loader.get_template('index.html') return HttpResponse(template.render({}, request)) However, my app is asking for basic-auth protect on URLs under /api as well. (In fact it's not even showing the dialog, just returning 403s for any requests.) How can I configure this so URLs under /api are not password-protected, but everything else is?