Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to have value for which subprocess created in viewflow
I want to have my attribute in the subprocess for which that subprocess is created, but i don't know how exactly i can do that. -
How to do indexing in python dictionary using html template
def send_template(request): my_folders = Folders.objects.filter(parent=None).order_by('name') new_headers = {} for foldr in my_folders: en_count = FolderEntries.objects.filter(folder = foldr.id ).count() new_headers[foldr.id] = en_count return render(request, 'folders.html', 'new_headers':new_headers) new_headers contains data in such way:- {190: 1, 196: 0, 199: 0, 121: 0, 185: 1, 194: 1, 108: 3, 168: 4, 197: 0, 195: 0, 198: 0, 171: 1} Now i want to get new_headers in html template using indexing For example:- new_headers[190] How to do this..Anyone plz help i am sending this data to my html template:- {190: 1, 196: 0, 199: 0, 121: 0, 185: 1, 194: 1, 108: 3, 168: 4, 197: 0, 195: 0, 198: 0, 171: 1} Now i want to do indexing in this data. -
Hello! How I can get Json in new format like just text/value
`` [ { "name": "doc2", "directions": [ { "mar", "qwe" } ] }, { "name": "John", "directions": [ { "Surgery", "qwe" } ] } ] NOT like this [ { "name": "doc2", "directions": [ { "name": "mar" }, { "name": "qwe" } ] }, { "name": "John", "directions": [ { "name": "Surgery" }, { "name": "qwe" } ] } ] Models.py class Directions(models.Model): name = models.CharField(max_length=355) def __str__(self): return self.name class Doctors(models.Model): name = models.CharField(max_length=255) directions = models.ManyToManyField(Directions) def __str__(self): return self.name Serializer.py class DirectionsSerializer(serializers.ModelSerializer): class Meta: model = Directions fields = ('name',) class DoctorsSerializer(serializers.ModelSerializer): directions = DirectionsSerializer(many=True) class Meta: model = Doctors fields = ('name', 'directions') -
Django (and DRF) "ContentType matching query does not exist" on unmanaged model
I'm getting the error ContentType matching query does not exist. on an unmanaged (managed = False) model. I thought it would just pull from the database, so I'm not sure why it's checking the content types. My plan was to have a history app which pulls history data from tables created by the library django-simple-history. So I've got the app model (using the Poll app for example): class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published', auto_now_add=True) history = HistoricalRecords() Then I've got the historical version of that model (from the database created by django-simple-history): class HistoricalPoll(models.Model): id = models.BigIntegerField() question = models.CharField(max_length=200) pub_date = models.DateTimeField() history_id = models.AutoField(primary_key=True) history_date = models.DateTimeField() history_change_reason = models.CharField(max_length=100, blank=True, null=True) history_type = models.CharField(max_length=1) history_user = models.ForeignKey(settings.AUTH_USER_MODEL, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'polls_historicalpoll' And a serializer to for the history model: class HistoricalPollSerializer(serializers.ModelSerializer): class Meta: model = HistoricalPoll fields = '__all__' And a viewset: class HistoricalPollViewSet(viewsets.ModelViewSet): serializer_class = HistoricalPollSerializer permission_classes = [permissions.IsAuthenticated] queryset = HistoricalPoll.objects.all() And a URL: router.register(r"history", HistoricalPollViewSet) But when I access /history I only get an error: DoesNotExist at /history/ ContentType matching query does not exist. Why is it not simply just pulling data from the … -
Django, CORS "Access-Control-Allow-Origin" error
Can't figure out what's wrong with my Django DRF api endpoint. I'm getting a CORS error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200. Problem is, I followed every step online to fix this. I've installed 'django-cors-headers' Added corsheaders app to INSTALLED_APPS above rest_framework and the app that includes api endpoint. Added cors middleware to the top of the middleware list in settings.py Added 'CORS_ALLOWED_ORIGINS = ('http://localhost:3000' # React app) (Also tried with CORS_ORIGIN_ALLOW = True) Quadruple-checked that API POST request includes a trailing slash. Nothing seems to fix it. Am I forgetting something? Thanks for any help. This is my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'core.apps.CoreConfig', ] CORS_ALLOWED_ORIGINS = ( 'http://localhost:3000', # for localhost (REACT Default) ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.common.CommonMiddleware', ] Not sure how revelant it is, but If I send POST request from insomnia, it works fine, but from React, it doesn't, this is my react request just in case: const postSomeData = async () => { const res = await axios.post( "http://127.0.0.1:8000/api/", { promptQuery: "pls just work … -
How to populate checkboxes in a table with values from a Django model
My html table has a column that contains a checkbox. The user can check or uncheck it. The value (boolean) is stored in the Django model Subscriber under Subscriber.participates. All objects of Subscriber are imported into the HTML using a Django view (context = {'subscribers' : Subscriber.objects.all(),}). When loading the table, the checkboxes must be set to the correct value. To that purpose I have written a javascript function, which is invoked in the <input> element. However, the checkboxes all remain unchecked, though I have verified through /admin/ in Django that some of the values in the dbase are indeed "TRUE". firstName and lastName load without any problem into the table. What did I do wrong? <head> <meta charset="UTF-8"> <title>Participants</title> <script> function checkBox() { if({{ x.participates }}){ document.getElementById("checkbox").checked = true; } else { document.getElementById("checkbox").checked = false; } } </script> </head> <body> <table> {% for x in subcribers %} <tr> <form action="updateSuscribers/{{ x.id }}" method="post"> {% csrf_token %} <td>{{ x.firstName }}</td> <td>{{ x.lastName }}</td> <td> <input id="checkbox" type="checkbox" name="participates" onload="checkBox()"> </td> </form> </tr> {% endfor %} </table> </body> -
I refer django 1.11 version but I install and practice django 4.2.1 version so i got to many errors so please guide me
I refer django 1.11 version but I install and practice django 4.2.1 version so i got to many errors so please guide me every command shows an error sometimes its very hard to diagnosis -
disconnection does not happen
I want to set up the disconnection. I have a page, Page 1, that is only accessible to an authenticated user. When i disconnect I can still access page 1. And i have anothers questions, How does Django know to execute the logout_user function ? (I have the same question for the login but as it works I didn't ask myself the question ^^). And why do we indicate a redirection in the return when in the html we already indicate the redirection ? appIdentification/views.py from django.contrib.auth import authenticate, login, logout def logout_user(request): logout(request) messages.success(request, ("You Were Logged Out!")) return redirect('home') appIdentification/urls.py from django.urls import path from . import views urlpatterns = [ path('/login', views.login_user, name="login"), path('', views.logout_user, name="logout"), ] mainApp/template/mainApp/page1.html <body> <h1> PAGE 1 </h1> {% if user.is_authenticated %} <a href="{% url 'login' %}"> Logout </a> {% endif %} </body> mainApp/views.py @login_required def page1(request): return render(request, 'mainApp/p1.html', {}) mainApp/urls.py from django.urls import path, include from . import views path('mainApp', include('django.contrib.auth.urls')), path('mainApp', include('appIdentification.urls')), path('home', views.home, name="home"), path('p1', views.page1, name="p1"), -
Django Rest Framework: upload image to a particular existing model's object
Hey I am trying to upload an image using Rest API[via Postman] to an object which already exists, and has all its field populated except for the image. I am using PUT method, to first get the object I want to upload the image to then trying to pass it through the serializer. The images are to be uploaded to my S3 bucket. The code for my views.py: @api_view(['PUT']) @permission_classes([IsAuthenticated]) def putproof(request): app=MasterTaskHolder.objects.filter(title=request.data['title'],user=request.user) serializer=ImageUploadSerializer(app,data=request.data,partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response("Posted") My serializer: class ImageUploadSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MasterTaskHolder fields = ( 'title','image' ) My model: class MasterTaskHolder(models.Model): status_code = [ ('C', 'Completed'), ('P', 'Pending'), ] title = models.CharField(max_length=50) point = models.IntegerField() category = models.CharField(max_length=50, null=True, blank=True) status = models.CharField(max_length=2, choices=status_code, default='P') user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True, upload_to="imageproof/") def __str__(self): return (f'{self.user} - '+(f'{self.title}')) I am really new to Django and DRF, any help would be appreciated. Thank you. -
Multiple try except in a serializer Django
I have a Warehouse model like the following: class ShelfBin(models.Model): bin_id = models.IntegerField(default=0) bin_name = models.CharField(max_length=50, default=0) class UnitShelf(models.Model): shelf_id = models.IntegerField(default=0) shelf_name = models.CharField(max_length=50, default=0) bin = models.ManyToManyField(ShelfBin, blank=True) class AisleUnit(models.Model): unit_id = models.IntegerField(default=0) unit_name = models.CharField(max_length=50, default=0) shelf = models.ManyToManyField(UnitShelf, blank=True) class ZoneAisle(models.Model): aisle_id = models.IntegerField(default=0) aisle_name = models.CharField(max_length=50, default=0) unit = models.ManyToManyField(AisleUnit, blank=True) class WarehouseZone(models.Model): zone_id = models.IntegerField(default=0) zone_name = models.CharField(max_length=50, default=0) aisle = models.ManyToManyField(ZoneAisle, blank=True) class Warehouse(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=250, default=0) address = models.CharField(max_length=500, default=0) zones = models.ManyToManyField(WarehouseZone, blank=True) for this I have created a serializer like the following: class WarehouseSerializer(serializers.ModelSerializer): zones = WarehouseZonesSerializer(many=True) class Meta: model = Warehouse fields = "__all__" def create(self, validated_data): print("validated data warehouse", validated_data) zone_objects = validated_data.pop('zones', None) instance = Warehouse.objects.create(**validated_data) for item in zone_objects: aisle_objects = item.pop('aisle') wz_obj = WarehouseZone.objects.create(**item) for data in aisle_objects: unit_objects = data.pop('unit') za_obj = ZoneAisle.objects.create(**data) for u_data in unit_objects: shelf_objects = u_data.pop('shelf') au_obj = AisleUnit.objects.create(**u_data) for s_data in shelf_objects: bin_objects = s_data.pop('bin') us_obj = UnitShelf.objects.create(**s_data) for b_data in bin_objects: b_obj = ShelfBin.objects.create(**b_data) us_obj.bin.add(b_obj) au_obj.shelf.add(us_obj) za_obj.unit.add(au_obj) wz_obj.aisle.add(za_obj) instance.zones.add(wz_obj) return instance Now the problem is that sometimes warehouse can have zone, aisle, units, etc(all 5 sub-levels) but sometimes it can only be 1,2 … -
How does multiple user types logging in & out work in a live environment? [Django]
I have a web app that has two different user types, Nurses and Doctors, and they can both log in and out. I opened two tabs and logged in as a Nurse in one tab and as a Doctor in the other. However, when I log out of either one of those tabs, the other will be automatically logged out as well. I have read this link How can made multiple user login at same time in same browser in django project and understand why this happens. I know that I can work around it by logging in from different web browsers and by using Incognito mode. However, how do I code it such that in a live environment, users can actually logout without logging other users out? -
Increase django fixed value
In my Django project, there is a fixed number in one of the html input fields and I want this number to increase every time the form is opened. But since it will increase every time the form is opened, it is necessary to get the value of the last data from the database in that field. How can I apply something like this? -
How to solve zsh: illegal hardware instruction python manage.py makemigrations on mac, what is this error
python manage.py makemigrations shows some error after the installation of pip install deepface Error : zsh: illegal hardware instruction python manage.py makemigrations System info :OS - Ventura 13.O, Chip- M1 What is this issue, why this happen and how to solve it -
Django : "break" a class based view with intermediate "return render" won't work
I use a CB ListView for displaying objects. I want to add a session variable based on another models' PK. views.py class ProduitListView(LoginRequiredMixin, ListView): model = Produit context_object_name = "produits" paginate_by = 10 template_name = 'products/produits.html' ordering = ['-mageid', ] def get_context_data(self, *args, **kwargs): context = super(ProduitListView, self).get_context_data( *args, **kwargs) # used for incoming products (sourcing cf URLS) supplier_pk = self.kwargs.get('pk', None) if supplier_pk: set_incoming_supplier(self.request, supplier_pk) context['avail_warehouses'] = Warehouse.objects.all() context['js_warehouses'] = serialize( 'json', Warehouse.objects.all(), fields=('code', 'id', )) context['title'] = 'Produits' return context set_incoming_supplier (in another APP) @login_required def set_incoming_supplier(request, pk): supplier = Supplier.objects.filter(pk=pk).first() supp = SupplierSerializer(instance=supplier).data rs = request.session if 'income' in rs: if 'cur_supplier' in rs['income']: prev_supplier = rs['income']['cur_supplier'] if supp != prev_supplier: return render(request, 'sourcing/alert_supplier_change.html', {'prev_supplier': prev_supplier, 'cur_supplier': rs['income']['cur_supplier']}) rs['income'] = {'cur_supplier': supp} I thought the return render(request, 'sourcing/alert_supplier_change... could "break" my ListView and render my alert page but it doesn't. ListView seems to continue and finally renders my ProduitListView page. Why doesn't this work ? -
Reverse for 'user-profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<pk>[^/]+)/$']
I'm watching a course, and after the lecturer used exclude = ['host'] in Meta class I got this error, which highlights this line in template: <a href="{% url 'user-profile' room.host.id %}">@{{room.host.username}}</a> view: def userProfile(request, pk): user = User.objects.get(id=pk) rooms = user.room_set.all() room_messages = user.message_set.all() topics = Topic.objects.all() context = {'user': user, 'rooms': rooms, 'room_messages': room_messages, 'topics': topics, 'pk': pk} return render(request, 'base/profile.html', context) urls: path('profile/<str:pk>/', views.userProfile, name='user-profile'), I tried to remove exclude = ['host'], but it did not help. Then I tried to add 'pk': pk to context in userProfile, but it also did not help. I will be grateful for help. -
How to merge two XML files with different child elements into single XML file
The below given are my sample xml files. (XML 1) ` <?xml version="1.0" encoding="utf-8"?> <objects> <object> <record> <organization>1010</organization> <code>000010001</code> <name>A &amp; SOLICITORS</name> <address_1>NORTH</address_1> <address_2/> <city/> <postcode>NUHMAN 1</postcode> <state/> <country>IE</country> <vat_number/> <telephone_number>054456849</telephone_number> <fax_number>01 64964659</fax_number> <currency>USD</currency> <start_date>1990-01-01</start_date> <end_date>2999-12-31</end_date> <status>ACTIVE</status> </record> <record> <organization>1010</organization> <code>0000100004</code> <name>ACCUTRON LTD.</name> <address_1>RAZIK PARK</address_1> <address_2/> <city>LIME</city> <postcode>V94654X7</postcode> <state/> <country>IE</country> <vat_number>IE6566750H</vat_number> <telephone_number>353 -61 - 54614</telephone_number> <fax_number/> <currency>USD</currency> <start_date>1990-01-01</start_date> <end_date>2999-12-31</end_date> <status>ACTIVE</status> </record> ` (XML 2) ` <?xml version="1.0" encoding="utf-8"?> <objects> <record> <po_number>45670369</po_number> <po_currency>USD</po_currency> <po_organization>1010</po_organization> <code>0000156001</code> <name>SOFTWAREONE INC</name> <capture_row_type>NONE</capture_row_type> <source_system>SAP</source_system> </record> <record> <po_number>45670372</po_number> <po_currency>USD</po_currency> <po_organization>1010</po_organization> <code>0000156001</code> <name>SOFTWAREONE INC</name> <capture_row_type>NONE</capture_row_type> <source_system>SAP</source_system> </record> ` As we can see some of the fields are similar here. I'm trying to merge these two into one xml in a way that inside the record element each of the data in the two xml's must be there. Both data in the two files are not in order. I want the data with the matching 'code' to be grouped together in the new XML file. Both files have different number of fields and code is on of the common field and I want it to be the common factor for which the data to be grouped together. -
Testing HTML and CSS for Email
I am building a Django application that needs to send out some Emails using HTML templates. The email templates use images as well as some variables from django context. Right now, every time I make an update to the inline css or html I send myself a new Email to check how the email looks in different Browsers/Applications. Is there a way I can preview the Email without having to send it to myself? Just previewing the Email in the browser doesn't work as the CSS is always "interpreted" differently when I send it in an actual Email. <table cellpadding="0" bgcolor="#fff" border="0" style="width: 900px;"> <a href="mailto:kontakt@schmerz-experts.de"> <img style="width: 900px" src="cid:top.jpg" /> </a> </table> <table cellpadding="12" bgcolor="#fff" border="0" style="width: 900px; margin-left: 0em; margin-bottom: 15px;"> <p style="font-weight: bold; font-size: 24px; text-align: center;">VIELEN DANK.</p> <p>Sehr geehrte Patientin, Sehr geehrter Patient,</p> <p>Ihre Registrierung ist nun abgeschlossen. In Kürze erhalten Sie Ihren ersten Newsletter. </p> <p>Sollten Sie diesen innerhalb von 24 Stunden nicht erhalten, schauen Sie bitte auch in Ihrem Spam Ordner nach. </p> <p>Sollten Sie Fragen oder Anmerkungen haben, zögern Sie nicht uns zu kontaktieren.</p> <table role="presentation" cellspacing="0" cellpadding="0" style="background-color: rgb(1,41,101)"> <tr> <td style="width: 350px; padding: 16px 48px; background-color: rgb(1,41,101); text-align: center;font-weight: 700;"> <a … -
Django Auto Increment Field Non Pk
How to make the model so that each order that a costumer submit is gonna be auto incremented (ie. order_number) without messing with the order obj primary_key? Models.py class Costumer(models.Model): costumer_name = models.CharField(max_length=100) costumerID = models.CharField(max_length=100) class Order(models.Model): costumer = models.ForeignKey(Costumer, related_name='order', on_delete=models.CASCADE) order_name = models.CharField(max_length=100) order_number = models.IntegerField(default=0) JSON Example [ { "id": 1, "order": [ { "id": 1, "order_name": "fruit", "order_number": 1, "costumer": 1 }, { "id": 2, "order_name": "chair", "order_number": 2, "costumer": 1 }, { "id": 3, "order_name": "pc", "order_number": 3, "costumer": 1 } ], "costumer_name": "john doe", "costumerID": "81498" }, { "id": 2, "order": [ { "id": 4, "order_name": "phone", "order_number": 1, "costumer": 2 }, { "id": 5, "order_name": "car", "order_number": 2, "costumer": 2 } ], "costumer_name": "jane doe", "costumerID": "81499" } ] If i need to submit more file such as seriallizers.py etc please let me know. Thank you in advance. -
(React Native and Django) TypeError: Network request failed
I'm developing a mobile app with the concept of using react-native as front end and Django as back-end. I'm actually following this series of tutorials: Javascript Fetch - Communicating between a ReactNative App and Django REST API but when I got to the part where I have to use a fetch method I am getting a TypeError: Network request failed. Here is a snippet of my code: const [ domain, setDomain ] = useState("http://10.0.2.2:8000") function initAppSettings(){ console.log(domain) fetch(`$(domain)/api/v1.0/app/settings`, { method: 'GET', }) .then (result => { if (result.ok) { return result.json() } else { throw result.json() } }) .then (JSON => { console.log(JSON) }) .catch (error => { console.log(error) }) } useEffect(() => { initAppSettings() }, []) I have already tried editing the AndroidManifest.xml by adding android:usesCleartextTraffic="true". I also tried using my own ipv4 address in my Django runserver but still failed to access it. I have the same question as this but the answer here do not solve my issue. -
Redirect all page not found to home page
I would like to redirect all 404 pages to a home page. I try this but it don't work app/views.py from django.http import HttpResponse from django.shortcuts import render, redirect def home(request): return HttpResponse('<h1> HOME </h1>') def redirectPNF(request, exception): return redirect('home') app/urls.py from . import views urlpatterns = [ path('home', views.home, name="home"), ] app/settings.py handler404 = 'app.views.redirectPNF' ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] DEBUG = False -
Combine 2 Query sets and display Django
Im new to django I am trying to combing two query sets for example, I have different farms. and in those farms they have respective blocks. I would like to output the farm as a heading and list the blocks of each farm underneath it. Example: Farm 1 Block 1 Block 2 Blaock 3 Farm 2 Block 1 Block 2 Block 3 What I currently in have in views: def irrigation(request): obj3 = Farms.objects.all().values("id", "farm_name") obj2 = Blocks.objects.all() obj = obj2 | obj3 context = {"object": obj} return render(request, "irrigation.html", context) in html: {% for farms in object %} <tr> <td>{{ farms.farm_name }} {{ farms.id }}</td> <td><a href="/ifarm/{{ farms.id }}"> Edit </a> </tr> {% endfor %} Please help! -
Django==3.2.15 celery v5.1.2 and jango-celery-beat==2.2.1 enable task and nothing heppens
Ok all day trying to figure out what is wrong. mysite.settings """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'your_secret_key_here' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'correlator.apps.CorrelatorConfig', 'reviews.apps.ReviewsConfig', 'parameters.apps.ParametersConfig', 'trex', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', #'django_filters', 'rest_framework_swagger', # optional, creates browsable API docs 'easy_thumbnails', # Required by `content_image` plugin 'celery', 'django_celery_beat', 'iris', 'django_celery_results', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'mysite.mycsrfmiddleware.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'mysite.mymiddleware.CorrelatorControllerMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'M@ster449644p', 'HOST': 'localhost', 'PORT': '5432', } … -
Django 4.1.2 unique=true doesn't create index?
Email = models.EmailField(max_length = 300, unique = True) Doesn't create index on sqlite 3. Documentation says, unique = True, will create a index. But checking the indexes on sqlite. It is not created. https://docs.djangoproject.com/en/4.1/ref/models/fields/ -
Django cannot find data that I'm sure exists in the database
basically my app receives a serial number through an AJAX POST request from the front end, and it has to find the product who's serial number matches the given serial number and return it's details. here is my view , I have confirmed that the data is being received correctly and that a product with the exact serial number exists in the database but i still get a 404 not found response. i am using Mariadb as my app's database. here is my code: `` ``` from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from products.models import Products from django.shortcuts import get_object_or_404 `` # Create your views here. @csrf_exempt def products(request): if request.method == 'POST': query = request.body.decode('utf-8') products = Products.objects.all() for i in products: print(f"item{i} : {i.serial_number}") print(f"request : {query}") context = { 'products' : products, } get_object_or_404(products,serial_number = query) return render(request,"products/products.html",context) else: return render(request,"products/products.html") ``` here is the terminal output: ` `[31/Oct/2022 10:29:48] "GET / HTTP/1.1" 200 2459 itemProducts object (1) : https://blog.minhazav.dev/research/html5-qrcode.html itemProducts object (3) : 123 itemProducts object (4) : itemProducts object (5) : http://shooka.com request : "http://shooka.com" Not Found: /` `` and here is my models code: ` ``` `` `from … -
How can I modify the keys in Django Auth ADFS claims mapping?
I am using django-auth-adfs to authenticate Azure AD users on my django backend, this works fine for users within my organization. For users in other organizations however, there are certain keys defined in my CLAIMS_MAPPING that aren't returned in the JWT token. I have tried different suggestions I found to get those keys to be present but non have worked for me, so I decided to just make use of the keys present in both tokens (tokens from my organization and tokens from outside my organization). For example, I changed 'USERNAME_CLAIM': 'upn' to 'USERNAME_CLAIM': 'email' because the upn key is not present in both tokens but the email key is and they pretty much return the same values. My problem right now is with the first_name and last_name keys. With tokens from my organization, this mapping works fine: 'CLAIM_MAPPING': {'first_name': 'given_name', 'last_name': 'family_name', 'email': 'upn'}, However the key family_name does not exist in tokens from outside my organization. The name key exists in both tokens, so I thought to .split(" ") the name key and get the parts but I am not sure how to go about this since the mapping is to a string representing a key in the …