Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'InnerDoc' object has no attribute 'pk'
I'm encountering an issue with Elasticsearch-dsl when trying to use a custom serializer with Django REST framework. The error message I'm getting is: 'InnerDoc' object has no attribute 'pk' This error originates in the line serializer = self.serializer_class(results, many=True) from the following code snippet in my PaginatedElasticSearchAPIView: class PaginatedElasticSearchAPIView(APIView, LimitOffsetPagination): serializer_class = None document_class = None @abc.abstractmethod def generate_q_expression(self, query): """This method should be overridden and return a Q() expression.""" def get(self, request, query): try: q = self.generate_q_expression(query) search = self.document_class.search().query(q) response = search.execute() print(f'Found {response.hits.total.value} hit(s) for query: "{query}"') results = self.paginate_queryset(response, request, view=self) serializer = self.serializer_class(results, many=True) return self.get_paginated_response(serializer.data) except Exception as e: return HttpResponse(e, status=500) I've checked my serializer, and it seems to have the primary key ("id") defined correctly: class OfficeSerializer(serializers.ModelSerializer): # ... class Meta: model = Office fields = [ "id", # ... ] My Elasticsearch document, defined as OfficeDocument, also appears to have the primary key ("id") defined correctly: @registry.register_document class OfficeDocument(Document): # ... class Django: model = Office fields = [ "id", # ... ] Despite this, I was still encountering the "'InnerDoc' object has no attribute 'pk'" error. Then I recreated all models without explicitly setting ids and removed the ids references … -
Using a Custom Django FilterSet and OrderingFilter at the Same Time Breaks My FilterSet
So I have MyFilterSet and CustomOrderingFilter both working perfectly by themselves but when I try to put both into the view at the same time the FilterSet breaks. I've removed the unnecessary business logic from the functions and just included the parts that matter. I tried to put the OrderingFilter inside the FilterSet (to no avail). (There are no errors generated. I'm using Django 1.14, Python 2.7.17 and PostgreSQL 10.23 and it will be near impossible to change those versions at the moment but if changing is the answer I'd like to know that too.) in filters.py: class MyFilterSet(FilterSet): id = filters.NumberFilter(name='id', lookup_expr='exact') class Meta: model = TheModel fields = list() exclude = [] class CustomOrderingFilter(OrderingFilter): fields_related = { 'vendor': { 'data_type': 'text', 'loc': 'thing__vendor',}, } def get_ordering(self, request, queryset, view): param = request.query_params.get(self.ordering_param) if param: return param return self.get_default_ordering(view) def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering in self.fields_related.keys(): return queryset.order_by(ordering) return queryset in views.py class getMyListAPIView(generics.ListAPIView): serializer_class = MySerializer filter_class = MyFilterSet filter_backends = [CustomOrderingFilter] def get_queryset(self): models = TheModel.objects return models -
How to implement connection requests in a room? [closed]
There is a room that can create any user, and he will automatically become its administrator. There may be people in this room who have entered the room code in a specific field. Now the user connects immediately, but I need that after sending the room code, the administrator sitting in the room receives a connection request (relatively speaking, block with the name of the person connecting and the “accept” and “reject” buttons). If the administrator accepts the connection, the user will be in the room, otherwise not. How to do it? Websockets? If yes, can you provide more details? Or maybe there is another way to implement all this? -
Why cant I add a new page to my Django project?
I am trying to add another page to my Django project. At first the problem was that the tutorial I was using was asking to use url so i switched it to re_path but it is still not working and giving me many errors. Right now my urls.py looks like this: from django.contrib import admin from django.urls import path, re_path, include from myapp import views urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^hello/$', include (views.hello)), ] However I keep getting an error that says "File "C:\Program Files\Python311\Lib\site-packages\django\urls\resolvers.py", line 725, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<function hello at 0x000001C657C0F2E0>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import." Amonge other errors for files I have not edited yet. -
Tuples in Django models
I want to write the whole word on the website when entering the product information by entering the first letter of the status field. But here it receives the information correctly, but only displays the first letter on the web page. class Product(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.TextField() category = models.CharField(max_length=64) first_bid = models.IntegerField() image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) status = models.CharField(max_length=1, choices= choice) active_bool = models.BooleanField(default = True) def __str__(self): return self.get_status_display() This is one of the ways to display this field. <a><a>Status: </a>{{ product.status }}</a><br> -
Connect SQL Server in Django Socker
Outside of Docker, my app works well, and I can connect to two SQL Server databases, on two diferent servers. Inside Docker, I can't connect to the second DB. I ger a timeout error. Can someone help me? settings.py DATABASES = { 'default': { 'ENGINE' : config('DB_ENGINE'), 'NAME' : config('DB_DEFAULT_NAME'), 'USER' : config('DB_DEFAULT_USERNAME'), 'PASSWORD': config('DB_DEFAULT_PASS'), 'HOST' : config('DB_HOST_DEFAULT'), 'PORT' : '', 'OPTIONS': { 'driver': config('DATABASE_DRIVER'), }, }, 'otherbd': { 'ENGINE' : 'mssql', 'NAME' : 'serverbd', 'USER' : 'user', 'PASSWORD': 'pw', 'HOST' : '192.168.1.165', 'PORT' : '63649', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } views.py def ordens_e_ensaques(request): try: second_db = connections['otherbd'] cursor = second_db.cursor() # Consulta para obter as ordens cursor.execute("SELECT * FROM Ordens WHERE ORD_Estado = '1'") print('Consulta SQL de Ordens executada com sucesso!') resultados_ordens = cursor.fetchall() # Consulta para obter os ensaques cursor.execute("SELECT * FROM OrdensEnsaqueActivas") print('Consulta SQL de Ensaques executada com sucesso!') resultados_ensaques = cursor.fetchall() context = { 'resultados_ordens': resultados_ordens, 'resultados_ensaques': resultados_ensaques } return render(request, 'pages/producoes.html', context) except Exception as e: print("Erro ao conectar ao banco de dados: ", e) return HttpResponse("Erro ao conectar ao banco de dados: " + str(e)) -
Implementation of binary tree in django
i am planing to implement binary tree for recommendation where a user can enroll any number of user but i want to keep all the user in binary tree A / \ B c / \ / \ D E F G how can i store this data in database i have tried creating model class Tremodel(models.Model): refered_by = foreign key user left = foreign key user right = foreign key user how can i query 15 level from there where A is the root but for the B/C tree start from it and B/C is the root where tree can go up to any level i just need to calculate up to 15 level in its branch i tried creating the model i have shown above but i am totally confused how to query it` -
Fast Refresh not happening using React js and Django
Im very new to react js and Django and i want to experiment how the screen changes whenever i save the codes. But currently whenever i do the changes, i need to press the refresh button on the browser manually to check the changes. After a lot of research i found the way to automatically do that is via Fast Refresh. I have tried a lot of things for it to work using the links below but none have worked so far. https://dev.to/thestl/react-fast-refresh-in-django-react-kn7 Development server of create-react-app does not auto refresh I am using webpack 5.88.2, babel/core 7.22.20,react 18.2.0 Please let me know how i can do this. Thanks -
How can I integrate djangocms-link in Ckeditor
I would like to use the functionality of the djangocms-link Plugin within the Ckeditor suche that I can add any and numerous links to my text. So far I have only found this feature. But this does not provide the flexibility I need (to add multiple links in various positions. Thanks a lot -
Customizing Permissions and Groups models in Django
I want to modify the Permissions and Group models from django.contrib.auth. I have extended them but am unable to understand how to use these extended models in my project. I had researched about it again and again but could not find the solution. Can any one help me? I had to add two extra fields in Permission model and 4 additional fields in Group model. I had extended both models but when I replace the permissions attribute of Group class it gives error that local fields cannot replace existing. Further, I cannot use add/contribute to original class methods as it is dangerous to replace original files and is not a good programming practice too. Is there any way to change permissions in Group model. Secondly, how can I use these new models in User model? -
How to differentiate created objects and updated objects in Django bulk_create?
I am using bulk_create to create objects in one query. I set update_conflicts to True to update permission level if the record already exists. bulk_create returns the created and updated objects. How can I separate the created object and updated ones? class UserPermission(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='permissions') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='permissions') permission_level = models.SmallIntegerField(default=1) class Meta: unique_together = ('project', 'user') permissions = UserPermission.objects.bulk_create( user_permissions, update_conflicts=True, update_fields=['permission_level'], unique_fields=['project', 'user'], ) -
Receiving Sendgrid Inbound Email webhook attachments as strings (not files)
I'm receiving multiple inbound email webhook requests from Sendgrid (a Django/DRF application on my side) with attachments that are strings rather than actual files. This results in an error when trying to save the files (because 'str' object has no attribute 'file' when trying to file.read()). It apparently happens to approx. 5-10% of all inbound emails and seems to only happen with image files (JPGs, GIFs etc), I did not encounter a PDF file passed this way. Before saving the files I iterate over attachments-info keys to get a list of attachments, here's an example result [ '����\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00��\x10�Exif\x00\x00MM\x00*\x00\x00\x00\x08\x00\x04\x01;\x00\x02\x00\x00\x00\r\x00\x00\x08J�i\x00\x04\x00\x00\x00\x01\x00\x00\x08X��\x00\x01\x00\x00\x00\x1a\x00\x00\x10��\x1c\x00\x07\x00\x00\x08\x0c\x00\x00\x00>\x00\x00\x00\x00\x1c�\x00\x00\x00\x08\x00..., <InMemoryUploadedFile: 40896630.pdf (application/octet-stream)> ] What exactly is this string? Why does that happen? How can I decode it (assuming all I have is the original file name and content type) -
"cannot cast type bigint to uuid" while changing db from sqLite3 to PostgressSql
So here is my Pet model and PetAttachmentImage model as well, in case if it can give any extra info. The problem is that I created my whole backend on Django using default engine (sqlite3) and now I need to deploy it on a cloud, in my case its neonDb - which uses postgres as engine. When I'm trying to migrate my data from sqlite3 on my local storage to postgress on neonDb I get this error - psycopg2.errors.CannotCoerce: cannot cast type bigint to uuid So I've done my research and found similar problem even here on StackOverflow,however it's solution doesn't work in my case, and I don't understand why. Also I use uuid as my primary key, I created id only to make it explicit about the fact that I don't want to use it, and to alter it with my custom one if it's somehow still exists by default. class Pet(models.Model): id = models.BigIntegerField(blank=True, null=True) uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, blank=False, null=False) name = models.CharField(max_length=150, default="Unnamed") animal = models.CharField(max_length=150, default="") breed = models.CharField(max_length=150, default="") location = models.CharField(max_length=150, blank=True, null=True) image = models.ImageField(upload_to='images/', default='images/pet.png', blank=True, null=True) description = models.TextField(max_length=1000, blank=True, null=True) info = models.TextField(max_length=1000, blank=True, null=True) def __str__(self): return f"{self.animal} … -
Bootstrap elements cause a reduction in width, which is not a proper behavior
As title says some bootstrap elements changes my whole website width, reducing it by 15px. I think that responsive elements cause this weird behavior. Code: <div class="px-4 py-5 my-5 text-center"> <img class="d-block mx-auto mb-4" src="{%static 'images/tinytools_logo.png'%}" alt="" width="100" height="100"> <h1 class="display-5 fw-bold text-body-emphasis">Tiny Tools - AI powered platform</h1> <div class="col-lg-6 mx-auto"> <p class="lead mb-4">Have you ever dreamt of a website that can instantly answer your questions or help you solve a test? Our advanced platform, powered by the mighty GPT-4, is here to assist you.</p> <div class="d-grid gap-2 d-sm-flex justify-content-sm-center"> </div> </div> </div> <div class="container col-xxl-8 px-4"> <div class="row flex-lg-row-reverse align-items-center g-5 "> <div class="col-10 col-sm-8 col-lg-6"> <img src="{% static 'images/ask_gpt_logo.jpeg'%}" class="d-block mx-lg-auto img-fluid rounded-circle" alt="Bootstrap Themes" width="500" height="500" loading="lazy"> </div> <div class="col-lg-6"> <h1 class="display-5 fw-bold text-body-emphasis lh-1 mb-3">Ask GPT - AI chatbot</h1> <p class="lead">AI chatbot powered by GPT-4 analyzes your question and provides precise answers based on the latest knowledge.</p> <div class="d-grid gap-2 d-md-flex justify-content-md-start"> <button type="button" class="btn btn-warning btn-lg px-4 me-md-2">Tool</button> </div> </div> </div> </div> <div class="container col-xxl-8 px-4 py-5"> <div class="row flex-lg-row-reverse align-items-center g-5"> <div class="col-10 col-sm-8 col-lg-6 order-lg-2"> <img src="{% static 'images/lensgpt_logo.jpg'%}" class="d-block mx-lg-auto img-fluid rounded-circle" alt="Bootstrap Themes" width="500" height="500" loading="lazy"> </div> <div class="col-lg-6 order-lg-1"> <h1 … -
I need to upload to profile pic
using base64 encoded and saved in database b'iVBORw0KGgoAAAANSUhEUgAABZ0AAALkCAYAAABkw5u0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAP+lSURBVHhe7N0JYBTl2Qfwf07CnXCHS4IIBEFJxCpRPIKohGIlFA9SbSteSMADRKv0a1W8ECoKAa2iVgselGClgIoEDwRRJChIuCSIHOFMgIRcm+z3PrMzyexkd7NJNskm/H84bvad2ZnZmXfemX323WcCvv/+ezvIr9jtjl0ijzabDUVFRejQoQPat2+PsLAwBAUFaeOJiOqLtE35+fnYv38/8vLyEBISorVNAQEBWtsljzIQEdUn45qK7VHDZuxHM1dlZubxlU1bHbUxTyLyrDbacvM8K5u/q/E8vxARucegs58xLmDlUYI6BQUF6N27N9q0aaOVExH5mz179uD48eMIDQ0tCzwLXoQTEZGveAryVhYA9scAsT+uE1F9qc... I need to upload profile pic I need to display image in circle in circle i need to get image from data base when user is login -
Live dashboard: django, dash or else?
I'm new to this kind of development, so I write hoping to have a feedback. I need to build a dashboard displaying several parameters (# ~100) taken from an OPC UA server. I also need to implement some logic based on the values to show if the parameters are within safety limits or not. I already used plotly + dash in the past, thus I decided to start using dash to build my dashboard together with a python script responsible to subscribe to the opcua datapoints I need to follow and constantly update a file with them. This file with all the values is then feeding the dash app which is set to update throughIntervals every sec. This gives me a live updating dashboard. Now I was wondering if there is a better way to design this. The dashboard has a general main page where some of the most important parameters are displayed. However there are also different tabs per subsystem/topic where the user can switch to and see all the available parameters of that subsystem at once. Here the problem I encountered is that in dash I can not share information within the Tabs. Thus if a datapoint is … -
I want to see or download the file in django admin uploaded by user from frontend site
I created the form like contact form to upload file and other details. urls.py from django.contrib import admin from django.urls import path from eSangrah import views urlpatterns = [ path("xerox", views.xerox, name='xerox'), views.py from django.shortcuts import render, redirect from .models import Xerox from datetime import datetime def xerox(request): if request.method=='POST': name=request.POST['name'] phone=request.POST['phone'] desc=request.POST.get('desc') file=request.POST['file'] xeroxs = Xerox.objects.create(name=name, phone=phone, desc=desc, file=file, date=datetime.now()) xeroxs.save() return redirect("/xerox") return render(request, 'xerox.html') models.py from django.db import models class Xerox(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=13) desc = models.TextField() file = models.FileField() date = models.DateTimeField() def __str__(self): return self.name admin.py from django.contrib import admin from .models import Xerox admin.site.register(Xerox) enter image description here If I click on the uploaded file . I get below error... enter image description here -
How to create a draggable icon on a web page with JavaScript or a third-party library
I would like to create a website where I can create a round icon by clicking an add button. I can then drag and drop the icon onto an image. When I release the mouse, the icon's position on the image should be saved. Later, on another page, the icon should be displayed on the same position. For the backend I use Django. I have not been able to find a way to implement this and would like to ask for your ideas. -
How to prevent double encryption in Django with Vercel
I am hosting a django website on Vercel and, both, vercel and Django are encrypting the url. So, the " " character in the url gets encrypted to "%20" and then django again encrypts it to "%2520", but when decrypting, it decrypts only once. In my code, I am appending a name which allows " " to be used and that name gets appended to url which later gets used by a function in views.py as pk(not primary key but just a way to get data from the database). The problem is clearly seen in the image, url has replaced " " with %20 but django se getting "%2520". So, the problem was just with the " " character, so I removed space character from the name, which solves the problem, but I don't want that to be the solution. -
Cannot query "zs": Must be "Product" instance
I want the seller to be able to choose one of the offers for sale and then close the sale by clicking on the close button. This code doesn't do anything if I put a separate for loop in the html file, but if it's the way I sent it, it displays the button to close the sale, but after clicking the button, it gives this error. and, I feel that this graphic is not very user-friendly. What is your suggestion for a better design and to reduce the number of buttons to close the auction? Error: Exception Type: ValueError at /seller_page/ Exception Value: Cannot query "zs": Must be "Product" instance. views.py: def seller_page(request): seller_offers = PriceOffer.objects.filter(product=request.user) if request.method == 'POST': offer_id = request.POST.get('offer_id') offer = get_object_or_404(PriceOffer, pk=offer_id) offer.is_closed = True offer.save() return render(request, 'auctions/product_detail.html', {'seller_offers': seller_offers}) def close_offer(request): if request.method == 'POST': offer_id = request.POST.get('offer_id') offer = get_object_or_404(PriceOffer, pk=offer_id) offer.is_closed = True offer.save() return redirect('seller_page') product_detail.html : <ul> {% for offer in offers %} <li><a> {{ offer.author }}:{{ offer.offer_price }}</a></li> <form method="post" action="{% url 'close_offer' %}"> {% csrf_token %} <input type="hidden" name="offer_id" value="{{ offer.id }}"> <button type="submit">Close Offer</button> </form> {% endfor %} </ul> <form method="POST" action="{%url 'product_detail' product.id %}"> … -
django.db.utils.ProgrammingError: relation "authentication_cityhaldata" does not exist LINE 1: ...hentication_cityhaldata"
I'm trying to perform migrations on my production server. I installed all packages and dependencies. However, I receive the message: django.db.utils.ProgrammingError: relation "authentication_cityhaldata" does not exist LINE 1: ...hentication_cityhaldata"."url_for_interview" FROM "authentic... I tried deleting all files from the migrations folder of the application and project, but it didn't help. I then tried to create a migration only for the authenticator app by 'python manage.py makemigrations authentication' it didn't work properly. What can I do to make the system allow me to create a makemigrations on the server? My modes: from django.db import models from django.contrib.auth.models import AbstractUser from imagekit.models import ProcessedImageField, ImageSpecField from imagekit.processors import ResizeToFill from decimal import Decimal from django.utils.text import slugify from dashboard.choices import PROVINCES_CHOICES class CustomUser(AbstractUser): ACCOUNT_TYPE_CHOICES = [ ('Konto firmowe', 'Konto firmowe'), ('Konto indywidualne', 'Konto indywidualne'), ] name = models.CharField(max_length=200, blank=True, null=True) [..more fields here..] def __str__(self): return self.email class Meta: ordering = ['email', ] class RecommendationsSystem(models.Model): owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='owner', verbose_name='Osoba pierwsza') [..more fields here..] class SocialMediaUrl(models.Model): PERCENT_RANGE = [ (0.05, '5 procent'), # (0.10, '10 procent'), # (0.15, '15 procent'), # (0.20, '20 procent'), # (0.25, '25 procent'), # (0.30, '30 procent'), # (0.35, '35 procent'), # (0.40, '40 procent'), # (0.45, … -
How to update availability set by user?
I have a model with two users Student and Consultant. Consultant is able to set up his availability like this: from django.db import models from userregistration.models import UserProfile class Setup_Availability(models.Model): consultant = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='consultant_availability') start_date = models.DateField() # The date when availability starts monday_start_time = models.TimeField(null=True, blank=True) monday_end_time = models.TimeField(null=True, blank=True) tuesday_start_time = models.TimeField(null=True, blank=True) tuesday_end_time = models.TimeField(null=True, blank=True) wednesday_start_time = models.TimeField(null=True, blank=True) wednesday_end_time = models.TimeField(null=True, blank=True) thursday_start_time = models.TimeField(null=True, blank=True) thursday_end_time = models.TimeField(null=True, blank=True) friday_start_time = models.TimeField(null=True, blank=True) friday_end_time = models.TimeField(null=True, blank=True) saturday_start_time = models.TimeField(null=True, blank=True) saturday_end_time = models.TimeField(null=True, blank=True) sunday_start_time = models.TimeField(null=True, blank=True) sunday_end_time = models.TimeField(null=True, blank=True) def __str__(self): return f"Availability for {self.consultant.user.username} starting on {self.start_date}" And Student will be able to book appointment through: class Appointment(models.Model): student = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='student_appointments') consultant = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='consultant_appointments') appointment_datetime = models.DateTimeField() appointment_start_time = models.TimeField() appointment_end_time = models.TimeField() is_available = models.BooleanField(default=True) def __str__(self): return f"{self.student.user.username} - {self.consultant.user.username} - {self.appointment_datetime}" def book_appointment(request): day_of_week_name = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] if request.method == 'POST': form = AppointmentBookingForm(request.POST) if form.is_valid(): consultant = form.cleaned_data['consultant'] date = form.cleaned_data['date'] appointment_start_time = form.cleaned_data['appointment_start_time'] appointment_end_time = form.cleaned_data['appointment_end_time'] # Check if the selected time slot is available availability = Setup_Availability.objects.get(consultant=consultant) day_of_week = date.weekday() available_start_time = getattr(availability, … -
How to get last modified date with each image present in different folders in AWS S3 bucket
I have created a bucket on aws s3 storage and saving folders dynamically by the user in that bucket. The code is working perfectly and getting each folder images. But I am not able to get last modified date of each image present in different folders. I want to get last modified date of each image present in different folders. #views.py code: def home(request): data = {} storage = S3Boto3Storage() s3 = boto3.client('s3') image_info_list = {} for obj in s3.list_objects(Bucket=storage.bucket_name)['Contents']: # Getting the folder name from the object key. folder_name = obj['Key'].split('/', 1)[0] if folder_name not in image_info_list: image_info_list[folder_name] = [] # Adding the image url to the folder's image list. image_info_list[folder_name].append(storage.url(obj['Key'])) # Check if a Camera instance with the same name already exists camera, created = Camera.objects.get_or_create(name=folder_name) data = { 'image_info_list': image_info_list, 'cameras': cameras, } return render(request, 'index.html', data) -
How to use Django test without Django models?
I have a Django app for REST api, but not using Django REST Framework. I don't use models for any tables, only using Raw SQL query. Could've used flask since not using any Django features, but higher ups decided to use Django. I want to use Django test but digging in the source code I can see both dumpdata and loaddata which test uses to create Test DB uses app's model. But since I don't have any models how do I test my Django app? It is OK to use the actual development DB for testing. I see django overrides the DEFAULT_DB_ALIAS connection param with the newly created test db params, should I just override the param with the actual default db connection param instead? So can I use django test without models and migrations? can I use default database for testing and prevent django from creating a test db? -
Angular 16 catch errors response from Django
i learning Angular and i have a standard login service in Angular 16.2.0 and backend with Django. I post login details all working fine but when i catch errors i get only get only generic errors, Django is sending personalized messages for errors and i try to catch those to be able to show them in frontend. This is my login service function: login(username: string, password: string): Observable<any> { return this.http.post(apiRoot + 'dj-rest-auth/login/', { username, password, }, ).pipe(catchError((error: HttpErrorResponse) => { let errorMsg = ''; if (error instanceof ErrorEvent) { errorMsg = `Error: ${error}`; } else { errorMsg = `Error Code: ${error}, Message: ${error.message}`; console.log(error.message) } return throwError(() => new Error(errorMsg)); })); } Now in case of an error this is all i got: Http failure response for https://link.stars-nexus.com/dj-rest-auth/login/: 400 OK . In network i have: Network Headers Django is sending personalized error messages in response: Response Image That messages i try to catch them to be able to show them letter in front end. Django is taking care of all validations and provide proper personalized per error feedback. There is any way to catch them? Thank Kind regards. To be able to catch those messages from error response to …