Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I render snippets that represent ui components in pages on Wagtail CMS?
I am new to wagtail and i'm working on a project to build a cms. The cms will have some ui components like NavBars and cards that i am making throught snippets, so that i can reuse them in diferent pages (or even on the same page). My question is what's the best aproach to render this items? I thought of using templatetags, but i am not complete sure if thats a good idea. What do you think its a nice and clean way of doing this? -
In add to cart Span is not working properly
I Created a add to cart function for my website but in the website span is not working properly . My problem is that: You can see in the marked portion of the image if i clicked on add to cart button it is changing "0-1" but when I am clicking on add to cart button of an another product it is not changing from "1-2" So, In product-detail.html: <button class="action-btn"> <ion-icon name="bag-handle-outline"></ion-icon> <span class="count cart-items-count">{{request.session.cart_data_obj|length}}</span> </button> In js file: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(response){ this_val.html("Item added to cart") console.log("Added products to cart"); $(".cart-items-count").text(response.totalcartitems) } }) }) In Views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], } if 'cart_data_obj' is request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data else: request.session['cart_data_obj']=cart_product return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': len(request.session['cart_data_obj'])}) So please help me out with this problem and I think that the probelm is in views because js file is working properly... In … -
Insert only to specific fields in formModel in django
I have a django model and its corresponding form to insert into and read value from a table with three columns in database. My requirement is I only need to insert in to say two column using form, leaving the third column which is a date field. But I have a requirement to read all three column to display it in html in later time. When I use exclude in the form it works good for the html part but when trying to save the form using form.save(), it tries to insert null in the the third column and raise error. Can anybody please help me to omit the third column completely while saving the form. Class sales(models.Model) product_name = models.CharField(max_length=500) quantity=models.FloatField() sale_date=models.DateField() -
django.core.exceptions.SynchronousOnlyOperation You cannot call this from an async context - use a thread or sync_to_async
I am using Django channels to implemented web sockets I wants to get database quries using ORM inside consumers.py look at my code import json from channels.generic.websocket import AsyncWebsocketConsumer from .models import Game from accounts.models import CustomUser as User from channels.db import database_sync_to_async `class CameraStreamConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): print("initializing") self.counter = 0 super().__init__(*args, **kwargs) async def connect(self): await self.accept() print("accepted connection") async def disconnect(self, close_code): pass print("disconect connection") async def receive(self, text_data=None,): print(" iam getting data online") data = json.loads(text_data) if data.get('type') == 'started': await self.handle_game_started(data) async def get_game(self, game_id): game_obj = await database_sync_to_async(Game.objects.get)(id=game_id) return game_obj async def get_user(self, user_id): user_obj = await database_sync_to_async(User.objects.get)(id=user_id) return user_obj async def handle_game_started(self, data): game_id = data.get('game_id') user_id = data.get('user_id') game_obj = await self.get_game(game_id) user_obj = await self.get_user(user_id) if game_obj and user_obj: game_creator = game_obj.creator if game_creator == user_obj: print("user is creator") await self.send(text_data=json.dumps({'message': f'Game {game_id} Started'})) ` and i am getting error django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. I try also with from asgiref.sync import sync_to_async but still getting same -
Django - Wants to restrict access to all of them to only logged-in users and I already have 100's of functions, is their anyway to add it directly?
In Python-Django views.py file I have 100's of functions and I want to restrict access to all of them to only logged-in users. I'm aware that I can add "@login_required(login_url='/admin/login/')" above every function and I works well. But as there are lots of function then adding it can be quite cumbersome. So, is there any way to achieve this without manually adding it to each and every function. Helps are highly appreciated. @login_required(login_url='/member/login/') def dashboard(request): id = request.user.id result = User.objects.get(pk=id) context={'result' : result} return render(request, 'member/dashboard.html', context) I want to restrict access to all of them to only logged-in users. -
I have a problem with static files in django
I cant refrence to contexts in js HTML {% load static%} {%block content%} <div id="backSign" , style="display: none;">go to lesions</div> <ol id="list"></ol> {% endblock content%} {% block extrajs %} <script src="{% static 'assets/js/idioms.js'%}"></script> {% endblock extrajs %} JS const Data = '{{ data|escapejs }}' console.log(Data) output : "{{ data|escapejs }}" when i put js in script tag it works but when i refrence the place its return this : {{ data|escapejs }} -
How to add m2m field, while iterating for copy objs
for a in Company.objects.all(): a.uuid=None a.save() a.users.add(*User.objects.all()) The goal of the code is duplicate Company and add all Users to it. It doesn't work, i need to save it first and iterate again to add the users. How can i add while iterating this object? I needed to save it first and iterate again to add the users. How can i add while iterating this object and duplicating it? -
Strategy to make django models with lots of memberfunctions more manageable?
I have a huge model because of its many member functions. I would like to organize the functions into separate classes according to their purpose, so everything is a bit more organized. Using OneToOneField is not a good option for me, because my app heavily relies on query caching (with cacheops). And I noticed that getting the latest version of a data object (from db) may be attached to a an outdated OneToOneField (from cache). Also, the number of data members is not a problem, only the number of member functions. So I would prefer to use just one data model. For example, I could do it this way: # models.py class MyModel(models.Model): # members # separate member functions class CustomModelFunctions: @staticmethod def some_function(my_model_instance): # logic # call the function on the my_model obj # instead of calling my_model.some_function() CustomModelFunctions.some_function(my_model) This works, but the problem is that these functions can not be used in django templates, since the my_model argument can not be passed. For example, I don't see how I could replace the following template code: {% if my_model.some_function %} Does anyone know a workaround for this? Or a different approach to organize models with a lot of member … -
How to make Django custom user restrict middleware?
urls.py path('panel/', include('panel.urls')), path('', include('base.urls')), non superadmin user restrict to access panel.urls superadmin user allowed panel.urls middllware.py # panel/middleware.py from django.shortcuts import redirect from django.urls import reverse class AdminRestrictMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path.startswith('/panel/'): if request.user.is_authenticated: if not request.user.is_superuser: # If the user is not an admin, redirect them to a restricted page return redirect(reverse('restricted_access')) else: # If the user is not logged in, redirect them to the login page return redirect(reverse('login')) response = self.get_response(request) return response -
Django data getting saved in wrong model Why its saving the Model B,C data in model A
I have 3 django models CustomerDetail CarrierForm InfluencerModel When i am trying to save data in CarrierForm or InfluencerModel through different different page's forms its getting saved in model CustomerDetail Why its happening tell me what i am doing wrong? Here is Model class CustomerDetail(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) contact_number = models.CharField(max_length=10, null=False, blank=False) message = models.TextField(null=False, blank=False) visited_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class CarrierForm(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) contact_number = models.CharField(max_length=10, null=False, blank=False) upload_resume = models.FileField(null=False, blank=False) message = models.TextField(null=True, blank=True) visited_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class InfluencerModel(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) contact_number = models.CharField(max_length=10, null=False, blank=False) instagram_id = models.CharField(max_length=50, null=False, blank=False) message = models.TextField(null=True, blank=True) visited_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email Here is Views class HomeView(CreateView): success_url = reverse_lazy('home') model = CustomerDetail template_name = 'home/home.html' fields = ['full_name', 'email', 'contact_number', 'message'] def get_context_data(self, *args, **kwargs): context = super(HomeView, self).get_context_data(*args, **kwargs) context['files'] = HomeVideoAndImage.objects.all() context['galleryImages'] = HomeGallery.objects.all() context['reviewImages'] = Review.objects.all() return context class CarrierFormView(CreateView): model = CarrierForm template_name = 'home/carrier.html' fields = ['full_name', 'email', 'contact_number', 'upload_resume', 'message'] def get_context_data(self, *args, **kwargs): context = super(CarrierFormView, self).get_context_data(*args, **kwargs) … -
django two factor OTP in DRF
I want to protect one route in a project on DRF, but there are features, an example of implementation that I have not found on the Internet. The structure of logic is like this bellow Implement Two-Factor Authentication (2FA): Integrate a third-party service like Google Authenticator for generating verification codes. When a user tries to access the sensitive route, prompt them to enter a verification code along with their credentials. Verify the entered code with the code generated by the Google Authenticator or similar service. Email Verification: Maintain a list of email addresses that are allowed to access the sensitive route. Compare the email address of the authenticated user (request.user.email) with the list of allowed email addresses. If the user's email is in the allowed list, send a verification code to their email address. Prompt the user to enter the verification code received via email. Verify the entered code against the code sent to the user's email. Granting Access: If the user successfully completes both steps of authentication (2FA and email verification), grant them access to the sensitive route. Otherwise, deny access to the route. If anyone has encountered a similar implementation, please give me some direction -
connection failed: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?
i am getting an error connecting to sql cloud during deployment to google cloud, in my sql cloud, IP public is 34.66.xx.xxx enter image description here but when I run code ./cloud-sql-proxy <connection_name> then feedback: 2024/03/05 22:53:02 Authorizing with Application Default Credentials 2024/03/05 22:53:03 [django-ecommerce-416314:us-central1:django-ecommerce-instance] Listening on 127.0.0.1:5432 2024/03/05 22:53:03 The proxy has started successfully and is ready for new connections! in my setting code django setting, I config database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'shopeedb', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '34.66.xx.xxx', 'PORT': '5432', } } more detail: I can run server on UI server but when LOGIN, REGISTER,... related with DB it not active. What need I do now? Thanks! I tried change config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'shopeedb', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '5432', } } results returned: enter image description here but when I run with config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'shopeedb', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '34.66.xx.xxx', 'PORT': '5432', } } results returned: 502 bad gate way Nginx -
Mypy with Django: type[MyModel] has no attribute "objects" [attr-defined]
After coding my Django model and adding a method which uses the "objects" manager, Mypy continues to show the error (command: "mypy ."): models.py:168: error: "type[MyModel]" has no attribute "objects" [attr-defined] How to solve that? -
Backend vs Frontend approach for upload of large files to remote storage
I am creating a software involving content delivery. It involves upload of large video files(100GB+). I understand that in general for file upload you can use the input element of html and upload it to the backend and from there you upload it to your storage. But this involves 2 uploads for 1 file and involves loading your large file into in-memory database in your backend. Im wondering if one could save some bandwidth and time, space and computation by somehow directly uploading from the frontend. What is the industry standard for dealing such a scenario? I've seen ways to upload large files from backend using multipart uploads using AWS sdk, but so far, I couldn't find a way to directly upload using HTML + JavaScript from the frontend itself(without loading the file into the in-memory database). I am using Django for backend, Angular for frontend and AWS s3 for storage. -
How to resolve a "DuplicateColumn" error when running Django migrations?
I'm encountering an issue while running migrations in my Django project. Here's the error message I'm receiving: psycopg2.errors.DuplicateColumn: column "order_address" of relation "orders_order" already exists This error seems to be related to the migrations process. I have checked my migration files and ensured that I'm not explicitly adding the "order_address" column multiple times. However, the error persists. What could be causing this error, and how can I resolve it? -
Not printing required data from json available data
[This is the source code. Here I iterate through a bunch of json entries and try to print only a few.] (https://i.stack.imgur.com/KUlfj.png) the last few empty columns are where I tried to print some specific data. It isn't printing it at all. The entries are supposed to be printed on a html page. I had tried to iterate through 'output' which had 2 json entries. I wish to print only a few specific values from each json entry but when i specified and ran the django webapp, it didn't print anything. -
csrf token is showing as text in the browser
enter image description herei am very new to django. i am trying to create a login form in django but when i write the csrf_token line after the tag it is showing in the browser view. everything is very confusing for me i don't know what to do. the tutorial that i watch on youtube only pass the csrf_token but don't say anything much. {% csrf_token %} Email Password Sign In Change Password this is a very simple form that i styled using tailwindcss and the csrf token is being shown. also my app has other errors. it does not run on the development server -
Error creating a closure table in Django: 'ForeignKey' object has no attribute 'column'
I have a Jobs model and need a closure table job_hierarchies schema looks like below Table job_hierarchies { account_id int [not null] ancestor int [not null, ref: > jobs.id] descendant int [not null, ref: > jobs.id] level int [not null] } I tried creating model & migration for JobHierarchy as below Model # api/models/job_hierarchy.py from django.db import models from .base import BaseModel from api.models import Job class JobHierarchy(BaseModel): account_id = models.IntegerField(null=False) ancestor = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='ancestor_jobs', db_column='ancestor_id') descendant = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='descendant_jobs', db_column='descendant_id') level = models.IntegerField(null=False) class Meta: db_table = 'job_hierarchies' Migration looks like below # Generated by Django 5.0.2 on 2024-03-08 04:28 from django.db import migrations, models def add_foreign_keys(apps, schema_editor): JobHierarchy = apps.get_model('api', 'JobHierarchy') Job = apps.get_model('api', 'Job') schema_editor.add_field( JobHierarchy, models.ForeignKey(Job, on_delete=models.CASCADE, related_name='ancestor_jobs', db_column='ancestor_id'), ) schema_editor.add_field( JobHierarchy, models.ForeignKey(Job, on_delete=models.CASCADE, related_name='descendant_jobs', db_column='descendant_id'), ) class Migration(migrations.Migration): dependencies = [ ('api', '0002_create_jobs'), ] operations = [ migrations.CreateModel( name='JobHierarchy', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('account_id', models.IntegerField()), ('level', models.IntegerField()), ], options={ 'db_table': 'job_hierarchies', }, ), migrations.RunPython(add_foreign_keys), ] When I run make migrations, I get below error File "/app/api/migrations/0009_create_job_hierarchies.py", line 8, in add_foreign_keys schema_editor.add_field( File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/schema.py", line 730, in add_field "name": self._fk_constraint_name(model, field, constraint_suffix), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/schema.py", line 1708, in _fk_constraint_name [field.column], ^^^^^^^^^^^^ AttributeError: … -
stripe transfer method in django
i am working on project where i want to transfer amount to multiple stripe customers i have used the stripe transfer method but i am getting the following error Error: Request req_FlLAHrjOxkd4IO: You have insufficient available funds in your Stripe account. Try adding funds directly to your available balance by creating Charges using the 4000000000000077 test card. See: https://stripe.com/docs/testing#available-balance here is my code charge = stripe.Charge.create( amount=5000, currency="usd", source='tok_visa', description="Adding funds to test account" ) charge_id = charge.id # Assuming you have defined 'total_charges', 'user.id', 'seller_amount', and 'referral_amount' earlier in your code session = stripe.PaymentIntent.create( amount=total_charges, currency="usd", transfer_group=f"ORDER10_{user.id}", ) stripe.Transfer.create( amount=seller_amount, currency='usd', destination='acct_1OrzGLI3hFSHp0X5', transfer_group=f"ORDER10_{user.id}", ) stripe.Transfer.create( amount=referral_amount, currency='usd', destination="acct_1OrzPRI5g3KKKWKv", transfer_group=f"ORDER10_{user.id}", ) -
Django not sending rendered array to Angular
I'm trying to build an API with Django that recieves an image, applies a filter and returns the image with the filter to the frontEnd, that it's made with Angular. But when I call the API my model does recieve the image but doesn't apply the filter and doesn't return the modified image. And it whe using the method POST doesn't return anything, not even an error This is my models.py: def apply_filter(noisy_image, kernel): smoothed_image = np.zeros_like(noisy_image) for channel in range(noisy_image.shape[2]): for row in range(noisy_image.shape[0] - kernel.shape[0] + 1): for col in range(noisy_image.shape[1] - kernel.shape[1] + 1): sub_matrix = noisy_image[row:row + kernel.shape[0], col:col + kernel.shape[1], channel] smoothed_image[row + 1, col + 1, channel] = np.sum(sub_matrix * kernel) fig, ax = plt.subplots() ax.imshow(smoothed_image.astype(np.uint8)) ax.axis('off') return fig def default_image(image_array): # Load image fig, ax = plt.subplots() ax.imshow(image_array.astype(np.uint8)) ax.axis('off') # Hide axes return fig def suavizado1(image_array): kernel_size = 12 kernel = np.ones((kernel_size, kernel_size)) / (kernel_size ** 2) noise = np.random.normal(0, 10, size=image_array.shape) noisy_image = image_array + image_array * noise return apply_filter(noisy_image, kernel) This is my views.py: def processImage(request): if request.method == 'POST': uploaded_file = request.FILES['image'] filter_name = request.POST.get('filter') image_path = default_storage.save('uploaded_images/' + uploaded_file.name, ContentFile(uploaded_file.read())) print(image_path) #Load image imagen = Image.open(image_path) image_array = np.array(imagen) … -
Django email html format not
`html = """\ <html> <head></head> <body> <p>Hi Team,<br><br> Reminder:<br> Please check if Domain listed below need to be renewed.<br><br> {0} </p> </body> </html> """ www = get_data_from_db() week_old = 14 d = [] for domain in www: days = compute_days(domain) if int(days) <= int(week_old): d.append("{0} is expiring in {1} days.<br>".format(domain, days)) print(d) html = ('\n'.join(d)) print(html) part2 = MIMEText(html, 'html') msg.attach(part2)` Hi, just started learning python/django not long ago. This project is to add a reminder/notification to the company by sending out email. I came across this problem where I am unable to correctly display the html with value. If I change my code at html = html.format('\n'.join(d)) It will display the html with 1 value where the actual result is 2 value. Missing the another one. If I use code above, it will only display 2 value but missing the html. What am i missing here? -
Null field returning required
I set a referral field on my django model to null but everytime I try to register without passing in a parameter it says that the field is required for registration. I've tried different approaches to try to solve it but still no fix. I want users to be able to register without using a referral code #models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, username, email, password, is_staff, is_superuser, address, **extra_fields): now = timezone.now() if not username: raise ValueError(('The given username must be set')) email = self.normalize_email(email) user = self.model(username=username, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, address=address, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email=None, password=None, **extra_fields): return self._create_user(username, email, password, False, False, True, **extra_fields) def create_superuser(self, username, email, password, **extra_fields): user = self._create_user(username, email, password, True, True, **extra_fields) user.is_active = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=250, blank=True) last_name = models.CharField(max_length=250, blank=True) email = models.EmailField(('email address'), unique=True) username = models.CharField(max_length=50, unique=True, blank=False, default='username') profile_picture = models.ImageField(upload_to='Pictures', blank=True) created_at = models.DateField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) referral_code = models.CharField(max_length=10, unique=True, blank=True, null=True) referred_by = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) referred_users_count = models.IntegerField(default=0) #subscription_start_dates = … -
Django async nested model loading
I have models: class ObjectA(models.Model): alias = models.CharField(max_length=50) objectb = models.ForeignKey(ObjectB, on_delete=models.PROTECT) class Meta: db_table = "objecta" class ObjectB(models.Model): name = models.CharField(max_length=50) objectc = models.ForeignKey(ObjectC, on_delete=models.PROTECT) class Meta: db_table = "objectb" class ObjectC(models.Model): name = models.CharField(max_length=50) class Meta: db_table = "objectc" In my ViewSet function I want to get ObjectA and then get name from referenced ObjectC. In synchonious django I would do get_object_or_404(ObjectA, alias="My alias").objectb.objectc.name But this in async Django throws me an error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. I found a solution which does not look very clean to me: from django.db.models.query import aprefetch_related_objects from django.shortcuts import get_object_or_404 get_objecta_model = sync_to_async(get_object_or_404, thread_sensitive=True) objecta = await get_objecta_model(ObjectA, name=alias) await aprefetch_related_objects([objecta], "objectb__objectc") objecta.objectb.objectc.name -
Pivot table with hierarchical indexes?
Using pandas 2.0.3. I know this may sound simple but i dont know how to make it work. I'm using pandas pivot table to rearrange a table to match a template. Here's the current code I'm using: x = pd.pivot_table(df, index=['locality', 'name', 'type', 'method'], columns='mineral', values='mineral_value', fill_value=0).reset_index() With this code I'm getting this data structure: However, I need to add a hierarchy with the columns mineral and method, so it looks something like this: I've been trying multiple ways but I just haven't been able to get it. I've tried to add x = pd.pivot_table(df, index=['locality', 'name', 'type', 'method'], columns=['mineral', 'method'], values='mineral_value', fill_value=0).reset_index() TypeError: keys must be str, int, float, bool or None, not tuple Any idea? thanks in advance -
Sending a custom error Through the API to appear in flutter
I have a functioning flutter front to register users that consumes a Django-rest-framework API. With 3 fields (Username,Email and Password). I'm trying to add a snack-bar that shows up when the user fills a field incorrectly according to my validations. this is what i tried : if (response.statusCode == 200) { // Request was successful print('Signup successful!'); // You can perform any other actions here, such as navigating to a new screen } else { // Request failed print('Failed to signup. Error: ${response.statusCode}'); final Map<String, dynamic> errors = jsonDecode(response.body); String? key = errors.keys.first; String value = errors[key][0]; print(value); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('$value'), backgroundColor: Colors.red, duration: const Duration(seconds: 2), ), ); } } catch (error) { // Handle any exceptions that occur during the API call print('Error while signing up: $error'); // You can display an error message to the user or perform other error handling actions } } For some reason when the password field or username field are Wrong i get a : Failed to signup. Error: 500 Error while signing up: FormatException: Unexpected character (at character 1). and when the email field is invalid i get the wrong error message (Enter a valid email address) . I'm still …