Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use swagger_auto_schema in a class based view with no serializer_class and how to add custom authentication permission to it?
I have a class based view as: class ClassBasedView(GenericAPIView): @swagger_auto_schema(responses={201: 'Created'}) @authorize(myCustomPermission) def post(self, *args, **kwargs) -> Response: // code..... return Response(status=HTTPStatus.CREATED) First: The use of swagger_auto_schema without any serializer is throwing error as: AssertionError: DetailView should either include a serializer_class attribute, or override the get_serializer_class() method. And I don't want to use serializer for this endpoint as I don't need that. But the swagger_auto_schema keeps on throwing this error. I want to know whether there is any way to avoid the use of serializer and get the swagger documentation of this endpoint. Second: I want to add my custom authorisation permission of this endpoint in the doc. There is a security field in swagger_auto_schema, but don't know how to make it to use for my custom permission class ie myCustomPermission Thanks. -
Variable inside a function in views is not accessible outside in Django
I have created a function that would get query parameters from the request URL and I need the query parameters that I got inside the function accessible outside so that I can concadenate it with the APIcall URL **views.py** def getformdata(request): if request.method=="GET": baseurl = request.build_absolute_uri() queryparams=urlparse(baseurl).query print("requesturl",baseurl) print("urlparams",queryparams) return JsonResponse({"message":"Request handled","queryparams":queryparams}) print("urlparams",queryparameter) -
django custom abstractuser model authorization
I've user custom model and subModel Teacher and Student I want them to login in the same form: models.py: class User(AbstractUser): course = models.ManyToManyField(Course, related_name='student_course') is_student = models.BooleanField('Студент',default=False) is_teacher = models.BooleanField('Учитель',default=False) image = models.ImageField(verbose_name='Фото',upload_to='uploads/accounts/',blank=True) class Student(User): class Meta: verbose_name = 'Студент' verbose_name_plural = 'Студенты' def __str__(self): return super(Student, self).__str__() class Teacher(User): class Meta: verbose_name = 'Учитель' verbose_name_plural = 'Учителя' views.py: def user_login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect(home) else: return render(request,'login.html') else: return render(request,'login.html') but not authorization -
How can I paginate this view?
I am trying to convert this function-based view to a class-based view for the purpose of pagination. def tag(request, tag): posts = Post.objects.filter(approved=True, tags__name__in=[tag]).order_by('-date_posted') return render(request, 'blog/tag.html', {'tag': tag, 'posts': posts}) I wrote it like this: class TagView(ListView): model = Post template_name = 'blog/tag.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 3 def get_queryset(self): return Post.objects.filter(approved=True, tags__name__in=[tag]).order_by('-date_posted') But this does not display any posts when I load the page. Can anyone tell me why this is? Or if you know another way of paginating this view without converting it to a class-based view that would also be appreciated. Thank you in advance. -
AWS ElasticBeanstalk how to upload staticfiles with django
I tried uploading staticfiles: aws:elasticbeanstalk:enviroment:proxy:staticfiles: /static: /static got this error in 2022-04-27 03:34:07 ERROR "option_settings" in one of the configuration files failed validation. More details to follow. 2022-04-27 03:34:07 ERROR Invalid option specification (Namespace: 'aws:elasticbeanstalk:enviroment:proxy:staticfiles', OptionName: '/static'): Unknown configuration setting. 2022-04-27 03:34:07 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. I also tried only doing python manage.py collectstatic and it did not work I tried my settings.py in this way: STATIC_URL = '/static/' STATIC_ROOT = 'static' and this way(current way im utilizing): STATIC_URL = '/static/' STATIC_ROOT = 'static' STATICFILES_DIRS = [BASE_DIR / 'templates/static'] -
AttributeError in Django - object has no attribute 'get'
It is the code of my Room model class Room(models.Model): #host #topic name=models.CharField(max_length=200) desccription=models.TextField(null=True, blank=True) #participants= updated=models.DateTimeField(auto_now=True) created=models.DateTimeField(auto_now_add=True) and here in views.py , I'm trying to get id def room(request, pk): room=Room.objects.get(id=pk) context={'room':room} return render(request, 'base/room.html', context) but it shows error AttributeError at /room/1/ 'Room' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/room/1/ Django Version: 4.0.4 Exception Type: AttributeError Exception Value: 'Room' object has no attribute 'get' -
Sudden error with Django 'python manage.py runserver' [duplicate]
Recently I started a Django project, created a model, then registered it in admin.py in the same app file. I then got this strange error: (djangoEnv) C:\Users\*****\sample_project>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\*****\djangoEnv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\*****\djangoEnv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\*****\djangoEnv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\*****\djangoEnv\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\*****\djangoEnv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\*****\djangoEnv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\*****\djangoEnv\lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "C:\Users\*****\djangoEnv\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Users\*****\djangoEnv\lib\site-packages\django\contrib\admin\__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "C:\Users\*****\djangoEnv\lib\site-packages\django\utils\module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\roanr\sample_project\projects\admin.py", line 6, in <module> admin.site.register(project) File "C:\Users\*****\djangoEnv\lib\site-packages\django\contrib\admin\sites.py", … -
How to Print celery worker details on windows and mac
I actually had issues printing mine on command prompt because I was using the wrong command but I found a link to a project which I forked Project (If on Mac ) celery -A Project worker --loglevel=info (If on Windows) celery -A Project worker -l info --pool=solo -
Django 3.2 ORM integrated in Tornado server
We're using django 2.2 before and can integrate django orm with our non-async tornado handlers but we're going to upgrade to django 3.2 where you can't run django orm(sync) in a tornado handler(non-async) due to it being async-unsafe unless we use djangos' sync_to_async and make the handler async Question: is there a way where we can still use django 3.2 orm in a tornado server non-async handler? or maybe what's the best way to integrate django orm in tornado handlers? -
Update status and select email recipients with a form - Django
I'm building a Django project where I have a model ('Notice') that has a 'draft' status by default . Its next step is to be "published", which means it is going to be sent by email to several receivers. To define who are going to receive this email, I want to let the user select from a series of checkboxes which people are going to receive this. This should be made from the detail view of the 'draft' Notice. I'm struggling to find the best strategy to build this: should this be a form that saves the selected options in the database in another model (SendNotice)? Should I just save a list of email receivers in the model Notice when updating its status? Maybe I'm complicating myself and there is a simpler approach to do this. Thank you in advance! -
Django Query-set Foreign Key in Pandas Dataframe Getting Duplicate Values
I have models like this. class Product(models.Model): id = models.UUIDField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) status = models.IntegerField(blank=True, null=True) sellerid = models.ForeignKey( "Seller", models.DO_NOTHING, db_column="sellerId", blank=True, null=True ) # Field name made lowercase. groupid = models.ForeignKey( Group, models.DO_NOTHING, db_column="groupId", blank=True, null=True ) # Field name made lowercase. createdat = models.DateTimeField( db_column="createdAt", blank=True, null=True ) # Field name made lowercase. updatedat = models.DateTimeField( db_column="updatedAt", blank=True, null=True ) # Field name made lowercase. class Meta: managed = False db_table = "product" class Group(models.Model): id = models.UUIDField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) status = models.IntegerField(blank=True, null=True) image = models.CharField(max_length=255, blank=True, null=True) createdat = models.DateTimeField( db_column="createdAt", blank=True, null=True ) # Field name made lowercase. updatedat = models.DateTimeField( db_column="updatedAt", blank=True, null=True ) # Field name made lowercase. class Meta: managed = False db_table = "group" class SubCategoryGroup(models.Model): id = models.UUIDField(primary_key=True) subcategoryid = models.ForeignKey( SubCategory, models.DO_NOTHING, db_column="subCategoryId", blank=True, null=True ) # Field name made lowercase. groupid = models.ForeignKey( Group, models.DO_NOTHING, db_column="groupId", blank=True, null=True ) # Field name made lowercase. class Meta: managed = False db_table = "sub_category_group" And then from sub category to category. Im querying from Products to get all including which category and subcategory they belong to into a … -
Understanding Django lazy querysets and how they work with function borrowing and Casting columns to integers
I have created a function that I use to apply filters sent from the frontend to query django's database. I include it in the get_queryset method of various ViewSet's. The main issue that arises is when I try to cast one of my model fields to an int to allow me to apply __gt queries to it. The field can contain normal character strings and string representations of integers, but I can easily filter non integer strings based on another field. I thought this would allow me to cast each item in a queryset without reciving an 'is not a valid integer' error when casting the field. But this isn't the case, and I believe the reason has to do with lazy querysets/queryset function borrowing rules. Example Viewset def get_queryset(self): queryset = MyModel.objects.all() # ... # ... other queries # ... filter_model = self.request.query_params.get('filter') if filter_model: queryset = apply_filter(queryset, filter_model) return queryset apply_filter def apply_filter(queryset, filter_model): for _filter in filter_model: # filter models to ensure only instances with valid integer strings are in the queryset field_qs = RelatedChildModel.objects.filter(data_field__name=_filter['name']) # cast integer field field_qs = field_qs.annotate("value_int"=Cast("value", output_field=IntegerField())) # solely to double check that every instance in the queryset has cast an … -
How would I customize a Buefy (or Bulma if easier) implementation with a custom theme/vars/colors in a Django project?
I have a Django web app with Vue on the frontend. I installed Buefy to get easy-to-use components. I'd like to create a theme file to customize some of the colors (things like is-info, primary, etc.) The Buefy and Bulma documentation basically just says "create a SCSS file and then you can specify variables"...but it doesn't explain WHERE this file would go, and how to ensure it gets converted to css, or integrated with webpack, etc. How would I integrate a custom .scss file into my project so it compiles and loads in my app? -
TypeError: wrapper() missing 1 required positional argument: 'backend' happens while tryting to do Oauth2 login
this is my views.py @api_view(http_method_names=['POST']) @permission_classes([AllowAny]) @psa() def exchange_token(request, backend): serializer = UserSerializer(data=request.data) if serializer.is_valid(raise_exception=True): user = request.backend.do_auth(serializer.validated_data['access_token']) if user:#drf built in token authentication?? token, _ = Token.objects.get_or_create(user=user) # drf token authentication return Response({'token':token.key}) else: return Response( {'errors':{'token':'Invalid token'}}, status = status.HTTP_400_BAD_REQUEST, ) https://www.toptal.com/django/integrate-oauth-2-into-django-drf-back-end I'm following this page and trying to request using postman But above error happends. I think I should pass "backend" argument when requesting, but I don't know what to do right now... someone please tell me how can I solve this problem -
Add extra field to django queryset after getting data from some api in graphql's resolver method?
I have a graphql api and there is product resolver method that returns queryset of products. I want to add a new field for every product in the queryset. The new field will be a an index with key of "similarity" and then there would be value. I have tried to use annotate but that does not work in my case. Need guidance on how can I go about this? Thanks in advance. -
Besy way to create records in bulk in django rest framework
I'm a newbie in Django and I'm currently creating my records but I want a more efficient way that can reduce the time and load on the server. Please let me know the best approach to create bulk records with ForeignKeys relations. models.py class Task(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, null=True, blank=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True) account = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class Meta: db_table = 'tasks' views.py @api_view(['POST']) def create_task(request): # added request JSON below try: response = [] for task in request.data: data = {} data['name'] = task['name'] data['description'] = task['description'] data['project'] = task['project_id'] data['account'] = task['user_id'] serializer = TaskSerializer(data=data) serializer.is_valid() serializer.save() response.append(serializer.data) return Response(response) except Exception as e: return Response(str(e)) serializers.py class TaskSerializer(serializers.ModelSerializer): project = ProjectSerializer(read_only=True) # added to fetch project detail in get request user = UserSerializer(read_only=True) # added to fetch user detail in get request class Meta: model = Task fields = ['id', 'name', 'description', 'project', 'user'] request from client side [ { "name": "foo", "description": "lorem ipsum", "project_id": 1, "user_id": 1 }, { "name": "bar", "description": "lorem ipsum", "project_id": 1, "user_id": 2 }, { "name": "baz", "description": "lorem ipsum", "project_id": 1, "user_id": 3 } ] -
How to filter with a non non-model field?
I have a model with one of its fields is a random generated string as the following from django.utils.crypto import get_random_string class Competition(models.Model): name = models.CharField(verbose_name="challenge name", max_length=256) start_date = models.DateTimeField(verbose_name="start date") end_date = models.DateTimeField(verbose_name="end date") code = get_random_string(length=6) owner = models.ForeignKey(User, related_name="owner", on_delete=models.CASCADE) def __str__(self): return self.name I am trying to have an endpoint like thathttp://192.168.1.2:8000/competitions/?code=${some_string} to access from react frontend. so in order to do so I have some filters from django_filters import rest_framework as filters class CompetitionFilter(filters.FilterSet): class Meta: model = competition fields = { "name": ["exact", "icontains"], "code": ["exact"], "start_date": ["exact", "lte", "gte"], "end_date": ["exact", "lte", "gte"], "owner": ["exact"], } but I have an error saying TypeError: 'Meta.fields' must not contain non-model field names: code So how can I achieve it? -
how to use ajax to update cart items
So, trying to use ajax to update the {{cartItems}} on nav when someone hits the add-to-cart button on template without reloading the page but can't get ajax to work, been at it for quite some time. would really appreciate it if someone can help, thx! views.py def ajax_update(request): data = cartData(request) cartItems = data['cartItems'] context = {"cartItems": cartItems} return render(request, 'store/shop.html', context) urls.py path('ajax_update/', views.ajax_update, name="ajax_update"), cart.js function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[productId]; } } console.log('CART:', cart) document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" /*replacing location.reload() with ajax*/ function updating_cart_ajax(){ $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: 'ajax_update/', type: 'POST', data : { 'cartItems' : cartItems, }, success: function(data){ console.log('success') console.log(csrftoken) } }) } } template {% for product in products %} <div class="shop-card"> <a href="{{product.slug}}"> <div class="image-card-wrapper"> <img id="store-cart-img" src="{{ product.image_URL }}"> </div> <div class="card-shop-info"> <p>{{product.name}}</p> <p id="styleb">${{product.final_price | floatformat:2}} | <a data-product="{{product.id}}" data-action="add" class="add-to-cart-action update-cart">Add to cart</a></p> </div> </a> </div> {% endfor %} -
Cannot assign "id": "Product.category" must be a "CategoryProduct" instance
i'm working on a django project and i got this error (Cannot assign "'11'": "Product.category" must be a "CategoryProduct" instance.) anyone here can help me please. Model: class Product(models.Model): name = models.CharField("Nombre", max_length=150) category = models.ForeignKey(CategoryProduct, on_delete=models.SET_NULL, null=True, related_name='category') def __str__(self): return self.name View: class ProductCreateView(CreateView): model = Product form_class = ProductForm success_url = '/adminpanel/products/' def post(self, request, *args, **kwargs): form = self.get_form() category = CategoryProduct.objects.get(id=request.POST['category']) if form.is_valid(): product = form.save(commit=False) product.category = category product.save() Form: class ProductForm(forms.ModelForm): name = forms.CharField(max_length=150, label="Nombre") category = forms.ChoiceField(choices=[(obj.id, obj.name) for obj in CategoryProduct.objects.all()], label="Categoría") class Meta: model = Product fields = ['name', 'category'] -
django orm like Wikipedia
imagine we have a model like post: id title->char body->text version or created-at now we nead to retrieve the latest post that grouped by title. latest field can be a veraion thats be a number or maybe a date. how can i write this query. Preferred django-orm query. thanks IF confused can check example: post1: title:test body: old body version:1 post2: title:test body:new body version:2 post3: title:bee body: old version:1 post4: title:bee body:new version:2 post5: title:bee body:newest version:3 post6: title:cow body:cow version:1 now we nead to retrieve posts like this post2, post5, post6 -
Unable to use django-extensions commands
I have created an app and project using django_cookie_cutter. I can run admin_generator, reset_db, makemigrations, migrate. show_urls is not listed in the subcommands dumpdata is and I cannot use dumpdata. Python==3.9 Django==3.2.13 django-extensions==3.1.5 pip3 install django-extensions Added to INSTALLED_APPS django_extensions and my app >>> import django_extensions >>> django_extensions.VERSION (3, 1, 5) manage.py Type 'manage.py help <subcommand>' for help on a specific subcommand. Available subcommands: [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate runserver sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver -
replace('\n','') does not work for import to .txt format
csv_reader = csv.reader(io_string, delimiter='\t',quotechar="|") for column in csv_reader: column_1 = str(column[1]).replace('\n','') b = Module( user= request.user, a=column_1, b=column[2], ) b.save() ** Here, in column_1 there is such data as an example in the .txt file 'This is a value' and I want to output this data as 'This is a value' after importing it, but I can't. How should I do?** -
Create a minute and hour MultiValueField implementation in django forms
I'm having some troubles to create a form in Django, I don't know if my aproaches are correct soy any help of where I have to read will be appreciated. I want to show a field compose by two fields, one for hours and the other for minutes, reading Django documentation I came out with the idea to use MultiValueField, and I tried this: class CreateEventForm(forms.ModelForm): class TimeField(forms.MultiValueField): def __init__(self, **kwargs): error_messages = { 'incomplete': 'Missing info', } fields = ( forms.CharField(max_length=64, label= "Horas"), forms.CharField(max_length=64, label="Minutos") ) super().__init__( error_messages=error_messages, require_all_fields=False, fields=fields ) journal_start = TimeField() journal_finish = TimeField() class Meta: model = UserEvent fields = ['duration', 'pre_time', 'post_time'] labels = { 'duration': 'Duración', 'pre_time': 'Previo', 'post_time': 'Después: ', } But instead of having two different fields for starting and finishing journey I only have one, this is the picture of the output How can I make a Django form field with two inputs using Model Forms? thanks for reading me! -
How to display ForeignKey fields in a table from inside a DetailView in Django?
I have two models Account and Order and I would like to render a Django table OrderTable will all orders of an account from inside a DetailView. To do that I first select the orders related to the Account instance with self.object and then I build the table into get_context_data, but the problem is that Django throws an error. What is the right way to to do that ? Cannot resolve keyword 'clientid' into field. Choices are: active, email, name [...] models.py class Account(models.Model): name = models.CharField(max_length=100, null=True, blank=False) active = models.BooleanField(null=True, blank=False, default=False) email = models.EmailField(max_length=100, blank=True) class Order(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='order', null=True) clientid = models.CharField(max_length=150, null=True) dt_update = models.DateTimeField(auto_now=True) dt_create = models.DateTimeField(default=timezone.now, editable=False) tables.py import django_tables2 as tables from myapp.models import Order class OrderTable(tables.Table): class Meta: model = Order fields = ('clientid', 'dt_create', 'dt_update') views.py class AccountDetailView(SingleTableMixin, generic.DetailView): model = Account table_class = OrderTable context_table_name = 'table' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Select orders of the account and render a table orders = Order.objects.filter(account=self.object) context['orders'] = OrderTable(orders) return context Template {% extends "base_generic.html" %} {% load static %} {% load django_tables2 %} {% load render_table from django_tables2 %} {% block content %} <h1>{{account.name}}</h1> <p>Orders … -
Question about Django cookie management (API rest) in Flutter application. Is my system robust?
I'm starting in Flutter and I built an api with a login. For authentication I get a cookie from my Django REST API. From my login POST request i store these cookies in my app. cookie sample (1): {set-cookie: csrftoken=7IASHmHBDkqkFxPnYF5rRjEaT0hyd4cxSKHKx2ibnNmmYBBvX68gVKOSDjPZxPAB; expires=Tue, 25 Apr 2023 21:35:15 GMT; Max-Age=31449600; Path=/; SameSite=Lax, sessionid=05yj1bmg5ei7riw8glh13d0gmmw06jbq; expires=Tue, 26 Apr 2022 23:35:15 GMT; HttpOnly; Max-Age=7200; Path=/; SameSite=Lax, date: Tue, 26 Apr 2022 21:35:15 GMT, vary: Accept, Cookie, content-length: 0, referrer-policy: same-origin, cross-origin-opener-policy: same-origin, x-frame-options: DENY, x-content-type-options: nosniff, server: WSGIServer/0.2 CPython/3.10.2, allow: POST, OPTIONS} Then to make a GET request I need to set a cookie of the form bellow. "csrftoken=MZ8YuHN7GaGPId6XEoHOmLJGCj5FrJFU1lElphAxWJVwq366rPoAyI3fOhcEK6ks; sessionid=7cwighx7vbpcoszfl5ltxy2jf32psjeh" To then use it in a Response object from Getx connect package : Response response = await get(appBaseUrl + uri, headers: {"Cookie": COOKIE}); So i manage to transform to the right shape my cookie sample (1) I would have liked to know if my system below is robust because it only needs to change a little bit and nothing will work anymore. Do you have another solution to advise me? Future<ResponseModel> login(String username, String password) async { _isLoading = true; update(); Response response = await authRepo.login(username, password); late ResponseModel responseModel; if (response.statusCode == 202) { print(response.headers); …