Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
aiogram: how to connect an inline keyboard from a function of another file with a bot file if this function will work in another code
Project (connection between DRF and bot with endpoints): -bot-directory (not in django project) : services.py and main.py in it -folders of django apps, manage.py etc. My function from services.py from bot directory def get_items_kb(): keyboard = InlineKeyboardMarkup() button1 = InlineKeyboardButton('Подтвердить', callback_data="yes") button2 = InlineKeyboardButton('Отклонить', callback_data="no") keyboard.row(button1, button2) return keyboard async def register_manager(CHAT_ID: str): bot = Bot(token='same') fake = Faker() username = fake.user_name() password = fake.password() await bot.send_message(CHAT_ID, f'Подтвердите:{username}\n{password}', reply_markup=get_items_kb()) Using of this function in django-signals (signals.py) @receiver(pre_save, sender=BotUser) def bot_user_manager_changed(sender, instance, **kwargs): if instance.id is not None: previous = BotUser.objects.get(id=instance.id) if not previous.manager and instance.manager: register_manager_sync = async_to_sync(register_manager) register_manager_sync(instance.user_id) main.py with bot in bot directory (in the same directory as the function, but different file) storage = MemoryStorage() TOKEN='same' bot = Bot(TOKEN) dp = Dispatcher(bot, storage=storage) @dp.callback_query_handler(lambda query: query.data == 'yes', state="*") @dp.callback_query_handler(lambda query: query.data == 'no', state="*") async def activate_manager_handler(callback_query: CallbackQuery, state: FSMContext): ... if __name__ == '__main__': executor.start_polling(dp,skip_updates=True) So all I want to do is get this inline keyboard to work and be caught by the handler when the function runs from django signals. Now, the function send a message, but inline-keyboard doesn't work. Expectation: Example of work: I change manager field to True in django-admin -> signal … -
React Native with Django backend how to make sure sure that only users with passed token can access images?
I am building a react native app with Django backend. In the app I let the users upload images which are stored in a models.FileField(). The problem I just noticed is that anyone can access the images from the backend server if they have the right link which raises privacy issues. How would the python and React Native code look like for making sure images that go into can be obtained only with passing a "POST" request which has a "user" and a "token" and how to put those images to be displayed with ? Thank you -
How to download a file from Azure FileShare with python?
How can i download a file from Azure Fileshare using python but i can't modify metadata in new file on local machine? When i download file using FileService or ShareFileClient (azure-storage or azure-storage-file libraries) it change creation date and modified date, so it download new file with metadata changed. I need to keep original metadata in downloaded file. #DOWNLOAD A FILE USING FILES SHARE AND SHAREFILECLIENT account_name = "account_name changed" account_key = "account_key changed" share_name = "share_name changed" file_name = "test.png" # Initialize the ShareServiceClient service_client = ShareServiceClient(account_url=f"https://{account_name}.file.core.windows.net", credential=account_key) # Get a reference to the file file_client = service_client.get_share_client(share_name).get_directory_client(None).get_file_client(file_name) print(file_client) file_props = file_client.get_file_properties() print(file_props) file_metadata = file_props.metadata print(file_metadata) local_file_path = "./test.png" I also try with external apps like rclone and it didn't work. -
How to filter a many-to-many field (not primary key) in a Django queryset for serialization with Django REST framework
Given two models with a many-to-many relationship between them. class Collection(models.Model): title = models.CharField(max_length=200, unique=True, verbose_name="Title") class Content(models.Model): author = models.CharField(max_length=200, unique=True, verbose_name="Author") collection = models.ManyToManyField(Collection, verbose_name="Collection") public = models.BooleanField(default=True, verbose_name="Public") How can I filter the Collection to only list Content where public == True? serializers.py: class ContentSerializer(serializers.ModelSerializer): class Meta: model = Content fields = ["author"] class CollectionSerializer(serializers.ModelSerializer): content_set = ContentSerializer(many=True, read_only=True) class Meta: model = Collection fields = [ "title", "content_set", ] view.py: class CollectionViewSet(viewsets.ReadOnlyModelViewSet): queryset = Collection.objects.all() serializer_class = CollectionSerializer permission_classes = [permissions.AllowAny] def get_queryset(self): return Collection.objects.filter(content_set__enable=True) # Not working as expected Desired output: [ { "title": "Foo", "content_set": [ { "author": "Jane Doe" } ] } ] -
Saleor custom url creation
I need to create a custom defined url like slug based on that some user data would be shown on the screen from the database but without authentication in saleor. from saleor.graphql.utils import get_current_user, create_login_and_password_url from saleor.core.utils.urlresolvers import reverse urlpatterns = [ path("my-custom-url/", my_custom_url, name="my-custom-url"), ] -
Django container CSRF verification fails
I made a container of my Django application and when I log in the app I get this error: Origin checking failed - https://127.0.0.1:8443 does not match any trusted origins. When I run the app in my pc I can log in without any issue. This error only occurs in the container. I declared in my compose file to trust the ip but still get the same error: DJANGO_CSRF_TRUSTED_ORIGINS: https://127.0.0.1:8443 -
how to deal with models in django
i have a problem how to create an login and register for a model that i create but nothing work good i try this for login def login_user(request): if request.user.is_authenticated: messages.success(request, "You are Already logged in ") redirect('/') else: if request.method == 'POST': form = login_client(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] client = authenticate(request, email=email, password=password) if client is not None: login(request, client) return redirect("/") else : form = login_client() return render(request, 'Login.html', {"form":form}) and for the register page i try this def register_user(request): if request.user.is_authenticated: messages.success(request, "You are Already logged in") return redirect("/") else : if request.method == 'POST': form = addNewClient(request.POST) if form.is_valid(): user = form.save() return redirect('login') else : form = addNewClient() return render(request, 'signup.html', {"form":form}) and this is the model in the file models.py class Clients(models.Model) : created_at = models.DateField(auto_now_add=True) idClient = models.AutoField(primary_key=True) first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) email = models.CharField(max_length=120, unique=True) username = models.CharField(max_length=120, unique=True) password = models.CharField(max_length=100) def __str__(self): return self.username -
Error After Uninstall in Shopify App Using Django
I am taking reference from https://github.com/Shopify/shopify_django_app repository to make a shopify app. The problem is that the app installs properly and works fine but the problem is that if we access App URL after it is uninstalled from shopify store, it returns the following error. I believe the error is because of the 'shop_login_required' decorator in shopify_app.decorator.py file. This decorator is used in login view in home.views.py file. Full Error Log:- Internal Server Error: / Traceback (most recent call last): File "D:\app\venv\lib\site-packages\pyactiveresource\connection.py", line 286, in _open http_response = self._handle_error(self._urlopen(request)) File "D:\app\venv\lib\site-packages\pyactiveresource\connection.py", line 316, in _urlopen return urllib.request.urlopen(request, timeout=self.timeout) File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 216, in urlopen return opener.open(url, data, timeout) File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 525, in open response = meth(req, response) File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 634, in http_response response = self.parent.error( File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 563, in error return self._call_chain(*args) File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 496, in _call_chain result = func(*args) File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 643, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 401: Unauthorized During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\app\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\app\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\app\shopify_django_app\shopify_app\decorators.py", line 12, in … -
How do I fix this error where I want to render templates which have static files
{% load static %} include 'accounts/navbar.html' %} block content %} endblock %} Our footer ` I wanted to render a page and it brought the following output. Invalid block tag on line 8: 'static,'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.2.4 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 8: 'static,'. Did you forget to register or load this tag? Exception Location: C:\Python311\Lib\site-packages\django\template\base.py, line 568, in invalid_block_tag Raised during: accounts.views.home Python Executable: C:\Python311\python.exe Python Version: 3.11.4 Python Path: ['D:\My_django_stuff\crm', 'C:\Python311\python311.zip', 'C:\Python311\DLLs', 'C:\Python311\Lib', 'C:\Python311', 'C:\Users\PATRICK -BITS\AppData\Roaming\Python\Python311\site-packages', 'C:\Python311\Lib\site-packages', 'C:\Python311\Lib\site-packages\vboxapi-1.0-py3.11.egg'] Server time: Fri, 11 Aug 2023 11:15:54 +0000 CRM ` -
Getting Unauthenticated warnings despite using permissions.AllowAny
This is my APIView as follows: class VerifyEmail(APIView): serializer_class = EmailVerificationSerializer token_param_config = openapi.Parameter( 'token', in_=openapi.IN_QUERY, description='Description', type=openapi.TYPE_STRING ) @permission_classes([permissions.AllowAny]) @swagger_auto_schema(manual_parameters=[token_param_config]) def get(self, request): token = request.GET.get('token') try: payload = get_payload(request) user = User.objects.get(id=payload['user_id']) if not user.is_verified: user.is_verified = True user.save() return Response({'email': 'Successfully activated'}, status=status.HTTP_200_OK) except jwt.ExpiredSignatureError as identifier: return Response({'error': 'Activation Expired'}, status=status.HTTP_400_BAD_REQUEST) except jwt.exceptions.DecodeError as identifier: return Response({'error': 'Invalid token'}, status=status.HTTP_400_BAD_REQUEST) It is asking for authentication despite me mentioning AllowAny. The complete code is hosted here -
Reverse for 'delete' with arguments '('',)' not found. 2 pattern(s) tried: ['delete/\\Z', 'delete/(?P<stock_id>[^/]+)\\Z']
I'm doing project with django. I'm getting an error when I run my code. I am trying to create a delete function on my webpage in a table . here is my code part from add_stock.html: {% if output %} {% for list_item in output %} <tr> <th scope="row">{{ list_item.0.companyName }}</th> <td>${{ list_item.0.latestPrice }}</td> <td>${{ list_item.0.previousClose }}</td> <td>${{ list_item.0.marketCap }}</td> <td>{{ list_item.0.ytdChange }}</td> <td>${{ list_item.0.week52High }}</td> <td>${{ list_item.0.week52Low }}</td> <td> <form action="{% url 'delete' item.id %}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-danger">Delete</button> </form> </td> </tr> {% endfor %} {% else %} <tr> <td colspan="8">You don't have stocks...</td> </tr> {% endif %} I'm also trying different links like : <form action="{% url 'delete' stock_id=list_item.0.id %}" method="POST"> Here is my delete functions: def delete(request, stock_id): if request.method == 'POST': item = Stock.objects.get(pk=stock_id) item.delete() messages.success(request, 'Stock Has Been Deleted!') return redirect('add_stock') and urls from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('about.html', views.about, name='about'), path('add_stock.html', views.add_stock, name='add_stock'), # path('delete_stock.html', views.delete_stock, name='delete_stock'), path('delete/<stock_id>', views.delete, name='delete'), path('delete/', views.delete, name='delete'), ] the strange thing - then I made new web page delete_stock.html - everything is working , but then I'm trying to do delete function in the same … -
Can't get request data
I have a viewset and a function with an additional address (decorator @action). In the serializer, I define an additional field through the SerializerMethodFieldenter image description here, and in order to define it, I need to know the user data through request.user. So the problem is, when the request goes through the viewset address (.../api/users/), everything is fine, but when it go through my additional address (.../api/users/subscriptions) there is no request data and i get this user = self.context.get('request').user AttributeError: 'NoneType' object has no attribute 'user' The serializer has no information about the request that went through @action viewset url @action url, self.context is empty -
How to shuffle my questions in django quiz?
I need to shuffle questions un mt Django quiz. There is my view: @login_required def test(request, test_id): test_set = get_object_or_404(TestSet, id=test_id) questions = test_set.question_set.all() user_test, created = UserTest.objects.get_or_create(user=request.user, test_set=test_set) user_answers = user_test.useranswer_set.all() correct_answers = sum(user_answer.selected_answer.is_correct for user_answer in user_answers) current_question_index = user_answers.count() find_percent = int(int(correct_answers) / len(questions) * 100) num_questions = questions.count() if current_question_index < num_questions: current_question = questions[current_question_index] if request.method == 'POST': form = QuestionForm(request.POST, question=current_question) if form.is_valid(): user_answer = form.cleaned_data['selected_answer'] user_test.useranswer_set.update_or_create(question=current_question, defaults={'selected_answer': user_answer}) return redirect('test', test_id=test_id) else: form = QuestionForm(question=current_question) else: return render(request, 'test_view.html', {'test_set': test_set, 'user_test': user_test, 'questions': questions, 'show_result': True, 'current_question': None, 'correct_answers': correct_answers, 'find_percent': find_percent}) return render(request, 'test_view.html', {'test_set': test_set, 'form': form, 'current_question_index': current_question_index, 'current_question': current_question, 'correct_answers': correct_answers}) I try to make random questions like: questions = test_set.question_set.all().order_by('?') But it doesn't work because questions can be repeated. How to solve this problem? -
Get an error while configuring celery for a django project with docker
When I start docker container with docker compose up command for some reason I get this error: celery-worker | Usage: celery [OPTIONS] COMMAND [ARGS]... celery-worker | Try 'celery --help' for help. celery-worker | celery-worker | Error: Invalid value for '-A' / '--app': celery-worker | Unable to load celery application. celery-worker | While trying to load the module backend.celery_app.app the following error occurred: celery-worker | Traceback (most recent call last): celery-worker | File "/usr/local/lib/python3.11/site-packages/celery/bin/celery.py", line 58, in convert celery-worker | return find_app(value) celery-worker | ^^^^^^^^^^^^^^^ celery-worker | File "/usr/local/lib/python3.11/site-packages/celery/app/utils.py", line 383, in find_app celery-worker | sym = symbol_by_name(app, imp=imp) celery-worker | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ celery-worker | File "/usr/local/lib/python3.11/site-packages/kombu/utils/imports.py", line 59, in symbol_by_name celery-worker | module = imp(module_name, package=package, **kwargs) celery-worker | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ celery-worker | File "/usr/local/lib/python3.11/site-packages/celery/utils/imports.py", line 104, in import_from_cwd celery-worker | return imp(module, package=package) celery-worker | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ celery-worker | File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module celery-worker | return _bootstrap._gcd_import(name[level:], package, level) celery-worker | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ celery-worker | File "<frozen importlib._bootstrap>", line 1206, in _gcd_import celery-worker | File "<frozen importlib._bootstrap>", line 1178, in _find_and_load celery-worker | File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked celery-worker | File "<frozen importlib._bootstrap>", line 690, in _load_unlocked celery-worker | File "<frozen importlib._bootstrap_external>", line 940, in exec_module celery-worker | File … -
get_object causes a ton of MySQL queries in my Django app
I am experiencing issues with MySQL queries. I've added get_object into MediaDetailView to achieve two slugs in URL pattern. This has increased the number of MySQL queries. The MySQL queries have gone from 6 to 36 and need 3ms to fetch all data from the database. As the website becomes filled with more content, the app produces even more MySQL queries. Within a Type model, I have three entries: channels, rooms, and groups. The objective is to create a URL structure such as localhost:8000/type_slug/handle_slug. - Here, the term "handle" is essentially regarded as the slug. MediaIndex cause all the MySQL queries. It is a view for the main/root page so it's important to optimize it. I use Django Debug Toolbar to analyze performance. (I don't see more info because I'm getting: 404: Not Found error). Any comments are welcome. Thank you. PYTHON views.py class MediaDetailView(DetailView): model = Media template_name = 'media_detail.html' # get_object may cause the issue ?! def get_object(self, queryset=None): type_slug = self.kwargs.get('type_slug') media_slug = self.kwargs.get('media_slug') media = get_object_or_404(Media, type__slug=type_slug, handle=media_slug) return media class MediaIndex(ListView): model = Media template_name = 'media/index.html' context_object_name = 'media_list' paginate_by = 200 models.py class Type(models.Model): title = models.CharField(max_length=200) description = models.TextField() slug = models.SlugField(max_length=100) … -
Authenticating with drango rest framework
I am just learning django and drf. I created a django app which authenticates user and i used default django views for it. (I made my own signup view as i needed to add user image). Now ive been asked to add apis to the same project using DRF. Should i use session authentication for it as the project is using it or implement the apis using token authentication? I'm quite lost on what to do. -
How to efficiently use Django bulk_update
def upload_file(request): if request.headers.get('x-requested-with') == 'XMLHttpRequest': file = request.FILES.get('file') righe = creatore_lista_numeri(file) data_fubatura = dt.now() # - timedelta(weeks=3) numeri_esistenti = set( NumeroDiTelefono.objects.values_list('numero', flat=True)) numeri_esistenti_da_confrontare = set(NumeroDiTelefono.objects.filter( Q(data_ultima_fubatura__lte=data_fubatura - timedelta(days=15)) | Q(data_ultima_fubatura=None)).values_list('numero', flat=True)) numeri_da_creare = [] numeri_gia_presenti = [] numeri_gia_presenti_da_confrontare = [] for riga in righe: numero_telefono = pulisci_numero_telefono(str(riga).strip()) if not numero_telefono: continue if numero_telefono not in numeri_esistenti: numeri_da_creare.append(NumeroDiTelefono( numero=numero_telefono, data_prima_fubatura=data_fubatura, data_ultima_fubatura=data_fubatura, fine_fubatura=data_fubatura)) numeri_esistenti.add(numero_telefono) else: numeri_gia_presenti.append(numero_telefono) if numero_telefono in numeri_esistenti_da_confrontare: # numero_da_modificare, created = NumeroDiTelefono.objects.update_or_create( # numero=numero_telefono, # defaults={ # 'data_ultima_fubatura': data_fubatura, # 'fine_fubatura': data_fubatura # } # ) numero_da_modificare = NumeroDiTelefono.objects.get( numero=numero_telefono) numero_da_modificare.data_ultima_fubatura = data_fubatura numero_da_modificare.fine_fubatura = data_fubatura numero_da_modificare.save() numeri_gia_presenti_da_confrontare.append(numero_da_modificare) numeri_creati = NumeroDiTelefono.objects.bulk_create(numeri_da_creare) lista_numeri_presenti = [numero.numero for numero in numeri_creati] numeri_da_creare = serializers.serialize('json', numeri_da_creare) numeri_gia_presenti_da_confrontare = serializers.serialize( 'json', numeri_gia_presenti_da_confrontare) data = { 'nome_file': file.name, 'numeri_da_creare': numeri_da_creare, 'lista_numeri_presenti': lista_numeri_presenti, 'numeri_gia_presenti': numeri_gia_presenti, 'numeri_gia_presenti_da_confrontare': numeri_gia_presenti_da_confrontare, } return JsonResponse(data) As you may see, I am basically creating or updating a list of phone numbers. My problem here is that the function works but, especially for the updating part, is totally inefficient. I have to create or update thousands of records. While creating is very fast, updating is extremely slow. I tried with the update_or_create, update or the classic get and save methods but none … -
Django: @action Method \"GET\" not allowed
I have an issue with one of my ViewSets that I don't know what to do about. It seems the methods I want to add using action are not registered properly and I get a MethodNotAllowedError. Here's a stripped-down version: from drf_spectacular.utils import extend_schema from rest_framework import mixins, viewsets, status from rest_framework.decorators import action from rest_framework.response import Response from error_database.models import DeviceConfigType from error_database.permissions import AllowAnyReadAccessOrHasWritePermission from error_database.serializers import DeviceConfigTypeSerializer class DeviceConfigTypeViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet ): queryset = DeviceConfigType.objects.all() serializer_class = DeviceConfigTypeSerializer lookup_field = "type" permission_classes = [AllowAnyReadAccessOrHasWritePermission] def get_queryset(self): return self.queryset.filter(release=self.kwargs['release_version_number']) def create(self, request, *args, **kwargs): # (some code) return Response(status=status.HTTP_201_CREATED) def destroy(self, request, *args, **kwargs): # (some code) return Response(status=status.HTTP_204_NO_CONTENT) @extend_schema( request=DeviceConfigTypeSerializer, responses={status.HTTP_201_CREATED: DeviceConfigTypeSerializer(many=True)}, ) @action( detail=True, methods=['get'], url_path=r'versions', url_name='config-type-list-versions', ) def list_versions(self, request, *args, **kwargs) -> Response: # (some code) return Response(status=status.HTTP_200_OK) @action( detail=True, methods=['get'], url_path=r'versions/(?P<version_id>\d+\.\d{1,3})', url_name='config-type-version-get', ) def get_version(self, request, *args, **kwargs): # (some code) return Response(status=status.HTTP_200_OK) @action( detail=True, methods=['delete'], url_path=r'versions/(?P<version_id>\d+\.\d{1,3})', url_name='config-type-version-delete', ) def destroy_version(self, request, *args, **kwargs): # (some code) return Response(status=status.HTTP_204_NO_CONTENT) The model in the background should handle two different keys: "config_type" and "version_id", with an API like this: /releases/{release_version_number}/config_type/{config_type}/versions/{version_id} I have working tests for the ViewSets like this: view = DeviceConfigTypeViewSet.as_view({'get': 'get_version'}) response … -
How to get boolean value from a JSONfield in Django?
I stored data into a JSONField in the form below, but when I access the data the boolean value remains as a string. What is the proper way to tell Django to automatically convert it into boolean ? obj.js = {"fast": 3, "slow": 6, "shift": "True", "signal": 2} obj.save() > obj.js['shift'] "True" I would like to avoid doing eval(obj.js['shift']) for security reason. -
Where is the best place to put external service client in Django?
Is there any best practice to put external service client code in Django? I want the client to be initialized only once and can be used globally in Django? For example I want to integrate ClickHouse and Meilisearch into Django, where I can put the clients? -
Django running async code in WSGI mode causes SynchronousOnlyOperation error
Our Django 4.1 website is running on a WSGI server. We are not ready to convert the entire website to ASGI but we rewrote an io-intensive operation in asyncio mode and called it in the view function as follows: async def utility_func(urls): await asyncio.gather(download_from_urls) class MyView(generic.edit.FormView) def form_valid(self, form): asyncio.run(utility_func(form.cleaned_data['urls'])) In our view, this has nothing to do with Django's async support because the view function is running in sync mode and the server is running on WSGI and there is no system event loop. However, when the view functions runs a little longer (e.g. > 5s), we notice some other parts of the website start to throw exceptions like SynchronousOnlyOperation You cannot call this from an async context - use a thread or sync_to_async. This happens to requests such as our health-check call path("is_alive/", lambda x: HttpResponse()), They are all straight sync views and have never thrown the SynchronousOnlyOperation exceptions before. Can anyone tell us what is happening here? The best guess we have is that when the asyncio.run() is running, the lambda function, which performs a completely unrelated task, is somehow executed in the async environment and causes the exception. If this is the case, how can we … -
How to seed a django model with foreign key and many to many fields at the same time?
i want to know the method of seeding for m2m and foreign key fields in a model of django automatically i use django fixtures but it is all manual system. i would like to know to automated way to do the fill the database.I want to know is there any way to make it rather than fixtures in eaborative way. -
Django manage test outputting progress percentage
I use Django 3.2 to run some tests using python -m manage test --parallel --verbosity=3. In other projects, I use pytest and this gives a test suite percentage on the right: How can one get Django's manage test to output something similar? -
Is there a way to determine which django db a pytest test function is currently running against?
Is there a way to know which database a test is currently running against from within the test itself? i.e. I have a test setup like so, and I have two databases configured pytestmark = pytest.mark.django_db(databases=["db1", "db2"]) def test_case_1(fixture_stuff): print("What db is this running on?") Is there a way for me to add the current db to that print statement? -
array is not acting like an array and i don't know what to do
I am making a react application with django backend. So for protected routes i am doing something like this. <Route element={<RequireAuth allowedRoles={['admin']}/>}> <Route path='admin' element={<Admin />} /> </Route> And in RequireAuth.js I have this: const RequireAuth = (allowedRoles) => { const location = useLocation() const userdata= JSON.parse(localStorage.getItem('user')) || {} return ( (allowedRoles.includes(userdata.user.role)) ? <Outlet /> : userdata?.token ? <Navigate to='/unauthorized' state={{ from: location }} replace /> :<Navigate to='/login' state={{ from: location }} replace /> ) } Doing this also causes the same error, how do I use props in react if not like this :( (allowedRoles.includes(localStorage.getItem('user.role'))) With some help from a youtube tutorial by Dave Gray, as his method wasn't working, i just opted to use local storage cause i am getting tired but even using local storage, i get the same error allowedRoles.includes is not a function TypeError: allowedRoles.includes is not a function But allowedRoles is an array I think, I had this <Route element={<RequireAuth allowedRoles='[admin]'/>}> didn't work so I did this <Route element={<RequireAuth allowedRoles={['admin']}/>}> still No. In my login I am storing the userdata response as const response = await axios.post(`http://localhost:8000/login/`, JSON.stringify({ email, password }),{headers:{"Content-Type":"application/json"}}) console.log(JSON.stringify(response.data)) localStorage.setItem('user',JSON.stringify(response.data) || []) This is the console log: {"token":"2a4d51f5f7132564115e89310487115ba4138c46","user":{"id":1,"email":"admin@admin.com","first_name":"admin","last_name":"admin","role":"admin"}} I am using …