Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I pass html files as the context for render in Django?
I have a home.html, a1.html, b1.html. Most codes are the same in these three files, so I made a base.html that I want to use as the template. {{the_different_stufs}} I'd like to save the the_different_stufs in other files. -
Django: How to avoid multiple http requests to rest API by having one endpoint connect to multiple
The API will be used to receive data from test results of different products. Currently I have a model for each unique product. The problem here is that I want to avoid sending multiple requests for each uniques products test result and I wonder how to approach this in Django. I pretty much want to achieve the same thing as noted in this question: How to creating a single endpoint with multiple endpoints connecting to it but with Django's rest api. -
how to return related data to a foreignkey django ajax
i have a project with two models one for computer features and the other for computer invoice class ComputerFeature(models.Model): car_model = models.CharField(max_length=50) CPU = models.CharField(max_length=30) RAM = models.CharField(max_length=30) #others class CustomerInvoice(models.Model): customer = models.CharField(max_length=50) model = models.ForeignKey(ComputerFeature, on_delete=models.CASCADE) order = models.IntegerField(default=1) price = models.IntegerField() and this is my template <form method='POST'>{% csrf_token %} <table class="table"> <thead> <tr> {{ form.customer.errors }} <th class="float-left" id="customer">Customer : {{ form.customer }}</th> </tr> </thead> </table> <table class="table"> <thead> <tr> <td><div class="form-group floating-label" id="modeling"> {{ form.model | add_class:'form-control select2-list ' | attr:'id:model'}} </div></td> </tr> <tr> {{ form.order.errors }} <td scope="col">quantity</td> <td scope="col" id="order">{{form.order}}</td> </tr> <tr> <td scope="col">CPU</td> <td scope="col" style="width: 50%" id="cpu"> <--! i want to return CPU here before submiting the form --> </tr> <tr> <td scope="col">RAM</td> <--! i want to return CPU here before submiting the form --> </tr> <tr> {{ form.Hard.errors }} <td scope="col">Hard</td> <td scope="col" id="hard">{{form.model.Hard}}</td> </tr> <tr> <td scope="col">Graphic</td> <--! i want to return CPU here before submiting the form --> </tr> <tr> {{ form.price.errors }} <td scope="col">price/td> <td scope="col" id="price">{{form.price}}</td> </tr> </thead> </table> <input type="submit" name="save" value="selling" class="btn btn-primary btn-block" id="submit"> </div> </div> </form> i need to return CPU,RAM and other feature from ComputerFeature before submitting the form , recall … -
ImportError: cannot import name 'app_settings' from 'leaflet'
I was running django project in Anaconda prompt and I got the following error: File "C:\Users\hp\geoportal_geodjango\mysite\polls\admin.py", line 4, in from leaflet.admin import LeafletGeoAdmin File "C:\ProgramData\Anaconda3\lib\site-packages\leaflet\admin.py", line 17, in from .forms.widgets import LeafletWidget File "C:\ProgramData\Anaconda3\lib\site-packages\leaflet\forms\widgets.py", line 15, in from leaflet import app_settings, PLUGINS, PLUGIN_FORMS ImportError: cannot import name 'app_settings' from 'leaflet' (C:\ProgramData\Anaconda3\lib\site-packages\leaflet_init_.py) I tried different leaflet versions. -
How to create a model in Django for a chatting platform?
I'm trying to figure out the model structure for a chatting platform in Django, which will save the two users that are talking and also give them a unique room_name. What I tried till now goes like following: models.py class Chat(models.Model): room_name= models.CharField(max_length=100) # I TRIED THIS BUT DIDN"T WORKOUT owner= models.ForeignKey(User, on_delete= models.CASCADE, related_name="owner") chatting_to= models.ForeignKey(User, on_delete=models.CASCADE, related_name="chatting_to") def __str__(self): return "{}".format(self.pk) class Message(models.Model): chat= models.ForeignKey(Chat, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.chat.owner.username If I put a ManyToManyField then I won't be able to create unique room_name for each set of user. How should I create the models then? Give an elaborate answer if possible. -
Allowing Users to Own Their Data and Connecting Data to Certain Users in django
i am making an assignment to add events in calender but after login all user can see the same evebts, this is my models.py code, i m trying to make an event in calender connecting to certain user who logged in but i have no idea, what to do next, because every user can access the event of every other user from django.db import models from django.urls import reverse from django.contrib.auth.models import User class Event(models.Model): title = models.CharField(max_length=200) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() owner = models.ForeignKey(User, on_delete=models.CASCADE) @property def get_html_url(self): url = reverse('cal:event_edit', args=(self.id,)) return f'<a href="{url}"> {self.title} </a>'enter code here this is my views.py code, from datetime import datetime, timedelta, date from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.views import generic from django.urls import reverse from django.utils.safestring import mark_safe import calendar from .models import * from .utils import Calendar from .forms import EventForm def index(request): return render(request, 'cal/index.html') class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context def get_date(req_month): if req_month: year, month = … -
Crawling spider and scheduling them
I have created a spider that crawls news. I want to run that spider and schedule it too. It is within a django project. It is such that the spider has will crawl the data and put it into the database, which will be used by django to display the same data. Here's my spider `class NewsSpider(CrawlSpider): name = "news" start_urls = ['https://zeenews.india.com/latest-news'] def start_requests(self): urls = ['https://zeenews.india.com/latest-news'] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): item = NewsScraperItem() data = response.css('div.sec-con-box') item['headlines'] = data.css('h3::text').extract_first() item['content'] = data.css('p::text').extract_first() return item` items.py: `import scrapy from scrapy_djangoitem import DjangoItem from news.models import LatestNews class NewsScraperItem(DjangoItem): # define the fields for your item here like: # name = scrapy.Field() django_model = LatestNews` -
Django mptt - how to show full name
is there any option to show full name in Django mptt? For example, I have model: class RecipeCategory(MPTTModel): title = models.CharField(max_length=255, verbose_name='Nazwa kategorii') full_name = models.CharField(max_length=255, verbose_name='Pełna nazwa') body = models.TextField(verbose_name='Opis kategorii', blank=True, help_text='To pole nie jest obowiązkowe. Jeśli chcesz, możesz napisać co konkretnie ma być dodawane do tej kategorii.') image = models.ImageField(upload_to='Tło', default='defaultbgcategory.jpg' ,verbose_name='Tło kategorii', help_text='Dodając zdjęcie jesteś w stanie wyróżnić kategorię, jeśli jednak tego nie zrobisz nic się nie stanie. :)', null=True, blank=True) slug = AutoSlugField(populate_from='title', unique=True) parent = TreeForeignKey('self', related_name='children', db_index=True, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Kategoria') subscribers = models.ManyToManyField(User, related_name='subscribed_category', blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) Model has title, parent field and full name, how to save full name containing title and parent title like: Title - parent title. In template it's not problem, but I try to create this in rest framework. -
Annotate Django queryset with result of date + timedelta calculation
I am looking to annotate a Django queryset with the result of a date + timedelta calculation. Date is stored as a Django DateField() and the timedelta is stored as a Django Duration() field. Result should be a datetime. Queryset is being annotated as per the code below: class MyModelObjectsManager(models.Manager): def get_queryset(self): result = F('my_date') + F('my_timedelta') return super().get_queryset().annotate( start_time=ExpressionWrapper(result, output_field=DateTimeField()) ) Following error occurs when attempting to use queryset: File "/app/venv/lib/python3.6/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/app/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/app/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1318, in _add_q split_subq=split_subq, simple_col=simple_col, File "/app/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1207, in build_filter condition = self.build_lookup(lookups, reffed_expression, value) File "/app/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup lookup = lookup_class(lhs, rhs) File "/app/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 20, in __init__ self.rhs = self.get_prep_lookup() File "/app/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup return self.lhs.output_field.get_prep_value(self.rhs) File "/app/venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1408, in get_prep_value value = super().get_prep_value(value) File "/app/venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1268, in get_prep_value return self.to_python(value) File "/app/venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1362, in to_python (self.model.__name__, self.name, value), AttributeError: 'DateTimeField' object has no attribute 'model' Above code follows other examples I've seen on S/O, for example here. Is it possible to annotate a Django queryset with the result of a date + timedelta calculation? If not, is … -
Django auto delete function
I'm trying to create a random discount code generator in django. And I have created a model for it in which there's an expiration date field 'valid_to'. I want the function to delete the coupon object when the time is now. models.py class Coupon(models.Model): code = models.CharField(max_length=10, unique=True, blank=True) valid_from = models.DateTimeField(default=datetime.now, blank=True) valid_to = models.DateTimeField(default=datetime.now() + timedelta(days=20)) discount = models.IntegerField(default=15, validators=[MinValueValidator(0),MaxValueValidator(100)]) active = models.BooleanField(default=True) def save(self, *args, **kwargs): if self.code is None or self.code == "": self.code = code_generator() super(Coupon, self).save(*args, **kwargs) def __str__(self): return self.code -
Generating a model field on process using Django
I am new to Django and I have a newbie problem. I have a Optical Character Recognition (OCR) project. I like to create an api using Python Django. My system should accept an pdf input from user and process with it and return output pdf file. At the end of the process, the api return should be like at below. { "id" : 1, "title": "Pdf title", "input" : "input.pdf", "output" : "output.pdf" } I use Django Rest Framework to generate this api. My question is, how can I be able to generate output file on process? class Document(models.Model): title = models.CharField(max_length=255) pdf_input = models.FileField(upload_to='documents/inputs', max_length=100, blank=True) pdf_output = models.FileField(upload_to='documents/outputs', max_length=100, blank=True) If I create a model as above, I should upload the pdf_output first place. However, I like it to be generated on process. -
Is there any way to put id along with <a> tag in coloums of datatables(serverside processing) in html page?
I tried to put a tag in data tables coloum, to work it as update link. But I can't able to make it as working url. I tried many ways still error is coming. i will get pk, if i put "data" = "pk", then default content will be removed. data.html <script> $(document).ready( function () { var default_url; default_url = "{% url 'f_admin:persons_serverside' %}" $('#myTable').DataTable({ "processing": true, "serverSide": true, "searching": true, "ajax": "{% url 'f_admin:person_json' %}", "columns": [ {"data": "code"}, {"data": "offer_name"}, {"data": "offer_arabic"}, {"data": "valid_from"}, { "data": null, "defaultContent": '<a target="_blank" href="'+default_url+'">test</a>' } ] }); }); models.py class Offers(BaseModel): code = models.CharField(max_length=255,blank=True, null=True) offer_name = models.CharField(max_length=255,blank=True, null=True) offer_arabic = models.CharField(max_length=255,blank=True, null=True) valid_from = models.DateField(blank=True, null=True) def to_dict_json(self): return { 'pk': self.pk, 'code': self.code, 'offer_name':self.offer_name, 'offer_arabic': self.offer_arabic, 'valid_from': self.valid_from, 'edit' : '' } what I need is, an edit link in every row. Which can pass id to backend view. Edit Please help me, where I went wrong, is there any other method? -
For loop through ManyToMany field in Django view returns only the first Query
I want to iterate through ManyToMany field of an object in my views getting the sum of all query sets But, what happens is that i got an error because the for loop got only the first query result and gives an error of operand + can not be between none and decimal values!! Here Is My Code: models.py class TourPackage_trip(models.Model): trip_Price_EGP = models.DecimalField(default=0, null=True, max_digits=15,decimal_places=2) class TourPackage(models.Model): trips = models.ManyToManyField(TourPackage_trip) views.py def PayNowTourPackageView(request, tour_id, buyer_id): tour = TourPackage.objects.get(id=tour_id) trips = tour.trips.all() for trip in trips: trip_fees += trip.trip_Price_EGP Any Help For That Will Be Thankful -
Unique Field not showing in Validation
my serializer class DeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = '__all__' my model class Device(models.Model): DeviceId = models.AutoField(primary_key=True, db_column='DeviceId') DeviceCode = models.CharField(max_length=25, null=False, blank=False, unique=True, default=None) Camera = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='CameraId') DeviceType = models.ForeignKey(DeviceType, on_delete=models.CASCADE, db_column='DeviceTypeId') class Meta: db_table = "Device" View.py serializer = DeviceSerializer(data=request.POST) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) but while i am checking in postman , No validation showing in case of DeviceCode , please find the image.. i want to show DeviceCode also as Required filed. Postman -
Pyhon: Exception Value: unsupported operand type(s) for -: 'str' and 'int'
I have set in my django project I have set the following class: models.py class Budget_Vendite(models.Model): MY_CHOICES = ( ('jan', 'jan'), ('feb', 'feb'), ('mar', 'mar'), ('apr', 'apr'), ) month = models.CharField(max_length=10, choices=MY_CHOICES, default="") year=models.IntegerField(default="") prodotto=models.ForeignKey() sottoprodotto=models.ForeignKey() prezzo_unitario=models.DecimalField() quantita=models.DecimalField() In my views I have set the following code: Views.py defaults = list(0 for m in range(12)) for prodotto_id, year, month, totale in(Budget_Vendite.objects.values_list('prodotto__name', 'year', 'month').annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('prezzo_unitario')), output_field=FloatField())).values_list('prodotto__name', 'year', 'month', 'totale')): if prodotto_id not in ricavi_bdgt_2.keys(): ricavi_bdgt_2[prodotto_id]=list(defaults) index=month-1 ricavi_bdgt_2[prodotto_id][index]=totale total_ricavi_2={'Fatturato Previsionale': [sum(t) for t in zip(*ricavi_bdgt_2.values())]} But django give me the following error: File "C:\Users\Federico\Desktop\Prova test\Budgeting\budget_vendite\func.py", line 36, in ce_func_bdgt index=month-1 TypeError: unsupported operand type(s) for -: 'str' and 'int' Where is the error? -
"message": "'ModelBase' object is not iterable", Django
I was trying to get data on the excel sheet ,i am getting this error class Task(models.Model): Name=models.CharField(max_length=50,null=False,blank=True,primary_key=True) Image1=models.FileField(blank=True, default="", upload_to="media/images",null=True) Image2=models.FileField(blank=True, default="", upload_to="media/images",null=True) Date=models.DateField(null=True,blank=True) def __str__(self): return str(self.Name) plans=Task.objects.all() workbook=xlsxwriter.Workbook('data.xlsx') worksheet=workbook.add_worksheet() b=[] for plan in plans: b.append({ "Name":plan.Name, "Image1":plan.Image1.url, "Image2":plan.Image2.url, "Date":plan.Date, }) row=1 col=0 for Name,Image1,Image2,Date in (Task): worksheet.write(row,col,Name) worksheet.write(row,col+1,Image1) worksheet.write(row,col+2,Image2) worksheet.write(row,col+3,Date) row+=1 workbook.close() print(workbook) return Response({'success':b,"sheet":worksheet}) -
maximum recursion depth exceeded while calling a Python object somthing strange
from django.conf.urls import url,include urlpatterns = [ url(r'', include('lesson1.urls')), ] this is main code,but I dont know why this eror exists it must work -
Email validator not working properly in django?
I am not using django forms here and I am validating field with ajax/jquery but this code is not working properly. If I enter the correct email it displays the error message but if i enter the invalid email then it doesn't display the error. Also this validate_email(request.GET.get('email', '')) always returns None. views class ValidateEmailField(View): def get(self, request): email = validate_email(request.GET.get('email', '')) print(email) data = {} if not email: data = { 'error_message': 'Invalid Email' } return JsonResponse(data) template dataType: 'json', success: function (data) { if (data.error_message) { $(".error").text(data.error_message).show(); $('#id_btn').prop("disabled", true); } else { $(".error").text(data.error_message).hide(); $('#id_btn').prop("disabled", false); } -
Django: setting a different SESSION_COOKIE_DOMAIN depending on the domain
I use the same Django project for various domains. Some are subdomains, some are entirely different domains, so I have these domains operating the same Django site: a.example1.com b.example1.com c.example1.com example1.com example2.com I do not use the sites framework for reasons unrelated to this query, and I have a single settings.py for all sites, which I'd like to maintain. When someone logs onto a subdomain, I'd like them to be logged onto any of the other subdomains as well. In fact, if it were possible I'd like them to be logged onto the other sites as well but I doubt this is possible. In order to achieve logging into all subdomains at the same time, I set the following variable in settings.py: SESSION_COOKIE_DOMAIN=".example1.com" This works as advertised and the logins are now working across different sites. However, I am not able to log onto any of the other domains anymore (I assume the cookie is set for the wrong domain and subsequently not properly recognized). What I assume I should do is somehow set SESSION_COOKIE_DOMAIN to either .example1.com when on the main site, or .example2.com when I'm on a different site. But how to achieve this? Here is a similar … -
Python save a file retrieved from api request
I'm new to python. I'm using docusign demo API to retrieve a document which is returned using the following code temp_file = envelope_api.get_document( account_id=ExampleBase.accountID, document_id=document_id, envelope_id=envelope_idd ) This returns a temp file of pdf, docx or zip format. My requirement is to save this file to a location of my choice. So far my searches have brought me across different libraries but none of them seem to work in my case (most of them are url centric). Any help or sense of direction to achieve this is appreciated. Following is a detailed response: {'data': '/var/folders/9r/4_w9qasd323r7b_vymc0m0000gp/T/06298232_132210_920997_World_Wide_Corp_Battle_Plan_Trafalgar.docx.pdf', 'doc_name': 'World_Wide_Corp_Battle_Plan_Trafalgar.docx.pdf', 'mimetype': 'application/pdf'} -
DRF: How to hide the password in serializers that using depth option?
I'm using the below serializer for the User model, but when I'm using depth for handling foreign keys, password shows in the User object. User serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User read_only_fields = ('is_active', 'is_staff', 'is_superuser',) exclude = ('password', ) extra_kwargs = {'password': {'write_only': True, 'min_length': 4}} In below serializer everything is fine: class AuditSerializer(serializers.ModelSerializer): def __init__(self, instance=None, **kwargs): if instance: setattr(self.Meta, 'depth', 10) else: setattr(self.Meta, 'depth', 0) super(AuditSerializer, self).__init__(instance, **kwargs) initiator = UserSerializer(read_only=True) class Meta: model = Audit fields = ['id', 'initiator'] read_only_fields = ['id', 'initiator'] depth = 0 But in the below that has relation to the previous model/serializer, I have the password issue: class AuditAttachmentSerializer(serializers.ModelSerializer): def __init__(self, instance=None, **kwargs): if instance: setattr(self.Meta, 'depth', 10) else: setattr(self.Meta, 'depth', 0) super(AuditAttachmentSerializer, self).__init__(instance, **kwargs) class Meta: model = AuditAttachment fields = ['id', 'audit'] read_only_fields = ['id'] depth = 0 -
Django, DateField with only month and year datetime?
In one of my djang apps I have the following model: class Budget_Vendite(models.Model): prodotto=models.ForeignKey() sottoprodotto=models.ForeignKey() prezzo_unitario=models.DecimalField() quantita=models.DecimalField() data=models.DateField() In my views I have created an algo that give me the montlhy total income extracting it from the Budget_vendite in the following manner: defaults = list(0 for m in range(12)) ricavi_bdgt = dict() for prodotto_id, year, month, totale in(Budget_Vendite.objects.values_list('prodotto__name', 'data__year', 'data__month') .annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('prezzo_unitario')), output_field=FloatField())).values_list('prodotto__name', 'data__year', 'data__month', 'totale') if prodotto_id not in ricavi_bdgt.keys(): ricavi_bdgt[prodotto_id]=list(defaults) index=month-1 ricavi_bdgt[prodotto_id][index]=totale All works perfectly, but now I have the necessity to give the possibility to choose only month and year in the dataField form and not also the day. How could I change my code to get this result? Ad example If i change my model in the following manner: class Budget_Vendite(models.Model): MY_CHOICES = ( ('jan', 'jan'), ('feb', 'feb'), ('mar', 'mar'), ('apr', 'apr'), ) ... ... month= models.CharField(choices=MY_CHOICES) year=models.IntegerField() How could I change the code of my views to obtain the same ricavi_bdgt result? -
Serializing Django objects to JSON
I am trying to serialize my question object and send it as a json object to my template but I keep getting an this error: Field 'id' expected a number but got '['. views.py from django.core import serializers def timer_view(request, order): condition = participant.condition.name field1 = condition[0] field2 = condition[1] filed3 = condition[2] == 'S' question_list = serializers.serialize("json", Question.objects.filter(filed1 = filed1, filed2 =filed2, filed3=True).order_by('order')) if order == 1: question = question_list[0] elif order == 2: question = question_list[1] elif order == 3: question = Question.objects.get(filed1 = 'N', filed2 ='E') data = {'question': question} json = JsonResponse(data) return json is it because of the queryset ? because I know that my queryset works fine but I couldn't find in the documentation how I can use the serialization to access the first item in the set. -
Django query model and return true if user in ManyToMany-field
I have a model like this: class FeedItem(models.Model) title = models.CharField(max_length=255) source = models.ForeignKey(Source, on_delete=models.CASCADE) read_by = models.ManyToManyField(User, blank=True, related_name='read') deleted_by = models.ManyToManyField(User, blank=True, related_name='deleted') I'm using rest framework to build an API. I would like to query the model above but not return the whole list of users in read_by and deleted_by but instead return True or False in those fields if the user that is Authenticated appears in those fields. Is there and way to do this in FeedItem.objects.filter( ... ). Below is my current API endpoint. class Posts(generics.ListAPIView): queryset = FeedItem.objects.all() serializer_class = ExampleModelSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_fields = ['title'] ordering_fields = ['title'] -
django all-auth case insensitive username
I'm using Django AllAuth and was making a simple profile page for the users of the app. That is reachable by typing in a user's username. # urls.py path('<str:username>/', UserDetail.as_view(), name='user-detail'), # views.py class UserDetail (DetailView): template_name = 'dashboard/user.html' model = User def get_object(self): return get_object_or_404(User, username=self.kwargs['username']) My thought is that it would work like twitter out of the gate. A user creates an account username like MyUsername which looks nice case-sensitive and is searchable case-insensitive. So if someone searched a user they could type in the username case-insensitive and it would always pull up the right user just with the nicer looking case-sensitive style. That's when I realized a user with username: MyUsername as supposed to myusername is actually 2 different users! Naive for me to think otherwise I suppose. Django AllAuth does have ACCOUNT_PRESERVE_USERNAME_CASING (=True) that I could implement but that would just make it so all usernames are lowercase while I was looking to just make usernames case-insensitive unique while still showing the nicer case-sensitive version. What would be the best approach to handle make the username case-insensitive unique but still show the case-sensitive format to the users?