Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Random sort after distinct
I want to do is: Always return a random sort for my query Query result should not include duplicates Support Paging for that This is my query simplified # merge two queries and eliminate duplicates queryset = (items_no_cards | items_no_categories).distinct() # return a sort order queryset.order_by('?') If i do this ^ then it returns duplicated items with a random order, if i just do: # merge two queries and eliminate duplicates queryset = (items_no_cards | items_no_categories).distinct() # return a sort order queryset.order_by("-date_created") No duplicates but returns a sorted order. I know that i can use a python random function instead of doing .order_by('?') but i want to support paging, so it doesn't apply for this case. Thanks in advance -
Django URL and Vue Router Conflict
I have been searching high and low for some way to fix this problem and can't seem to find anything that will work. I appreciate any insight you can give. My project is built with Django and Vue and the router in Vue always picks of the URL to my /media directory, preventing files from being able to download properly. My Django URL setup looks like this: urlpatterns = [ # path('admin/', admin.site.urls), url(r'^admin/', admin.site.urls), path("accounts/register/", RegistrationView.as_view( form_class=CustomUserForm, success_url="/", ), name="django_registration_register"), path("accounts/", include("django_registration.backends.one_step.urls")), path("accounts/", include("django.contrib.auth.urls")), path("api/", include("users.api.urls")), path("api/", include("questions.api.urls")), path("api/", include("contacts.api.urls")), path("api/", include("filemanager.api.urls")), path("api-auth/", include("rest_framework.urls")), path("api/rest-auth/", include("rest_auth.urls")), path("api/rest-auth/registration/", include("rest_auth.registration.urls")), path(r"", IndexTemplateView.as_view(), name="entry-point") # re_path(r"^.*$", IndexTemplateView.as_view(), name="entry-point") ] if settings.DEBUG: urlpatterns += static( settings.STATIC_URL, document_root=settings.STATIC_ROOT ) urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) The Vue router looks like this: export default new Router({ mode: "history", routes: [ { path: "/", name: "home", component: Home }, { path: "/question/:slug", name: "question", component: Question, props: true }, { // the ? sign makes the slug parameter optional path: "/ask/:slug?", name: "question-editor", component: QuestionEditor, props: true }, { path: "/answer/:id", name: "answer-editor", component: AnswerEditor, props: true }, { path: "/contacts/", name: "contacts", component: ContactView, props: true }, { path: "/contacts/:id", name: "single-contact", component: SingleContactView, props: … -
How to add "public" by default to cached views by Django?
Im trying to use Google Cloud CDN to cache Django responses. Django properly sets the cache-control header with the max age, but it is missing the 'public' part of the header. Basically, currently all cached views have: cache-control: max-age=3600 But I want: cache-control: max-age=3600,public -
Question about integrating my python Django-Dash-Plotly app to a sub-domain in SquareSpace
I currently have a python app deployed using Django, which uses Dash-plotly as a critical aspect. All of my copy/content has to be done through source code, which works for me, but is not convenient for everyone. I have a friend that wants to help me with the copy/content website. So due to circumstances: I want to create a SquareSpace for the website, and then use a sub-domain to connect the python app. Would it make sense to keep my app deployed via Django (trimming down all unnecessary code)? And then just connect my app to the sub-domain? The last thing I want is for things to feel slowed down, I have my doubts that Django might be overkill for this specific case. How viable would this turn of events be in terms of development? -
How to set up chat rooms with limited access in Django? That is, we allow connections only from users registered in a particular chat room?
I recently joined a friend and his colleague in creating a social network-like website. I have sizeable programming experience, though no experience with Django. The friends have intermediate experience in general, but distinctly more with Django than me. We want to implement chat rooms, which behave similar to e.g. WhatsApp groups: Upon certain events, the server can add users to a particular chatroom and conversely also remove them. The users can send and recieve messages to and from that chatroom when connected and retrieve old messages which they missed since the last time they were online. My question is no to ask for the standard way to implement that system. We already have chat rooms where everyone can join via the right URL. However that is evidently not sufficient because we can't restrict access yet. Up to this point, we are using Django channels and we have set up the public chat rooms in accordance with the Channels Tutorial. I have already seen the django private chat package. However, I am reluctant to integrate that because I'm trying to avoid cluttering the project with packages and more importantly am trying to minimize the new technologies that we, particularily I, have … -
Mysterious Django API Behavior In Production
Long time reader but newly joined the community. I have a mysterious issue that I would like to seek help with. Since this is a part of the code that is currently running in production I need to redact parts of the info and will provide information is and when required. If needed I will also make a new sample code to make sure we can all test and also guide me the right way to troubleshoot the issue. Currently, there is an web application ( django/wagtail/coderedcms ) backend that need to be converted into a mobile app. To allow the mobile app to communicate with the Backend server, I have implemented an API endpoint using the Django-rest-framework. To authenticate the user, I have already implemented a simple authentication endpoint using Django-rest-simplejwt. This part is working fine. One of the requirement for the app is that the user must be able to view/update their profile through the mobile app. When working in dev server in my localhost, The behaviour is as intended, each user may login using the application, the backend will send back a token, and the tokan will be use subsequently to access the various part off the … -
Can't connect to PostGreSQL from a same-host container
I am using docker to manage my Django apps, and have the same configuration on my laptop and digital ocean : From my laptop I can connect to PostGreSQL thanks to the adminR image (https://hub.docker.com/_/adminer) But if I try to connect to PostGreSQL from adminer on the localhost, I can't : I can ping and find PostGreSQL from the django container : But I can't migrate my database from django scripts : Funny enough, I can migrate on the digital ocean cloud from my laptop : I can see the updated database on my laptop's admineR page : So the issue is obviously an issue of networking between the containers... But if I can ping the service, why can't django access it ???? -
How in django set in url unrequirement argument
All sense in title of query, i try this: path(r'get_turnover/<str:attributes>/\?product=(?P<product>\w+$)', views.OutputTurnover.as_view(), name='get_turnover') but it's not work for me. -
How can fix this error in python " ProgrammingError: 1064,"
Traceback (most recent call last): File "D:\current_task\Django\360ehs\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\current_task\Django\360ehs\ime360ehs\views.py", line 792, in createOrder cursor.execute(query + category_condition2 + " ORDER BY category") File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\mysql\base.py", line 74, in execute return self.cursor.execute(query, args) File "D:\current_task\Django\360ehs\env\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "D:\current_task\Django\360ehs\env\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "D:\current_task\Django\360ehs\env\lib\site-packages\MySQLdb\connections.py", line 239, in query _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY category' at line 1") category_condition1 = "" category_condition2 = "" count_left = 0 count_right = 0 category_counts = "SELECT category, COUNT(category) FROM tbl_products GROUP BY category ORDER BY COUNT(category) DESC" with … -
Cannot get frontend to run on localhost. nginx docker nuxt/express
I'm trying to configure nginx to serve frontend and backend of my app. My frontend is a nuxtjs application and my backend is django. I can access backend at localhost:8000 But I cannot access nuxt at localhost:3000 I'm using nginx as a reverse proxy. When I run npm run dev which uses the "nuxt" command my project builds successfully. I can't see anything in the logs and I don't know why localhost or 0.0.0.0 isn't getting any response or error when the frontend is build and running. How do I get the front to be mapped and served by nginx so I can access the api of django? ℹ [HPM] Proxy created: / -> http://backend:8000/api [HPM] Subscribed to http-proxy events: [ 'proxyReq', 'proxyRes', 'error', 'close' ] ℹ Listening on: http://172.19.0.5:3000/ ℹ Preparing project for development ℹ Initial build may take a while ✔ Builder initialized ✔ Nuxt files generated ℹ Compiling Client ℹ Compiling Server ✔ Server: Compiled successfully in 11.82s ✔ Client: Compiled successfully in 19.09s ℹ Waiting for file changes ℹ Memory usage: 212 MB (RSS: 337 MB) ℹ Listening on: http://172.19.0.5:3000/ docker-compose.yml version: '3.3' volumes: autobets_data: {} redis_data: networks: random_name: driver: bridge services: backend: build: context: ./backend … -
media file not serve in django with wihtenoise
Media files in Django are not visible and are not displayed. I used WhiteNews. like this: in wsgi.py i add this: application = WhiteNoise(application, root=BASE_DIR / 'static') application.add_files(BASE_DIR / 'media', prefix='mdeia/') in settings.py i add this: INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', . . . MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', . . . STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' STATIC_ROOT= BASE_DIR / 'static' STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT= BASE_DIR / 'media/' in html file : <img src="{{user.photo.url}}" style=" width:90px; height:90px; border-radius:50px 50px 50px 50px;"> and in models.py i using this: photo=models.ImageField(upload_to='users/photos/',default='user-photo.png',null=True,blank=True) I download static files without any problems and media files are saved without any problems but they are not downloaded. Thank you for your help. -
Django templates tag value separation
I have tag in my template {{ x.list }} which prints entire entry from database. Is there a way to print entries one by one separated by space? {{ x.list.1 }} prints first letter. -
Image uploaded but not saved in media and database Django
Am creating a settings page where the user should be able to chang there image and biodata. But only the biodata gets updated when I print the request.FILES.GET("profile_picture") it prints the name of the photo I uploaded. why is it not uploaded and saved to the database? Models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): profile_pic = models.ImageField(upload_to="images/", null=True ,blank=True) bio = models.TextField(max_length=100, blank=True) forms.py class ProfileForm(forms.Form): profile_picture = forms.ImageField(required=False ) bio = forms.CharField(label='Bio', max_length=100 ,widget=forms.Textarea()) views.py def settings(request): if request.user.is_authenticated: intial_data = { 'first_name': request.user.first_name, 'last_name': request.user.last_name, 'user_name': request.user.username, 'email':request.user.email, 'bio':request.user.bio } profile_form=ProfileForm(intial_data) if request.method == "POST": profile_form=ProfileForm(request.POST, request.FILES) if profile_form.is_valid(): user_name = profile_form.cleaned_data.get('user_name') profile_picture =request.FILES.get('profile_picture') bio = profile_form.cleaned_data.get('bio') user= User.objects.get(pk=request.user.id) if user is not None: user.profile_picture=profile_picture, user.bio=bio user.save() context ={ "profile_form":profile_form } return render(request, 'user/settings.html',context) return redirect('home') my_template.html <tr> <td>Bio</td> <td>{{profile_form.bio}}</td> </tr> <tr> <td>Update Profile Picture</td> <td>{{profile_form.profile_picture}}</td> </tr> -
Django and DataTables ignoring Read, Edit, Delete buttons after initial 10 results
I am using Django with DataTables and it is working fine, except for one part I have not been able to figure out what I am missing. I have a table that adds Actions to each row READ, UPDATE and DELETE buttons to perform CRUD actions on each row of data. The buttons depend on data-form-url being set to the url and id, like the below, which then pop up in a modal. <button type="button" id="read-file" class="inline-block bs-modal btn btn-sm btn-primary" data-form-url="{% url 'read_file' fileupload.id %}"> <span class="fa fa-eye"></span> </button> This only works for the first 10 entries initialized in the table. The buttons are dead for entries 11 and beyond, basically anything not initialized in the first view and paginated or hidden via the "show 10, 25, 50, 100 entries" dropdown. Can someone help me understand why the buttons are not working and how to activate them again for paginated or hidden rows? views.py class FileUploadListView(generic.ListView): model = FileUpload context_object_name = 'fileuploads' template_name = 'fileupload/file-list-view.html' #Filter view for current user def get_queryset(self): """Returns FileUploads that belong to the current user""" return FileUpload.objects.filter(my_user=self.request.user) html (for the file-table which is included into a base file) <table class="table table-striped table-sm table-bordered {% … -
Bootstrap 4, Card Style in HTML
I use bootstrap 4 cards to develop my blog which actually looks grate, however, when it is used on a mobile version, the picture of the posts shifts on the top and all the dimensions go random. I would like to have the box dimensioning but still be on the left. Basically avoiding the shift to the top in html. <div class="d-flex justify-content-center"> <div class="container"> <div class="row"> <div class="col-12"> {% for post in object_list %} <div class="card mb-3" style="max-width: 540px;"> <div class="row no-gutters"> {% if post.immagine %} <div class="col-md-4"> <img src="{{ post.immagine.url }}" class="card-img" width="200" height="260"> </div> {% else %} <div class="col-md-4"> </div> {% endif %} <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">{{ post.nome }} {{ post.cognome }} - </div> </div> </div> {% endfor %} -
Django split string from db and use in requests
I have tag {{ post.tags }} in template which prints all post tags from database. I would like to separate tags by space and use them in search function. Search function: def search_posts(request): query = request.GET.get('p') object_list = Post.objects.filter(tags__icontains=query) liked = [i for i in object_list if Like.objects.filter(user = request.user, post=i)] context ={ 'posts': object_list, 'liked_post': liked } return render(request, "feed/search_posts.html", context) -
Uncaught ReferenceError: $ajax is not defined
$ajax({ type: "POST", url: "/Unread", data: { htable: t, csrfmiddlewaretoken: "XgHM9ZCPEj9KaXa8OUoL2GLIBcv9SKPB56tTm7gVubudHPwwbrWpSO8hVP7mvBCP", }, success: function () { alert("done"); }, }); When i click on the SaveTable ("#saveTable") - it throws below error. Uncaught ReferenceError: $ajax is not defined at HTMLButtonElement. ((index):575)`` at HTMLButtonElement.dispatch (jquery-3.5.1.js:5429) at HTMLButtonElement.elemData.handle (jquery-3.5.1.js:5233) -
How to import whole python file and not break F403 flake8 rule?
Imports like this: from .file import * are "anti-patterns". How can I import one python file into another, without breaking flake8 F430 rule? I have settings.py in the Django project that I want to "overwrite" in test_settings.py like this, from settings import * # make tests faster DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'} to test with in-memory database, and I cant figure out how to do it without breaking the rule. -
When doing runserver, keep getting new data loaded in my database
Every time I do a: python manage.py runserver And I load the site, python gets data and puts this in my database. Even when I already filled some info in the database. Enough to get a view of what I am working on. Now it is not loading the information I want and instead putting in new information to add to the database so it can work with some data. What is the reason my data in the database is not being processed? And how do I stop new data being loaded into the database. -
ImportError: cannot import name 'Celery'
I'm trying to learn Celery i'm using Django 2.0 and celery 5.0.2 and my os is Ubuntu. This is my structure My project structure is: celery/ manage.py celery/ __init__.py cerely_app.py settings.py urls.py wsgi.py apps/ main/ __init__.py admin.py apps.py models.py task.py views.py test.py My configuration for cerely_app, based on documentation: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery.settings') app = Celery('celery') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') And my init.py: from .celery_app import app as celery_app __all__ = ('celery_app',) But when django give a error of import when i use command python3 manage.py runserver: $python3 manage.py runserver Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/brayan/Envs/celery/lib/python3.8/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/brayan/Envs/celery/lib/python3.8/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/home/brayan/Envs/celery/lib/python3.8/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/brayan/Envs/celery/lib/python3.8/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/brayan/Envs/celery/lib/python3.8/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in … -
RecursionError: maximum recursion depth exceeded in comparison in pylint
I have created many tests and all working fine on local and gihub CI but while check PyLint I'm getting this error RecursionError: maximum recursion depth exceeded in comparison. I would be great if you can help me. command running on server: DJANGO_SETTINGS_MODULE=projectname.settings.test_set pylint --generated-members=viridis --load-plugins pylint_django okko/apps/* --errors-only Error: File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/decorators.py", line 96, in wrapped res = next(generator) File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/bases.py", line 136, in _infer_stmts for inferred in stmt.infer(context=context): File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/util.py", line 160, in limit_inference yield from islice(iterator, size) File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/context.py", line 113, in cache_generator for result in generator: File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/decorators.py", line 132, in raise_if_nothing_inferred yield next(generator) File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/decorators.py", line 89, in wrapped if context.push(node): File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/context.py", line 89, in push if (node, name) in self.path: RecursionError: maximum recursion depth exceeded in comparison """ -
Adding Css in Django templates
I have been trying to apply css in the main.css on the class of (custom-card) but its not working. Anyone can find what's the mistake i'm doing. custom-card class is in home.html Below is the base.html in Django\mysite\blogapp\templates\blog\base.html . {% load static %} <!DOCTYPE html> <html> <head> <title>Home Page</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- CSS link --> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <!-- ================ HEADER NAVIGATION ========================= --> <section class="header"> <div class="container"> <nav class="navbar navbar-expand-lg "> <a class="navbar-brand" href="#"><span>e-</span>Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <i class="fa fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto text-center"> <!--ml auto used to have nav on right side,text-center used to make text in center when using mobile view--> <li class="nav-item"> <a class="nav-link active-home" href="{% url 'blog-homepage' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'blog-aboutpage' %}">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Our project</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Blog</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </nav> </div> </section> <!-- ================ HEADER NAVIGATION/ENDED ========================= --> <div class="container"> {%block homecontent%} {%endblock%} … -
Database Postgres in Docker with Django?
For example I Use defoult settings in Django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'database', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': '127.0.0.1', 'PORT': '5432', } When dockerize my db with depends_on: - db Should I change change my 'HOST' parameter '127.0.0.1' for 'db' could you explain this process thank you in advance -
Django Rest - "serializer.data" is empty dict() even though "serializer" has data with details
I was trying to implement password change based on some recommendations on stackoverflow but something which is really weird for me. After troubleshooting I got idea data my view is not working. Changing serializer actions to print I see data "serializer.data" is result "{}" even though "print(serializer)" give result. serializers.py class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField(max_length=128, write_only=True, required=True) new_password1 = serializers.CharField( max_length=128, write_only=True, required=True ) new_password2 = serializers.CharField( max_length=128, write_only=True, required=True ) def validate_old_password(self, value): user = self.context["request"].user if not user.check_password(value): raise serializers.ValidationError( { "old_passowrd": _( "Your old password was entered incorrectly. Please enter it again." ) } ) return value def validate(self, data): if data["new_password1"] != data["new_password2"]: raise serializers.ValidationError( {"new_password2": _("The two password fields didn't match.")} ) validate_password(data["new_password1"], self.context["request"].user) return super().validate(data) views.py class ChangePassword(UpdateAPIView): serializer_class = ChangePasswordSerializer permission_classes = [IsAuthenticated] def get_object(self, queryset=None): return self.request.user def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): # user.set_password(serializer.data.get("new_password1")) # user.save() print(serializer.data) return Response("Success", status=status.HTTP_204_NO_CONTENT) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) -
Stripe Checkout Webhook CSRF Error despite @csrf_exempt (Django)
I am using Stripe Checkout for my Django subscriptions. I tested webhooks via CLI locally - with success. Now I am moving the project to staging area and got a CSRF issue. The registered webhook throughs this message (my comments are already added): In general, this can occur when there is a genuine Cross Site Request Forgery, or when https://docs.djangoproject.com/en/2.2/ref/csrf/ Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. -> Yes, all cookies are accepted. Tests with different browsers led to the same result. The view function passes a request to the template's https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render “render” method. -> No template is being used, since Stripe Checkout provides the template. In the template, there is a “{% csrf_token %}” template tag inside each POST form that targets an internal URL. -> No, CSRF_TOKENS inside the html. No template is being used, since Stripe Checkout provides the template. If you are not using “CsrfViewMiddleware”, then you must use “csrf_protect” on any views that use the “csrf_token” template tag, as well as those that accept the POST data. -> I am using CsrfViewMiddleware. Funny fact: If I disable CsrfViewMiddleware, then webhooks are functioning. …