Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - I want to sort a previous query and not the entire model
I have two view functions: home_view - filters the database and renders the output in list.html display_view - sorts the page by date or price My PROBLEM: display_view sorts all the model and not only the output of home_view. Maybe I have to change the display_view: obj = Model.objects.all() ---> obj = home_view.obj How can I do this? def display_view(request): obj = Model.objects.all() myFilter = SortFilter(request.GET, queryset=obj) obj = myFilter.qs context = { 'objects': obj, 'myFilter': myFilter } return render(request, "list.html", context) def home_view(request): obj = Model.objects.all() myFilter = SortFilter(request.GET, queryset=obj) obj = myFilter.qs context = { 'objects': obj, 'myFilter': myFilter } return render(request, "home.html", context) -
How to toggle a wishlist button with an Ajax function in Django
So I have run into a bug that is just driving me crazy. When you open my webpage, a list of jobs are provided which have a small heart shaped wishlist icon next to them. Normally, if the job is part of your wishlist it should appear as a red icon, which if you click would have a sweetalert popup that says the job is removed from your wishlist. And if the job is not part of your wishlist it would be displayed in blue, which if you click would have a pop up that says the job has been added to your wishlist. All this works, except for when you have just loaded the page for the first time, and one of the listed jobs is NOT part of your wishlist, and displayed in blue. If you click this blue icon, instead of saying "added to wishlist" and turning red, it says "removed from wishlist" and stays blue, even though its not part of the wishlist. Clicking the button AGAIN, will then do the correct action, saying "added to wishlist" and flipping the color, so the error only occurs the first time. Something wrong with .data('wl') being set for … -
How to pass the CSRF Token in iFrame of Django?
I have made a site with django. I wish people can iframe my form and fill it to check the results. I have already tried by writing the following code in settings.py X_FRAME_OPTIONS = 'ALLOW-FROM example.com' CSRF_TRUSTED_ORIGINS = ['example.com'] CSRF_COOKIE_SAMESITE = None But it won't work. Shows the following error. How can I solve this issue. Moreover, if I want to allow all user how to write Xframe options. I am new to Django. I have tried with this It shows iframe but when submit form it is showing this kind of error. -
Handling ManyToMany Signals: Updating Individual Objects
I want to update user profiles by sending a signal once a specific user has been added onto an external m2m field. This is my setup. account-app class Deliverer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='deliverer') busy = models.BooleanField(default=False) orders-app: models.py class Order(models.Model): deliverer = models.ManyToManyField(Deliverer, related_name='Deliverer') deliveringstatus = models.BooleanField(default=False) order/views.py def assign_deliverer(request, user_id): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) del = get_object_or_404(Deliverer, user_id=user_id) order.deliverer.add(del) order.save() order/signals.py @receiver(m2m_changed, sender=Order.deliverer.through) def m2m_changes_deliverer(sender, instance, **kwargs): if kwargs['action'] == 'post_add': instance.deliveringstatus = True instance.save() Once a deliverer has been assigned an order (multiple deliverers can work on the same order) I want an additional seignal changing his/her profile's busy-status to TRUE. Failed: What I've tried: account-app/signals.py @receiver(post_save, sender=Order) def deliverer_added(sender, instance, **kwargs): obj, _ = Deliverer.objects.get(user=instance.deliverer) obj.status = True obj.save() ERROR: Field 'id' expected a number 1. Any insight on how to do this? -
How to distinguish different paths in Django which has similar path pattern? [closed]
I have recently started working with the Python Django framework. I have set up urls.py file that contains all my application URLs ```from django.urls import path from . import views app_name = "wiki" urlpatterns = [ path("", views.index, name="index"), path("encyclopedia/search", views.search_entries, name="search_entry"), path("encyclopedia/<str:title>", views.get_entry, name="entry"), path("encyclopedia/<str:action>", views.add_new, name="add_new"), ]``` How do identify the last 2 paths (encyclopedia/str:title) and (encyclopedia/str:action) uniquely? -
Annotate user of last revision in django-reversion
I keep track of the revisions of one of my django-models like so: @reversion.register() class MyModel(models.Model): In my views, I have a ListView for this model: class MyModelListView(ListView): model = MyModel Now: In the list/table of objects I want in one column displayed who made the last revision... i.e. the username of the last revision of the object... So my idea is something like this: def get_queryset(self): object_list = MyModel.objects.annotate(user_lastversion=reversion.reverse()[0].revision.user.get_username) But of course it is not working, since reversion has no attribute reverse. And I don't know how to merge something like Version.objects.get_for_object(MyModel.objects.get(slug=slug)).reverse()[0].revision.user.get_username into "annotate". Any help would be appreciated! -
How to download the uploaded file in s3 bucket without storing the temporary folder Python?
I have uploaded some of the files to the S3 bucket In private mode. I want to download the file based on the key. It should look like when I click the link to download it downloads directly without storing anywhere in the machine. Thanks in advance! -
DoesNotExist at /delete/64 list matching query does not exist.django
i'm creating todo list its fine working but when i double click so it shows me an error here is the screenshot here is my views.py code https://www.onlinegdb.com/edit/SJjz-d1aD -
DJANGO: Exception has occurred: AttributeError type object 'Client' has no attribute 'objects'
this is driving me crazy, it was working 2 days ago! I have a model called client on authentication/models: import datetime from django.contrib.auth.models import User from django.db import models from logs.mixins import LogsMixin class Client(LogsMixin, models.Model): """Model definition for Client.""" id = models.CharField("ID del cliente", primary_key=True, null=False, default="", max_length=50) company_name = models.CharField("Nombre de la empresa", max_length=150, default="Nombre de empresa", null=False, blank=False) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) cif = models.CharField("CIF", null=False, default="", max_length=50) platforms = models.ManyToManyField('consumptions.Platform', verbose_name=("Plataformas")) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) When I try to get Clients with my funcion "get_client_data" like this: # -*- encoding: utf-8 -*- import datetime import json import sys from operator import itemgetter from authentication.models import Client from consumptions.models import Platform from ..models import MF, Call, Consumption, Course, Message, Provider from .sap import * def get_client_data(request): """ Con esta función pediremos los datos del cliente a SAP y devolveremos una respuesta """ if request.is_ajax(): response = {} try: request_body = request.body.decode('utf-8') url = json.loads(request_body) if Platform.objects.filter(url=url).exists(): client = Client.objects.filter(platforms__url=url).first() # FAILS HERE I receive the next error: Exception has occurred: AttributeError type object 'Client' has no attribute 'objects' What am I doing wrong? -
Django static files not loading on heroku server showing "Refused to apply style from '<URL>' because its MIME type"
Hi my django project working fine on local server but heroku couldn't find my static files i have installed whitenoise and also run collectstatic but still show this error "Refused to apply style from '' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled." # MIME TYPE import mimetypes mimetypes.add_type("text/css", ".css", True) # Application definition INSTALLED_APPS = [ 'pages', 'listings', 'realtors', 'accounts', 'contacts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'btrc.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'btrc.wsgi.application' import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600) DATABASES ['default'].update(db_from_env) # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'btrc/static') ] # Media folder setting MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = … -
Load more button
I have developed a template for viewing the images in my Django application. I want to view only 2 images at the starting and then after clicking the load more button, the next 2 image needs to be shown. I am unable to do this.I am using ajax and javascript but I don't know how to write {% url 'profile' username=portfolio.user.username %}" URL inside javascript code $(document).ready(function(){ $('#loadmoreBtn').on('click',function(){ var currentResult=$('.portfolio-item').length; $.ajax({ url:"{% url 'load-more' %}", type:'post', data:{ 'offset':currentResult, }, beforeSend:function(){ $('#loadmoreBtn').addClass('disabled').text('Loading..'); }, success:function(res){ console.log(res); var html=''; var json_data=$.parseJSON(res.posts); $.each(json_data,function(index,data){ console.log(data.fields.file); var v='/media/'; html+=' <section id="portfolio"'+data.fields.id + ' class="portfolio">\ <div class="container" data-aos="fade-up">\ <div class="row portfolio-container" data-aos="fade-up" data-aos-delay="200">\ <div class="col-lg-4 col-md-6 portfolio-item">\ <img src='+v+ data.fields.file+' class="img-fluid" alt='+ data.fields.title+' >\ <div class="portfolio-info">\ <h4>'+data.fields.title+' </h4>\ <a href="'+v+ data.fields.file+' onclick="views('+data.fields.id+')" data-gall="portfolioGallery" class="venobox preview-link" title='+ data.fields.title+' >\ <i class="bx bx-show-alt"></i>\ </a>\ <a href='+v+ data.fields.file+' onclick="dow('+data.fields.id+')" class="details-link" title="Download" download>\ <i class="bx bxs-download pl-2"></i>\ </a>\ <p id="views"'+data.fields.id+' >'+data.fields.views+'</p>\<span id="dow"'+data.fields.id+'>'+data.fields.total_downloads+'</span>\</div>\<strong class="text-secondary" >Total likes:<span id="total_likes"'+data.fields.id+'>'+data.fields.number_of_liked+'</span>\</strong>\ </div>\</div>\</div>\</section>'; }); $('.items').append(html); var counttotal=$('.portfolio-item').length; if(counttotal==res.totalResult){ $('#loadmoreBtn').remove(); }else{ $('#loadmoreBtn').removeClass('disabled').text('Load More...'); }} }); }); }); <div class="items"> {% for portfolio in portfolios %} <!-- ======= Portfolio Section ======= --> <section id="portfolio{{portfolio.id}}" class="portfolio"> <div class="container" data-aos="fade-up"> <div class="row portfolio-container" data-aos="fade-up" data-aos-delay="200"> <div class="col-lg-4 col-md-6 portfolio-item"> <img src="{{ … -
How to fix 'Raw query must include the primary key' in Django?
I have written a Raw SQL Query which I want to return through the objects.raw() function in my views.py: (For reference, pk is my input in my API Query) UserDetails.objects.raw("""SET datestyle = dmy; SELECT CASE WHEN ud.gender = 'M' THEN 1 ELSE 0 END Gender, DATE_PART('year',AGE(CURRENT_DATE,DATE(ud.dob))) AS AGE, CASE WHEN ud.mobile_count IS NOT NULL THEN ud.mobile_count ELSE 2 END Mobile_Number_Count, CASE WHEN ud.mobile_registered_at_bureau = TRUE THEN 1 ELSE 0 END Mobile_Registered_With_Bureau, ud.state_id AS State_Id, ud.city_id AS City_Id, CAST(REPLACE(rlv_lp.lookup_value, ' Days','') AS INTEGER) AS Loan_Period, CAST(REPLACE(rlv_rf.lookup_value, ' Days','') AS INTEGER) AS Repayment_Period, CASE WHEN cli.create_full_installment = TRUE THEN 1 ELSE 0 END Moratorium_Availed, CASE WHEN pinfo.is_married = TRUE THEN 1 ELSE 0 END Is_Married, CASE WHEN pinfo.is_spouse_working = TRUE THEN 1 ELSE 0 END Is_Spouse_Working, pinfo.no_of_children as No_Of_Children, CASE WHEN pinfo.is_joint_family = TRUE THEN 1 ELSE 0 END Is_Joint_Family, CASE WHEN pinfo.is_migrant = TRUE THEN 1 ELSE 0 END Is_Migrant, pinfo.other_assets AS Other_Asset, CASE WHEN pinfo.is_political = TRUE THEN 1 ELSE 0 END Is_Political, CASE WHEN pinfo.is_police = TRUE THEN 1 ELSE 0 END Is_Police, CASE WHEN pinfo.is_lawyer = TRUE THEN 1 ELSE 0 END Is_Lawyer, CASE WHEN bd.gst_no IS NOT NULL THEN 1 ELSE 0 END Has_GST, bd.business_nature AS Industry_Type, … -
Why login function in Django takes HttpRequest object?
Login function in django.contrib.auth takes HttpRequest object. I wanted to know why does it require HttpRequest object or in general how it works. -
Calling value of django tag in javascript
I am currently working on a beginner level project in django. I want to be able to pass the value of my django tag {{total_value}} in javascript in the similitude of this total: document.getElementById("total").value , I tried using var total = {{total_value}}; and passed total but it didn't work. Can someone help me out. Thank you in advance. -
Django-webpush: Service worker is not supported in your browser (Firefox)
I am using Django-Webpush to push notification. I followed the instructions and its working perfectly on Chrome, but in Firefox (version 84.0 - which supports service workers) I get the message that the service worker is not supported in your browser!. I checked other websites that have service workers and they seem to be working fine. I ran the browser with all add-ons deactivated, but the problem still persists. I also ran the browser with all add-ons disabled to see if anything was preventing it, without any success. In order to get the message that service workers are not supported in my browser, the following condition should fail in webpush.js : if('serviceWorker' in navigator) { var serviceWorker = document.querySelector('meta[name="service-worker-js"]').content; navigator.serviceWorker.register(serviceWorker).then(function(reg){subBtn.textContent = 'Loading...'; registration = reg; initialiseState(reg); }); } else { messageBox.textContent = 'Service Worker is not supported in your Browser!'; messageBox.style.display = 'block'; } Any idea on what else to check? -
How to dynamically add/remove the fields in django restframework serializer.?
I want to dynamically add/remove field items from a django rest serializer. when an api gets request that contains information to populate certain fields of the model only, i wanted to create/retrieve that particular fields only apart from populating all the fields of the model. is there any way to do this? -
Registring models on django admin site
I have made a django admin superuser previously for a project and now for another project i created another admin site super user but when i register models on admin site it gets registered on both admin sites( i.e prev one and in new one) -
Why I can't enable PyLint for this Django project using Visual Studio Code?
I am starting working with Django Python framework (working on an Ubuntu 20.04 VM) following the famous Mozzilla example project, this one: https://developer.mozilla.org/it/docs/Learn/Server-side/Django/Home_page I am using Python 3.8.5 version. I am finding the following problem (here on Stackoverflow I see that many persons had this problem and this should be related to Pylint. Basically the problem is the same exposed here: Django/Visual Studio Tutorial - objects method error I have this Django views.py file: from django.shortcuts import render # Create your views here. from .models import Book, Author, BookInstance, Genre def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) The problem is that Visual Studio Code give me the following error on line like this: num_books = Book.objects.all().count() the error is: Class 'Book' has no 'objects' memberpylint(no-member) And this is my Book class code: class Book(models.Model): """Model … -
Remote access to django module
BACKGROUND I want to create an app that will be hosted on external server. It sounds easy and simple but I want to keep control over my code. So my idea is to develop an app that will load only necessary components over the HTTP. WHAT IS IN NOTES MODULE It's a simple django module. apps.py from __future__ import unicode_literals from django.apps import AppConfig class NotesConfig(AppConfig): name = 'notes' path = r'/PATH/TO/PROJECT/SAMPLE_httpimport/notes/' models.py from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django_extensions.db.models import TimeStampedModel, TitleSlugDescriptionModel from mptt.models import MPTTModel class Note(TimeStampedModel): title = models.CharField(max_length=256) body = models.TextField() created_by = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('note-detail', kwargs={'pk': self.pk}) def __str__(self): return self.title urls.py from django.conf.urls import url from notes.views import NoteListView, NoteDetailView, NoteCreate, NoteUpdate, NoteDelete urlpatterns = [ url(r'^$', NoteListView.as_view(), name='note-list'), url(r'^(?P<pk>\d+)/$', NoteDetailView.as_view(), name='note-detail'), url(r'note/add/$', NoteCreate.as_view(), name='note-add'), url(r'note/(?P<pk>[0-9]+)/$', NoteUpdate.as_view(), name='note-update'), url(r'note/(?P<pk>[0-9]+)/delete/$', NoteDelete.as_view(), name='note-delete'), ] views.py from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.urls import reverse_lazy from django.views.generic import CreateView from django.views.generic import DeleteView from django.views.generic import DetailView from django.views.generic import ListView from django.views.generic import UpdateView from notes.models import Note class NoteListView(ListView): model = Note class NoteDetailView(DetailView): model = Note class NoteCreate(CreateView): model = … -
How do I show all child objects in a template?
These are my models.py class Supplier(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Product(models.Model): sku = models.IntegerField(null=True) description = models.CharField(max_length=30) costprice = models.FloatField(null=True, max_length=99, blank=True) retailprice = models.FloatField(null=True, max_length=99, blank=True) barcode = models.CharField(null=True, max_length=99, unique=True, blank=True) image = DefaultStaticImageField(null=True, blank=True, default='images/item_gC0XXrx.png') supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.description I have a supplierpage/str:pk_supplier/ and inside it I want to display all products that belong to that specific supplier in a table like: <tr> <th>ID</th> <th>Description</th> <th>Cost</th> <th>Retail Price</th> <th>Barcode</th> </tr> </thead> <tbody> <tr> **{% for ??? in ???? %} <-----what should i put here??** <td> <a href="{% url 'productpage' product.id %}">{{product.id}}</a></td> <td><h6><strong>{{product.description}}</strong></h6></td> <td>£{{product.costprice |floatformat:2}}</td> <td>£{{product.retailprice |floatformat:2}}</td> <td>{{product.barcode}}</td> </tr> {% endfor %} -
Django choice field
I want to create a form that user can select her/his company from a choicefield. But this choicefield should contains another model's field. What I mean: models.py class CompanyProfile(models.Model): comp_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) comp_name = models.OneToOneField(User, on_delete=models.CASCADE) class UserProfile(models.Model): comp_name = models.ForeignKey(on_delete=models.CASCADE) #select from CompanyProfile comp_id = models.ForeignKey(on_delete=models.CASCADE) user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) forms.py companies = [] #problem is here class SignUpForm(UserCreationForm): comp_name = forms.CharField(label='What is your company name?', widget=forms.Select(choices=companies)) comp_username = forms.CharField(max_length=30, required=False) email = forms.EmailField(max_length=254) class Meta: model = User fields = ('comp_name', 'comp_username', 'email', 'password1', 'password2') How can I select company name from CompanyProfile? -
Python3 & Django3.1.4 - No module named django.core.management
I had issues with django because installing it using pip would only install django1.x for python2.7, so I made a clean install, but now it won't works when calling it. I very recently reinstalled Python and Django: python3 --version Python 3.9.1 python3 -m django --version 3.1.4 But when I try to create a new project using Django, I get the error: django-admin startapp test Traceback (most recent call last): File "/usr/local/bin/django-admin", line 5, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management If I do python3 -m django startapp test the command will do what's asked, but not if I do python3 -m django-admin startapp test I'll get /usr/local/bin/python3: No module named django-admin I looked for answers to people who had a similar error message but it didn't solve my problem. Could you tell me what I'm missing/what should I do ? -
Django reverse nested filtering
I want to make a filter on a nested Model with the Django reverse relation. Below is the sample models I have : class ProcessVersion(TimeStampedModel): tag = models.CharField(_('Tag Name'), max_length=48) status = FSMField( _('Status'), max_length=12, choices=VERSION_STATUS_CHOICES, default=VERSION_STATUS_IN_EDITION) class Step(models.Model): version = models.ForeignKey( ProcessVersion, verbose_name=_('Process Version'), on_delete=models.CASCADE, related_name='steps', blank=True, null=True) is_active = models.BooleanField( _('Is active'), default=False) title = models.CharField(_('Title'), max_length=32) class Block(models.Model): step = models.ForeignKey( Step, verbose_name=_('Loan Process Step'), on_delete=models.CASCADE, related_name='blocks', blank=True, null=True) is_active = models.BooleanField( _('Is active'), default=False) title = models.CharField(_('Title'), max_length=128, blank=True) The first scenario was accessing the Step through it's related name and it worked : process_version = ProcessVersion.objects.get(id=process_version_id) steps = process_version.steps.get(id=param_id) meaning that I passed through ProcessVersion to get the Step. Now, my question is what if I want to get the Block but passing through ProcessVersion with it's id , how can I query that ? -
How to avoid Django Rest Framework logging extra info?
I am using Django Rest Framework. In settings.py I am using the following entry: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': str(BASE_DIR) + '/debugme.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } IN my code I just added logger.info('Checking Balance!') but when I checked debugme.log it dumped loads of unwanted info but the one I needed? Watching for file changes with StatReloader Waiting for apps ready_event. Apps ready_event triggered. Sending autoreload_started signal. Watching dir /muwallet_web/muwallet/locale with glob **/*.mo. Watching dir /usr/local/lib/python3.9/site-packages/rest_framework/locale with glob **/*.mo. Watching dir /usr/local/lib/python3.9/site-packages/django_extensions/locale with glob **/*.mo. Watching dir /muwallet_web/muwallet/api/locale with glob **/*.mo. (0.004) SELECT c.relname, CASE WHEN c.relispartition THEN 'p' WHEN c.relkind IN ('m', 'v') THEN 'v' ELSE 't' END FROM pg_catalog.pg_class c All I need to show info I need. -
Django - No CSRF error for posts without token
I'm using Django to host a React application. I added the CSRF protection middleware in Django. I tried testing it by sending a http post with Postman, without the x-csrftoken in the header. To my surprise, I did not get a 403, but I was able to get data without the x-csrftoken. How is this possible? Below you find my CSRF settings. My additional Django settings are very straightforward and include CORS. ... # Cross Origin Resource Sharing Protection CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:3000', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True # Cross Site Request Forgery Protection CSRF_TRUSTED_ORIGINS = [] MIDDLEWARE = [ ... 'django.middleware.csrf.CsrfViewMiddleware', ]