Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i access cookie in the django model?
After Login in Django Admin popup appeared in which we have to select a database and it will store in the cookie . Here problem Come How do I get database from the cookie and set on the django model? -
Django app w/Python and JS: Alert modal is not produced when user does not apply search filters to jqGrid
Below I have some python logic for a Django view that takes the search_query and checks if the data the user wants to download has had filters applied, to prevent them from downloading all database records for every page of the grid. The code does reach return JsonResponse; I have checked that. However, the corresponding JS function does not produce the alert modal. There is another piece of js code adjacent to my if(gridData["export_Error"] does produce a modal for a separate gridData value, but why would mine not be working? It seems to attempt to produce the exported CSV instead of stopping to show a modal filters = search_query['filters'][0] filter_list = filters.split('[')[1] list_fields = re.findall("\{(.*?)\}", filter_list) no_search = False for search_filter in list_fields: filter_data = search_filter.split(':')[-1] if filter_data not in ['"2"', '""', '"any"']: break no_search = True if no_search: data = { "export_error": "Results must be filtered before exporting. If you need large exports, " "please contact Production Bioinformatics team." } return JsonResponse(data, safe=False) JS script for producing modal loadComplete: function(gridData){ $('#jqGrid').jqGrid('setGridParam', {postData:{download:false}}); $(function(){ $(".toggle_search").attr("disabled", false); }); $(".overlay").hide(); if(gridData["export_error"]){ showAlertModal("Error", griData["export_error"]); } -
It work for me, yout need change the LANGUAJE CODE IN the settings.py
In django, you need change the language in you setting.py like that: LANGUAGE_CODE = 'es-PE' i'm from Perú. -
Partial update on boolean fields in Django not updating the field in Database
I'm trying to update boolean fields using PATCH request and partial-update in DRF. However, only the name field gets updated and not the others Model: class UserModel(): name = models.CharField(max_length=64) enabled = models.BooleanField(default=False) admin = models.BooleanField(default=False) Serializer class UserSerializer(): class Meta: model = UserModel fields = ( 'id', 'name', 'enabled', 'admin' ) read_only_fields = ('id',) View and function class UserView(): def get_queryset(self): return User.users.for_company(company=self.request.company.pk) def get_serializer_class(self): return UserSerializer def update(self, request, id): try: instance = self.get_queryset().get(id=id) except User.DoesNotExist: return Response('User not in DB', status=status.HTTP_404_NOT_FOUND) if 'name' in request.data and self.get_queryset().filter(name=request.data['name']).exists(): return Response('Duplicated user name', status=status.HTTP_400_BAD_REQUEST) serializer = self.get_serializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) Url urlpatterns = [ url(r'^(?P<id>${uuid})/$', UserView.as_view( {'patch': 'update'}), name='user-update') ] Currently if I send a PATCH request with a user_id and the following data in the body, ONLY the name field gets updated in the DB. name = user2 enabled = True admin = True However if I change the update method as follows, the DB gets updated correctly def update(self, request, id): try: instance = self.get_queryset().get(id=id) except User.DoesNotExist: return Response('User not in DB', status=status.HTTP_404_NOT_FOUND) if 'name' in request.data and self.get_queryset().filter(name=request.data['name']).exists(): return Response('Duplicated user name', status=status.HTTP_400_BAD_REQUEST) serializer = self.get_serializer(instance, data=request.data, partial=True) if 'enabled' or 'admin' … -
setup crontab with docker in django
I'm want to run a cron job and I have a docker envrioment but unfortunately the corn is not working. Dockerfile FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # COPY ./core /app WORKDIR /app EXPOSE 8000 COPY ./core/ /app/ COPY ./scripts /scripts RUN pip install --upgrade pip COPY requirements.txt /app/ RUN apt-get update && apt-get install -y cron && service cron start && \ pip install -r requirements.txt && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts USER app CMD ["/scripts/run.sh"] settings.py INSTALLED_APPS = ( 'django_crontab', ... ) # Cron Jobs CRONJOBS = [ ('* * * * *', 'projects.cron.notifications_cron', '>> /var/log/cron.log') ] cron.py: def notifications_cron(): print("hello from cron") when I check cron status in my docker container so it throws me following error: app@40e4b7a671cd:/app$ service cron status cron is not running ... failed! python manage.py crontab show app@40e4b7a671cd:/app$ python manage.py crontab show Currently active jobs in crontab: 822cc1d53a9bdce5e2b3a94a98bdb284 -> ('* * * * *', 'projects.cron.notifications_cron', '>> /var/log/cron.log') I'm unable to figure out what's the issue -
Django mptt filters children
I'm building an eCommerce website that has categories and sub-categories. I'm using the Django MPTT model for the categories. I want to add the children of the category while filtering the category and when filtering the children only the children to get filtered. Here's the filtering process I tried: views.py def categoryview(request): category = Category.objects.all() return render(request, 'products/category.html', {'category':category}) def filteredproducts(request, slug): category = Category.objects.get(slug = cat_slug, is_active =True) products = Products.objects.filter(category = category, is_active = True).order_by('-created_on') return render(request, 'products/filteredproducts.html', {'products': products}) models.py class Category(MPTTModel): category = models.CharField(max_length = 255) cat_slug = models.SlugField(max_length = 255, unique = True, default = 'random') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class Meta: unique_together = ('cat_slug', 'parent') verbose_name_plural = "categories" def __str__(self): return self.category -
using Django views Queries in graphene resolvers
how can i use my django view qureies in graphene resolvers as queries def get_queryset(self): return CustomerModel.objects.for_entity( entity_slug=self.kwargs['entity_slug'], user_model=self.request.user ).order_by('-updated') i trie this it did not work class CustomerList(DjangoObjectType): """testing API """ class Meta: model = CustomerModel fields = ("email",) class CustomerQuery(graphene.ObjectType): all_customers = graphene.List(CustomerList) def resolve_all_customers(self, root, **kwargs): return CustomerModel.objects.for_entity.filter( entity_slug=self.kwargs['entity_slug'], user_model=self.request.user ).order_by('-updated') i get this graphql error { "errors": [ { "message": "'NoneType' object has no attribute 'kwargs'", "locations": [ { "line": 2, "column": 3 } ], "path": [ "allCustomers" ] } ], "data": { "allCustomers": null } } -
Heroku - Django - the application loading process fails
I've been browsing all the options and advice on the internet for 14 days and I can't help it, please help me how to run a properly installed application on Heroku? I'm creating an application on Windows10 and I can't run "gunicorn" there locally, unfortunately, how do I debug or where am I making a mistake...? 2022-03-08T17:05:18.069332+00:00 heroku[web.1]: State changed from up to crashed 2022-03-08T17:05:18.091002+00:00 heroku[web.1]: State changed from crashed to starting 2022-03-08T17:05:17.994885+00:00 heroku[web.1]: Process exited with status 1 2022-03-08T17:05:24.550895+00:00 heroku[web.1]: Starting process with command gunicorn final_sda_project.wsgi --log-file - 2022-03-08T17:05:26.835207+00:00 heroku[web.1]: State changed from starting to up 2022-03-08T17:05:26.291724+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [4] [INFO] Starting gunicorn 20.1.0 2022-03-08T17:05:26.292294+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [4] [INFO] Listening at: http://0.0.0.0:12794 (4) 2022-03-08T17:05:26.292350+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [4] [INFO] Using worker: sync 2022-03-08T17:05:26.296152+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [9] [INFO] Booting worker with pid: 9 2022-03-08T17:05:26.399828+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [10] [INFO] Booting worker with pid: 10 2022-03-08T17:05:26.442367+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [11] [INFO] Booting worker with pid: 11 2022-03-08T17:05:27.924052+00:00 app[web.1]: [2022-03-08 17:05:27 +0000] [11] [ERROR] Exception in worker process 2022-03-08T17:05:27.924073+00:00 app[web.1]: Traceback (most recent call last): 2022-03-08T17:05:27.924074+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-03-08T17:05:27.924074+00:00 app[web.1]: worker.init_process() 2022-03-08T17:05:27.924075+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in … -
django "StringRelatedField.to_internal_value() must be implemented for field " error
I have a model for a "gym", and a model for a "workout": class Gym(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) def __str__(self): return self.name class Workout(models.Model): gym = models.ForeignKey(Gym, on_delete=models.CASCADE) time = models.DateTimeField() I will also show the 'WorkoutSerializer': class WorkoutSerializer(serializers.ModelSerializer): gym = serializers.StringRelatedField() class Meta: model = Workout fields = ['gym','time'] as you can see, gym is represented in the workout json as a string of the field 'name'. here is the view for workout: @api_view(['GET','POST']) def workout_list(request): if request.method == 'GET': queryset = Workout.objects.select_related('gym').all() serializer = WorkoutSerializer(queryset, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = WorkoutSerializer(data=request.data) serializer.is_valid(raise_exception=True) # rasis 400 bad request if needed serializer.save() return Response('ok') when I try to test a POST request with (I want to use the gym's str representation in POST as well): { "gym": "gym 2", "activity": "Yuga", "time": "2022-03-07T06:00:00Z", "participants": [ "Anna Boing" ] } I get the error: StringRelatedField.to_internal_value() must be implemented for field any idea why, and what can I do to fix this? -
how to create a hyperlink in matched results in Django search autocomplete trevoreyre
I am using autocomplete trevoreyre to handle autocomplete function in my search bar. For now, the user is redirected to the search_result page when clicking enter or search icon. The problem is that even if a suggestion appears user must click on title then click enter or search icon, then the function will redirect him to the search_results page, and then user can click on a card that is interested in. I'd like to extend this feature and create a hyperlink in title suggestions so if the user clicks on the title suggestion then the function should redirect the user directly to DetailedView page. I know that I should follow this logic: onSubmit: result => { window.open(`${wikiUrl}/wiki/${ encodeURI(result.title) }`) } but I am not sure how to create a link to DetailView pages if there are 3 models in my Django app and these models have different URLs. I want to add something like onclick event so when the user clicks on suggestion then it will redirect him to the DetailView page but if clicks enter or search icon it will redirect him to the search_result page. base.html <button onclick="openSearch()"><i class="fas fa-search fa-sm"></i></button> <form action="{% url 'search_result' %}" method="get" id="search"> … -
How to auto save data every month?
CentreInvoice model: class CentreInvoice(core_models.TimestampedModel): centre = models.ForeignKey(Centre, null=False, on_delete=models.CASCADE, related_name="c_centre_invoice") rcl_share_amount = models.FloatField(null=True) total_billed_amount = models.FloatField(null=True) start_date = models.DateField() end_date = models.DateField() paneluser = models.ForeignKey("panel.PanelUser", related_name="c_invoice_creator", on_delete=models.DO_NOTHING) invoice_no = models.CharField(max_length=255) total_advance_payment = models.FloatField(default=0) I am using this model to generate invoices in my project. I need to save this manually everytime, but I want it to happen automatically every month. Is there a way to do this? Any advice would be appreciated. -
Sending notification according to user group in Django Channels
I have implemented a notifications functionality in my app where a notification is sent out to employees whenever a new customer is created. The problem I face is that the employees belong to different user groups. I would like to have only one user group, i.e., managers to receive the notification when the new customer is created. All other user groups, 'sales', 'customer service' should not receive that notification. How do you suggest I go about this given I am new to using Django Channels. Thank you -
JavaScript and HTML button
I'm working on a Django project and I'm trying to add buttons that onclick direct you to another page, on a table that is built from a model. Here is the HTML for the table: And here is the JS function: On the site this looks like this: The first button where the ID is 1 when clicked takes me to the right page. The second button though is not doing anything check clicked. What I'm trying to achieve is every time an application object is created and the table is updated I want the to be able to click the button and go to a page with a url like this: /review/id wit the id being the same as the one on the table. -
Django: cannot get data sent by axios in views
I am trying to send post request using axios like usual axios({ method: 'post', url: '/handle_login_info/', headers: { 'X-CSRFToken': csrftoken, }, data: { a: 'a', b: 'b' } }).then(res => console.log(res)).catch(err => console.error(err)) The view function corresponds to /handle_login_info/ is called, but there is nothing in request.POST. If I modify the code above a little like below data: JSON.stringify({ a: 'a', b: 'b' }) then request.POST's value is <QueryDict: {'{"a":"a","b":"b"}': ['']}>. Why does this happen? How do I send and receive axios data normally? -
Heroku hosting uses 5 times more RAM than Google Cloud Run
For my Django application, there are many lists, sets, and dictionaries, that I load from pickle files into RAM, for fast access at any moment. I am getting Error R14 (Memory quota exceeded) on Heroku. I have done lots of debugging and memory usage analysis of Python. I know how to optimize code, and I have optimized everything that can be optimized. Now this is the weird thing: the same application, literally the same deployment, on Google cloud takes 5 times less RAM memory than on Heroku. I deploy both of them from the same Git repo. 1 GB of RAM on google is enough, lets assume it takes around 900 MB RAM there, well on Heroku the same thing takes 4.5 GB RAM, for which I need to "rent" 8 GB RAM, which makes the costs insanely high. Why is this happening? So it's not about optimizing my own code. How can the same app on Heroku occupy around 5 times more RAM than on Google? How I got that measurement of 5 times, is actually, I have an ecommerce website, with products, and they have attributes and values, and also keywords. I store all these values and keywords … -
Filtering a Model with a Foreignkey with a list of other models?
I want to filter the org collectors by their foreign key org_data by a list of org_data with the Github type. OrgCollector.objects.filter( org_data=OrgData.objects.filter( data_type=DataTypeEnum.GITHUB )) I currently have this but it does not work. What do I do instead? Running through the list with a for loop works, but I expect that there is a better way. I also tried org_data__in but that did not seem to work either. -
django 4 recent issue
Django has recently released a new version and I'm trying to work with it. But the problem that I have is that one I say pip install Django no matter in the cmd or visual studio's cmd, it installs Django 4.0, but once I put the file in the code editor (it is vs code), it changes to Django 3.0 and I was shocked once I saw that even in pip freeze` it is changed! I would be so glad if you can help me with this problem -
Django: handle multi stock (related table) in Product Based List View
I need to manage Products shared by multiple Warehouses. I tried to get through with annotate, prefetch_related, select_related but in my case, those solutions are upside-down for my need. I need first to get product and then, the related stock in each warehouse and display it in template and the foreignKey is in my Sststock, not in Product I have : Product models.py class Product(models.Model): famille = models.ForeignKey(Famille, on_delete=SET_NULL, null=True) sku = models.CharField(max_length=100, unique=True) nom = models.CharField(max_length=250) fournisseur = models.ForeignKey( Supplier, on_delete=models.SET_NULL, default=12, null=True) qty = models.IntegerField() mini = models.IntegerField() maxi = models.IntegerField() [...] Warehouse models.py class Warehouse(models.Model): nom = models.CharField(max_length=100) code = models.CharField(max_length=10, null=True) adresse = models.CharField(max_length=255) cp = models.IntegerField() ville = models.CharField(max_length=50) tel = models.CharField(max_length=10) email = models.EmailField(default='sav@iturbo.fr', null=False, blank=False) allow_store = models.BooleanField(default=False) def __str__(self): return self.nom.upper() Sststock models.py class SstStock(models.Model): sst = models.ForeignKey(Warehouse, on_delete=models.CASCADE) mageid = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) qty = models.IntegerField() last_update = models.DateTimeField(default=timezone.now) For the time, I only have 3 warehouses but there could have more in the future. First I had "hard-coded" my 3 warehouses in Product's model but this solution was not easily scalable. What would be the best way to achieve my goal ? I've seen solution with Mysql Stored Procedures in … -
Password saved as plain text in database Django AbstractUser
Actually, I am working on a project and I have to modify the authentication system so that I am able to log in using email instead of a username. Also, I have to remove the username field as it's not relevant for the use case scenario. The problem i am getting is after user registers the password is saved as a plain text in database. Below is my implementation My views.py def signup(request): if request.method == 'POST': password = request.POST['cr-pwd'] email = request.POST['cr-eml'] phone_number = request.POST['cr-phone'] print(password, email, phone_number) user = User.objects.create_user(email, password) # user.username = username user.password = password user.email = email user.phone_number = phone_number user.save() messages.success(request, 'Your account has been created successfully') return render(request, 'index.html') return render(request, 'index.html') My models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular … -
Django - Create custom PrimaryKey with selected ForeignKey object
Problem: I want to create a custom-PrimaryKey in ItemCode Model contain with selected-ForeignKey object. So, It's gonna change the custom-PrimaryKey every time submit a new ForeignKey field. Here's my Model: class ItemCategory(models.Model): idItemCat = models.CharField(primary_key=True max_length=5) nameCategory = models.CharField(max_length=150) class ItemCode(models.Model): idItemCode = models.CharField(primary_key=True, editable=False, max_length=20) idItemCat = models.ForeignKey(ItemCategory, on_delete=models.DO_NOTHING) To illustrate, here's the example of custom-PrimaryKey I wanna create: MN.202203.001 MN means Monitor from selected-ForeignKey object Then, it change every time I submit new ForeignKey field, like this: CM.202203.002 CM means Printer from new selected-ForeignKey object What I've tried: I've tried to using request method but I don't know how to implemented it in my Model. def CustomPK(request): if request.method == 'POST': category = ItemCategory.objects.get(pk=request.POST.get('idItemCat')) return category Question: Is there anyway to get or fetch the object from selected-ForeignKey field to make a custom-PrimaryKey with request method? or is there any better way to do it? If my question isn't clear enough, please let me know... -
django - get values from formset
I've tried to get value from formset do some calculations and pass the output. My code is: def form_valid(self, form, formset): rndid2 = RndIds() form.instance.doc_added_by = self.request.user form.instance.doc_guid = rndid2.random_doc_guid() instances = formset.save(commit=False) for instance in instances: cd = instance.cleaned_data() at_id=cd.get('att_guid') instance.att_added_by = str(self.request.user) instance.att_ctrl_sum = rndid2.random_doc_application_id(at_id) instance.save() return HttpResponseRedirect(self.get_success_url()) But got an error 'Att' object has no attribute 'cleaned_data' Att is my model How can I get the formset values? -
DoesNotExist at /admin/auth/user/. User matching query does not exist
I am trying to delete a user from admin, but can't do it. I tried to delete function by changing sender to User and user= instance but 'maximum recursion depth' error occurs. 1.users/signals.py from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from .models import Profile from django.contrib.auth.models import User @receiver(post_save, sender=Profile) @receiver(post_save, sender=User) def createProfile(sender, instance, created, **kwargs): if created: print('Profile created') user = instance user.save() profile = Profile.objects.create( user=user, username = user.username, email=user.email, ) # @receiver(post_delete, sender=Profile) def deleteUser(sender, instance, **kwargs): user = instance.user // error showing to this line user.delete() # post_save.connect(createProfile, sender=User) post_delete.connect(deleteUser, sender=Profile) **2.Users/models.py from django.db import models import uuid from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models. OneToOneField(User,on_delete=models.CASCADE, null=True,blank=True) name = models.CharField(max_length=200, null=True, blank=True) username = models.CharField(max_length=200, null=True, blank=True) short_intro = models.TextField(max_length=1000,null=True,blank=True) short_bio = models.TextField(max_length=1000,null=True,blank=True) user_image = models.ImageField(null=True,blank=True,upload_to='profiles/',default='profiles/mehdi.png') email = models.CharField(max_length=200, null=True, blank=True) social_github = models.CharField(max_length=200, null=True, blank=True) social_linkedin = models.CharField(max_length=200, null=True, blank=True) social_website = models.CharField(max_length=200, null=True, blank=True) social_twitter = models.CharField(max_length=200, null=True, blank=True) social_stackoverflow = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.username -
Django differentiate between incorrect login information and inactive user on login
Currently I added in my site a method for email confirmation when registering. What I saw though, is that when the user is registered, but didn't click in the confirmation link yet and tries to login, I can't differentiate between wrong user/password and not confirmed user. This is my login function: def loginUser(request): if request.user.is_authenticated: return redirect("decks:index") if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) return redirect("myApp:portal") elif user is not None: messages.error(request, "Email is not confirmed.") else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return render(request, "myApp/login.html", context = {'login_form': form}) The problem is that when running form.is_valid() the authenticate function from /home/nowork/.local/lib/python3.8/site-packages/django/contrib/auth ModelBackend is executed: def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user So the form.is_valid() will never be true when … -
Django/Python - remove row in sqlite3 database with form button
I want to have a delete button to delete a row in my sqlite3 database. I'm almost there but I'm not sure what I should add to send the ID from my html of the row to my views.py. This is what I have: mailindex.html <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <a href="{% url 'core:mail' mail.id %}" class="btn btn-secondary btn-sm">Manage</a> <button type="submit" name="deletemail" value="deletemail" class="btn btn-secondary btn-sm">Delete</button> </div> </form> views.py class MailboxView(generic.ListView): extra_context = {"mailbox_page": "active"} model = MailMessage context_object_name = 'mails' template_name = 'core/mailbox/mailindex.html' def post(self, request): # if 'deletemail' in self.request.POST: if request.POST.get('deletemail'): mail = MailMessage.objects.get(pk=13) mail.delete() return HttpResponseRedirect(self.request.path_info) It works, in a sense that when I push the delete button it deletes email with ID = 13. Which is logical as I put no. 13 there. I would like to replace '13' with the mail.id, but I'm not sure how to do this. I hope it is possible: I would prefer it to be as simple as possible, so to not create an extra url, but again don't know if this is possible... -
Covert String into Hexbytes
I have this signature b'V\xae\xc1\x0bU:\xcaV0\xcbBO@\xe6\xf7\x9c\xb3\xe4R\xa0\xb4\x10\xcf\x1e\x9b\xc3\x03\t\x84\xf9\x92!\xd2p\x12\x16*\x8biJ\xfeNq\x11\xfa5\x05\n\x19*9\xdak\x989j\xd8:\x7f\xdd\x03\xa2\xd7\x1c' but it is in string format. I am using w3.eth.account.recover_message(encode_defunct( text=account_address.challenge), signature=signature) to get address back, but as it only accepts <class 'hexbytes.main.HexBytes'> format. So can please anyone help me convert this value into Hexbytes but as you can see value of string should not change. I am using django here.