Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"detail": "Authentication credentials were not provided." Django-rest-frameweork and React
I'm trying to create Club object via React form but I get those 2 errors: {"detail": "Authentication credentials were not provided."} and 401 Unauthorized. Obviously there is something wrong with authorisation, I tested it with postman and it did not work, however when I tried with http://127.0.0.1:8000/api/clubs/ everything worked. I am pasting all of my code below. frontend/CreateClub.js import React, {useEffect, useState} from 'react'; import { useNavigate } from 'react-router-dom'; import Base from '../base/Base'; import { isAuthenticated } from '../user/helper/userApiCalls'; import { getAllClubs, createClub } from './helper/apiHelper'; const CreateClub = () => { const [clubName, setClubName] = useState(''); const [clubs, setClubs] = useState([]); const [nameTaken, setNameTaken] = useState(false); const navigate = useNavigate(); useEffect(() =>{ if (!isAuthenticated()) { navigate('/login') } else { loadClubs(); } },[]) const loadClubs = () => { getAllClubs() .then((data) => { setClubs(data); }) .catch((error) => console.log(error)); } const handleChange = (event) => { setClubName(event.target.value) } const onSubmit = (event) => { event.preventDefault(); if (checkExistingClubNames(clubName, clubs)) { const owner = isAuthenticated().user; const name = clubName; createClub({owner, name}) .then((data) => { if (data.name === clubName) { setClubName(''); setNameTaken(false); navigate('/'); } }) .catch((error) => console.log(error)); } else { setNameTaken(true); } } const checkExistingClubNames = (newClubsName, existingClubs) => { const filteredClubs … -
trying to send data from python to html
I'm scraping some content and trying to display on html page but it display nothing when i try to run jinja loop for dictionary i sent from python file, it runs every variable separately but not running loop on dictionary Python dictionary i'm trying to display dictionary = dict( [('page_title', url), ('title', title), ('anchor', anchor), ('images', images)]) Html code with jinja tags <div id="dictionary"> {% for items in dictionary %} <div class="card" style="width: 18rem;"> <img src="{{ items.images }}" class="card-img-top" alt="{{ items.title }}"> <div class="card-body"> <a href="{{ items.anchor }}" class="btn btn-primary"><h5 class="card-title">{{ items.title }}</h5></a> </div> </div> {% endfor %} -
Problems using createview on heroku
I was working locally and 3 Create Views worked perfectly for me to upload data. I passed it to Heroku and sadly out of the 3, only one CreateView works for me, any idea what it could be? I already reviewed the code and it is very similar both in views and in the template. The problem is that when I click the save button it doesn't do anything, it doesn't save anything and it doesn't take me to any link, but it seems strange to me that locally it worked quite well and not on heroku models class Carro(models.Model): placas=models.CharField(max_length=255) año=models.IntegerField() marca=models.CharField(max_length=255) modelo=models.CharField(max_length=255) tipo=models.CharField(max_length=255) motor=models.CharField(max_length=255, default='0') vin=models.CharField(max_length=255) color=models.CharField(max_length=255) agente_seguros=models.CharField(max_length=255) compañia_seguros=models.CharField(max_length=255) no_politica=models.CharField(max_length=255) cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.placas} {self.año}{self.marca} {self.modelo} {self.tipo}{self.motor}{self.vin}{self.color}' \ f'{self.agente_seguros}{self.compañia_seguros}{self.no_politica}{self.cliente}' views class create_carros(CreateView): model=Carro form_class=CarroForm template_name='carros/carros-form-add.html' success_url=reverse_lazy('carros:list_cars') -
Django ajax how to add load more functionality?
I am implementing ajax for real-time updating data in my html page without refreshing or reloading page. Now I am thinking to add functionality for load more content by click on load more button or scroll down. Right now my all content displaying in html page. Assume I have 100 object and I want to load only 10 object at a time. If user click on load more button or scroll down then it will load another 10 object. here is my code: views.py class PostJsonListView(View): def get(self, *args, **kwargs): posts = list(Blog.objects.all().filter(is_published='published') ) data = list() for i in posts: blog_cover_image = None if i.blog_cover_image: blog_cover_image = i.blog_cover_image.url data.append({'author_first_name':str(i.author.first_name),'author_last_name':str(i.author.last_name),'blog_cover_image':blog_cover_image,'title':i.title,'body':i.body,'slug':i.slug,'created_at':i.created_at.strftime("%A, %d. %B %Y %I:%M%p")}) return JsonResponse({'data':data},safe=False) html <script> const postsBox = document.getElementById('posts-box') $(document).ready(function(){ setInterval (function(){ $.ajax({ url: '/posts-json/', type: 'get', success: function (response){ $("#posts-box").empty(); for (var key in response.data){ console.log(response.data[key].title) if (response.data[key].blog_cover_image){ postsBox.innerHTML += `<div class="card mb-4"> <img class="img-fluid rounded" style="max-height:300px;max-width:900px;" src=${response.data[key].blog_cover_image} alt="..." /> <div class="card-body"> <h2 class="card-title"><a href=${response.data[key].slug}>${response.data[key].title}</a></h2> <a class="btn btn-primary" href=${response.data[key].slug}>Read More →</a> </div> <div class="card-footer text-muted"> Posted on (${response.data[key].created_at}) <div class="author">${response.data[key].author_first_name}&nbsp${response.data[key].author_last_name}</div> </div> </div>` } else{ postsBox.innerHTML += `<div class="card mb-4"> <img class="img-fluid rounded" style="max-height:300px;max-width:900px;" src="https://via.placeholder.com/900x300" alt="..." /> <div class="card-body"> <h2 class="card-title"><a href=${response.data[key].slug}>${response.data[key].title}</a></h2> <a class="btn btn-primary" href=${response.data[key].slug}>Read More … -
Django: Autofocus different widgets depending on content
I have a form with two fields. I want to autofocus the first if it is empty, but autofocus the second if the first has content (from the initial= argument). How can this be done? It seems that changing the widget attribute after the form has been created doesn't work. # Build edit form initial = { 'title': area_title, } area_form = AreaForm(initial=initial) if len(area_title) > 0: # Focus description if title already exists area_form.fields['description'].widget.attrs['autofocus'] = 'autofocus' else: # Otherwise focus title area_form.fields['title'].widget.attrs['autofocus'] = 'autofocus' -
Django Cloudflare Proxy "CSRF Verification Failed"
I'm trying to proxy my Django App through Cloudflare via workers. The setup is like so: example.com/app/* forwards to my Django site ~everything else~ forwards to my Webflow site So far that part is working! However, I can't get Django to accept CSRF validation. Here are the headers for the request (scrubbed for identity purposes) { 'HTTP_HOST': 'fluent-spring.uc.r.appspot.com', 'HTTP_X_FORWARDED_FOR': '70.192.78.2', 'HTTP_X_FORWARDED_PROTO': 'https', 'HTTP_FORWARDED': 'for="172.70.0.123";proto=https', 'HTTP_CF_WORKER': 'example.com', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_CF_RAY': '6d2a89b3435e8c3b-EWR', 'HTTP_CF_VISITOR': '{"scheme":"https"}', 'HTTP_CF_EW_VIA': '15', 'HTTP_CDN_LOOP': 'cloudflare; subreqs=1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.9', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'HTTP_CACHE_CONTROL': 'no-cache', 'HTTP_REFERER': 'https://fluent-spring.uc.r.appspot.com/', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36', 'HTTP_CF_CONNECTING_IP': '70.19.78.2', 'HTTP_ORIGIN': 'https://www.example.com', 'HTTP_PRAGMA': 'no-cache', 'HTTP_SEC_CH_UA': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"', 'HTTP_SEC_CH_UA_MOBILE': '?0', 'HTTP_SEC_CH_UA_PLATFORM': '"macOS"', 'HTTP_SEC_FETCH_DEST': 'document', 'HTTP_SEC_FETCH_MODE': 'navigate', 'HTTP_SEC_FETCH_SITE': 'same-origin', 'HTTP_SEC_FETCH_USER': '?1', 'HTTP_X_CLOUD_TRACE_CONTEXT': '959632cd27b84e7aad1a5e3c71f1d8a3/18242229191417730943', 'HTTP_COOKIE': 'csrftoken=GHjnkrOrhave8EJ1eayWxxaSZiaxu5JJcJAaI1dmzc5Tdnb9T1YwaXvYUDr5ZQ83', 'HTTP_X_APPENGINE_CITYLATLONG': '40.735657,-74.172367', 'HTTP_X_APPENGINE_COUNTRY': 'US', 'HTTP_X_APPENGINE_CITY': 'newark', 'HTTP_X_APPENGINE_REGION': 'nj', 'HTTP_TRACEPARENT': '00-959632cd27b84e7aad1a5e3c71f1d8a3-fd296acc51b7177f-00', 'HTTP_X_APPENGINE_TIMEOUT_MS': '599998', 'HTTP_X_APPENGINE_HTTPS': 'on', 'HTTP_X_APPENGINE_USER_IP': '172.70.230.1', 'HTTP_X_APPENGINE_API_TICKET': 'ChBkODIxOGU1YjRmMWE5NDlmGhMI2KyFxePK9QIVY049Ah0P8gjM', 'HTTP_ACCEPT_ENCODING': 'gzip', 'HTTP_X_APPENGINE_REQUEST_LOG_ID': '61eecfb100ff02c818a28bb9f40001737e666c75656e742d737072696e672d3333303332310001323032323031323474313035373136000100', 'HTTP_X_APPENGINE_DEFAULT_VERSION_HOSTNAME': 'fluent-spring-.uc.r.appspot.com' } And the error I get in the logs is Forbidden (CSRF token missing or incorrect.): /app/sadmin/login/ And on the screen is: CSRF verification failed. Request aborted. And my CSRF settings in my settings.py are: CSRF_TRUSTED_ORIGINS = [ "www.example.com", "example.com", "kevin-dot-fluent-spring.uc.r.appspot.com", "fluent-spring.uc.r.appspot.com", "localhost", "https://www.example.com", "https://example.com", ] -
Passing OpenAPI specs to Frontend framwork using DRF
The DRF app is very transaction heavy, it has lots of POST endpoints which expect forms. Some of these forms are 30+ input fields long. My plan is to now request the form that is requiered by the endpoint before I render it in the frondend. I got this idea from learning about the OPTION request, it returns a json that looks as following: { "name": "Snippet List", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { <------------------------- "id": { "type": "integer", "required": false, "read_only": true, "label": "ID" }, "title": { "type": "string", "required": false, "read_only": false, "label": "Title", "max_length": 100 }, It gets really interesting in the POST section of the json. Here every field that the API expects is listed, with the label, the type and abviosuly the key. But how do I request this data in the frondend. Also, I don't believe the OPTION request is ment for this. That's why I want to use OpenAPI specs for this. I've read a bit in the Django Docs and was able to create OpenAPI specs for my entire website but I somehow need specs that I can request per endpoint. … -
unable to import models to nested sub-directory django
Here is my project tree: (base) justinbenfit@MacBook-Pro-3 cds_website % tree . ├── api │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── serializers.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── admin.py │ ├── apps.py │ ├── main.py │ ├── management │ │ ├── __init__.py │ │ ├── commands │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ └── private.cpython-39.pyc │ │ │ ├── private.py │ │ │ └── scrape.py │ │ └── test.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ ├── 0001_initial.cpython-38.pyc │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── cds_website │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py └── requirements.txt api is an app in a greater project called cds_website. The settings.py file in cds_website project directory contains the following installed apps: INSTALLED_APPS = [ … -
[Celery]CELERYD_NODES where is this configuration used?
In the celery document CELERYD_NODES, I found such a configuration, but I didn't find any place to use it in the celery source code. Is this configuration really useful? -
Django How to escape special character and use slice method in HTML template for json data
before applying json method I was using this {{filt.body|striptags|safe|slice:":250" }} in my html template for escape all special character. Now my data loading from json and how to apply above method in my html template. models.py class Blog(models.Model): body = RichTextUploadingField() views.py class PostJsonListView(View): def get(self, *args, **kwargs): posts = list(Blog.objects.all().filter(is_published='published') ) data = list() for i in posts: data.append({'body':i.body}) return JsonResponse({'data':data},safe=False) -
Get latest related item for each item in QuerySet
I have a simple model of an Observation made by a Sensor: class Observation(models.Model): class ObservationType(models.TextChoices): PM25 = 'pm25_kal', 'PM2,5' PM10 = 'pm10_kal', 'PM10' RH = 'rh', _('Relative humidity') TEMP = 'temp', _('Temperature') date_time = models.DateTimeField() sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE) obs_type = models.CharField(max_length=8, choices=ObservationType.choices) value = models.DecimalField(max_digits=6, decimal_places=3) What I want to do, is get a list or QuerySet with the latest Observation of a certain type that should at least have been created within 24 hours, for each sensor. I solved the problem using a model method for my Sensor model and a custom QuerySet for my Observation model, to filter recent observations. class ObservationQuerySet(models.query.QuerySet): def recent(self): return self.filter(date_time__gte=timezone.now() - timedelta(days=1)) def latest_recent_observation(self, obs_type): try: return self.observation_set.filter(obs_type=obs_type).recent().latest('date_time') except Observation.DoesNotExist: return None I can loop over all sensors and get the latest_recent_observation() for each of them, but for larger datasets it is pretty slow. Is there any way to make this more efficient? -
Can i use model function when i do django orm query?
I have a model like: class User(AbstractUser): ... some fields longitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def get_range_between(self, lon, lat): return great_circle(self.longitude, self.latitude, lon, lat) And i like call this get_range_betwen func when i do this query: User.objects.annotate(range=model_in_query.get_range_func(lon, lat)) something like this. How i can realize this in my code and is it evan real? -
how to update an object when several other related objects get created
I have to add a progress_level field to my User model that shows where does this user stand at the moment so I added a field to the user model like this: progress_level = models.CharField(max_length=25, null=True, choices=USER_PROGRESS_LEVELS) I want this field to automatically update itself whenever an action gets done by the user. for instance, if the user completes their contact info and document info and submit their forms, the progress level should change to [1][0]. I really dont know how to do this but I created a signal like this: @receiver(pre_save, sender=User, dispatch_uid='progress_change') def progress(sender, instance, **kwargs): user = instance if DocumentInfo.objects.filter(user=user).exists() and ContactInfo.objects.filter(user=user).exists(): user.progress_level = USER_PROGRESS_LEVELS[1][0] it works fine but it activates only if I save the User model. how can I prevent that? how can I activate this signal whenever that statement is true? please help me thanks -
Django mypy operator error on queryset aggregate with F
I have the following code to get an average over all of my objects: from django.db.models import Avg, F from django.utils.timezone import now from main.models import Dog def get_dog_average_update_time() -> int: """Get the average update time delta in seconds.""" q = Dog.objects.all().aggregate( avg_update=Avg(now() - F("last_updated")) ) return int(q["avg_update"].total_seconds()) I've tested the code and it seems to work but I get an error from mypy: test.py: error: No overload variant of "__sub__" of "datetime" matches argument type "F" [operator] avg_update=Avg(now() - F("last_updated")) ^ test.py: note: Possible overload variants: test.py: note: def __sub__(self, timedelta) -> datetime test.py: note: def __sub__(self, datetime) -> timedelta And this is my setup.cfg config for mypy, I'm using the Django stubs: [mypy] ignore_missing_imports = True show_error_codes = True plugins = mypy_django_plugin.main [mypy.plugins.django-stubs] django_settings_module = "settings" I'm not sure to understand the problem here, can someone help me ? -
django setUpTestData doesn't run
Here is my test: class FirstTestCase(TransactionTestCase): @classmethod def setUpTestData(cls): Car.objects.create(id=10001) def findAllCars(self): print(list(Car.objects.all())) this gives no errors, and the list is simply printed as [], when clearly it should be [10001] I know tests aren't supposed to inlude print statements, this is just an easy way to illustrate that for some reason the object in setUpTestData is not being created. How can I get it to make this object? -
Find unused resources using SDK
Is there any good way to find unused resources on subscription using python SDK? I found info about changed time using ResourceManagementClient but I dont think it is the best source. -
After overriding create function, how to the get the id of the newly created object in django?
I have a ModelViewSet and I want to perform some more operations on the newly created object. But I am unable to get the newly created object id here. How to get the newly created object id after the super()? def create(self, request, *args, **kwargs): phone = request.data.get('student_phone_number') batch_id = request.data.get('batch_id') class_number = request.data.get('class_number') if not any([phone, batch_id, class_number]): return Response({"message": "Missing Params"}, status=status.HTTP_400_BAD_REQUEST) if self.queryset.filter(student_phone_number=phone, batch_id=batch_id, class_number=class_number, is_cancelled=False).exists(): return Response({"message": "Compensation class already booked"}, status=status.HTTP_400_BAD_REQUEST) super().create(request, *args, **kwargs) -
Save a list of data from the checkbox inside my database with django
I've a small problem, i'm trying to save some checkbox values in my database multiple times with django in differents rows. For example, if the user select the checkbox 'France', 'Belgium' and 'USA' i'd like to have in my database: country_name mover France 1 Belgium 1 USA 1 Models.py class Mover_Country(models.Model): country_name = models.CharField(max_length=300) mover = models.ForeignKey(Mover, on_delete=models.CASCADE) html file <!-- Form START --> <form class="row g-3 mt-2 position-relative z-index-9" method="POST"> {% csrf_token %} <!-- Company Name --> <div class="col-lg-12"> <div class="form-check"> {% for data in countries %} <input class="form-check-input chkvalues" type="checkbox" value="{{data.name}}" name="country_name[]"/> <label class="form-check-label"> <h4>{{data.name}}</h4> </label></br> {% endfor %} </div> </div> <!-- other informations --> <input type="text" name="name" id="txtvalues"/> <input type="hidden" name="mover_id" value="{{mover_information.id}}"> </br> <!-- Button --> <div class="col-12" align="center"> <button type="submit" class="btn btn-primary mb-0">Continuer vers l'étape 4</button> </div> </form> <!-- Form END --> views.py def mover_inscription_step3(request, mover_pk): mover_information = get_object_or_404(Mover, pk=mover_pk) countries = Country.objects.all() if request.method == 'POST': mover_id = request.POST.get('mover_id') if request.POST.get('country_name'): country_name = request.POST.get('country_name') mover = get_object_or_404(Mover, id=request.POST.get('mover_id')) savedata = Mover_Country(country_name=country_name, mover=mover) savedata.save() messages.success(request, 'Informations ajoutées avec succès !') return redirect('mover_inscription_step4', mover_pk=mover_id) else: messages.error(request, 'Veuillez faire au moins une sélection !') return redirect('mover_inscription_step3', mover_pk=mover_id) return render(request, 'base_app/mover/mover_inscription_step3.html', {'mover_information': mover_information, 'countries': countries}) Thanks ! -
HTMX parsing JSON response issue
I have a page that posts some data to the Django back-end and JSON response is returned. I have an issue parsing this using templates. Any help would be appreciated. Thank you in advance. <div class="card-body"> <form> {% csrf_token %} <div class="input-group mb-3"> <label class="input-group-text">Command</label> <select class="form-select" name="run_show_command" id="run_show_command"> <option selected disabled>Choose...</option> <option value="{{ data.version.id }}:1">show ip interface brief</option> <option value="{{ data.version.id }}:2">show interfaces description</option> <option value="{{ data.version.id }}:3">show ip arp</option> <option value="{{ data.version.id }}:4">show ip route</option> <option value="{{ data.version.id }}:5">show ip cef</option> <option value="{{ data.version.id }}:6">show version</option> </select> <button type="submit" class="btn btn-sm btn-success" hx-post="{% url 'inventory:device_run_command' %}" hx-target="#command_output" mustache-template="m_template" hx-indicator="#loader_bars"> <i class="fas fa-terminal"></i> Run </button> </div> </form> <div class="d-flex justify-content-center" hx-ext="client-side-templates" id="command_output"> <img id="loader_bars" class="htmx-indicator" alt="Loading..." src="{% static 'images/loaders/bars.svg' %}"/> <template id="m_template" type="text/mustache"> {% for data in dataset %} {% for key, value in data.items %} <li>{{ key }} {{ value }}</li> {% endfor %} {% endfor %} </template> </div> </div> JSON: [{ "intf": "GigabitEthernet1", "ipaddr": "10.10.20.48", "status": "up", "proto": "up" }, { "intf": "GigabitEthernet2", "ipaddr": "unassigned", "status": "administratively down", "proto": "down" }, { "intf": "GigabitEthernet3", "ipaddr": "unassigned", "status": "administratively down", "proto": "down" }, { "intf": "Loopback1", "ipaddr": "10.10.10.100", "status": "up", "proto": "up" }, { "intf": "Loopback123", "ipaddr": "unassigned", … -
I am getting some problem while login from jwt token, I can get token but getting some problem as authentication not provided ? In Django from API
Hello Everyone Can Anyone Please Help me I am getting some problems while logging the user. I can get proper tokens also but can't authenticate that. I am Getting an Error as Below also while getting the token too. HTTP 401 Unauthorized Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: JWT realm="api" { "detail": "Authentication credentials were not provided." } In setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webapi.apps.WebapiConfig', 'corsheaders', 'rest_framework', 'ratings', # 'rest_framework.authtoken', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', 'rest_auth', 'phone_field', 'phonenumber_field', 'djoser', 'users.apps.UsersConfig', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('JWT',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } At urls.py from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView, ) urlpatterns = [ path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] -
How to read env vars from settings in django unittest?
I am new to unittesting. I want to read some env vars in django unittests, but I am having some troubles when trying to read the env var from django.conf.settings, but I can read the env var using os.environ.get(). How can I access the current env var from django.conf.settings? The test code looks like the following: from unittest.mock import patch def test_functionality_in_non_production_environments(self): with patch.dict('os.environ', { 'ENVIRONMENT': 'local', 'ENV_VALUE': 'test_env_value', }): from django.conf import settings print(settings.ENV_VALUE) # --> DOES NOT PRINT 'test_env_value' print(os.environ.get('ENV_VALUE')) # --> PRINTS 'test_env_value' I am trying to test the correct behaviour of the code depending on the env var. In some parts of the code there is some logic like: if settings.ENV_VALUE and setting.ENVIRONMENT == 'local': # do some stuff -
ImportError: cannot import name from partially initialized module Django
I'm facing an issue which I don't know why the error occurs, please help me to resolve this error: error: ImportError: cannot import name 'User' from partially initialized module 'authentication.models' (most likely due to a circular import) (/app/authentication/models.py) User model: from projects.models import Organization class User(AbstractBaseUser, PermissionsMixin): organization = models.ForeignKey(Organization, on_delete=models.CASCADE, null=True) the error occurs after this ^ import Project models: from django.db import models from authentication.models import User class Organization(models.Model): OWNER = 1 CONTRACTOR = 2 DISTRIBUTOR = 3 MANUFACTURER = 4 CONSULTANT = 5 ORG_TYPES = [ (OWNER, 'Owner'), (CONTRACTOR, 'Contractor'), (DISTRIBUTOR, 'Distributor'), (MANUFACTURER, 'Manufacturer'), (CONSULTANT, 'Consultant'), ] name = models.CharField(max_length=255, default='') created_at = models.DateTimeField(auto_now=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) is_active = models.IntegerField(default=1, null=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True) org_type = models.CharField(max_length=1, choices=ORG_TYPES) class Meta: db_table = 'organizations' class Project(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') created_at = models.DateTimeField(auto_now=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) is_active = models.IntegerField(default=1, null=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True) account = models.ManyToManyField(User, related_name='account') contractor = models.ForeignKey(Organization, related_name="contractor", on_delete=models.CASCADE) distributor = models.ForeignKey(Organization, related_name="distributor", on_delete=models.CASCADE) manufacturer = models.ForeignKey(Organization, related_name="manufacturer", on_delete=models.CASCADE) consultant = models.ForeignKey(Organization, related_name="consultant", on_delete=models.CASCADE) owner = models.ForeignKey(Organization, related_name="owner", on_delete=models.CASCADE) class Meta: db_table = 'projects' -
show_name() missing 1 required positional argument: 'obj'
I am whant to use a function that I have in a different admin, but it gives me an error. this is the function I whant to use: def show_data_user(self, obj): if obj.is_individual(): return self.show_owner(obj) obj = obj.get_real_instance() return mark_safe('<br>'.join( filter( None, [ self.show_name(obj), self.show_second_name(obj), self.show_business(obj), self.show_country(obj), self.show_position(obj), self.show_money(obj), ] ) ) ) and I've puted in another admin like this: def show_employer(self, obj): from employerdata.admin import Titular if obj.titular and isinstance(obj.titular, Employer): return Titular.show_data_user( Titular.show_name(obj), Titular.show_second_name(obj), Titular.show_business(obj), Titular.show_country(obj), Titular.show_position(obj), Titular.show_money(obj) ) How should I fix it? -
Single data from the relation m2m field - Django
In my signal (post_save), I would like to send a single email to a single person who has been assigned using the m2m relationship. One-to-many, the message goes to the user, but m2m nothing happens. specials = models.ManyToManyField(User, related_name='special_users') I've tried everything, searched the topics, but still nothing happens. I have included the pseudocode to illustrate the situation. all_users_from_m2m = instance.specials.all() for single_user in all_users_from_m2m: message = ('Subject', 'Here is message', 'from@example.com', [single_user.email]) send_mass_mail(message, fail_silently=False) -
Jupyter Notebook crashes every time there is an error
I am using the Django Shell Plus notebook on mac. Every time there is an execution error, the Jupyter Notebook crashes without showing the error on the notebook, but showing it on the Shell Plus prompt. It forces me to restart the notebook and execute all the cells each time.