Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validator errors
I'm running my code through validator and it's coming back with four errors which I don't know how to fix as the code has been imported from django forms. Does anyone know how to fix these? <div class="form-group"> <form method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="0AxrgENq77DUAfiu7a1XIsQ2gveB9bBBO96oqSIrlW5OQxoV8EMCrmIIbAn31wa4"> <p><label for="id_username">Username:</label> <input type="text" name="username" maxlength="150" autofocus class="form-control" required id="id_username"> <span class="helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span></p> <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" class="form-control" maxlength="100" required id="id_first_name"></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" class="form-control" maxlength="100" required id="id_last_name"></p> <p><label for="id_email">Email:</label> <input type="email" name="email" required id="id_email"></p> <p><label for="id_password1">Password:</label> <input type="password" name="password1" autocomplete="new-password" class="form-control" required id="id_password1"> <span class="helptext"> <ul> <li>Your password can’t be too similar to your other personal information.</li> <li>Your password must contain at least 8 characters.</li> <li>Your password can’t be a commonly used password.</li> <li>Your password can’t be entirely numeric.</li> </ul> </span></p> <p><label for="id_password2">Password confirmation:</label> <input type="password" name="password2" autocomplete="new-password" class="form-control" required id="id_password2"> <span class="helptext">Enter the same password as before, for verification.</span></p> <div class="d-grid"> <button class="btn btn-dark ">Register</button> </div> </form> </div> -
Is my DRF create function losing data before saving?
I have the following DRF viewset: class RecordViewSet(ModelViewSet): queryset = Record.objects.all() serializer_class = RecordSerializer filterset_fields = ['task', 'workday'] def get_workday(self, request): date = get_date_from_calendar_string(request.data['date']) obj, _ = Workday.objects.get_or_create(user=request.user, date=date) return obj.id def create(self, request): request.data['workday'] = self.get_workday(request) print(request.data) return super().create(request) The create() method is failing on a not-null constraint: django.db.utils.IntegrityError: null value in column "task_id" violates not-null constraint DETAIL: Failing row contains (159, Added via task panel., 0, 0, 0, null, t, f, null, 98). However, the print statement in create() shows that the data present in the submission: {'minutes_planned': 5, 'description': 'Added via task panel.', 'minutes_worked': 5, 'task': 148, 'workday': 98} I am not seeing the pk for task (148) in the error statement for some reason, indicating to me that it is getting dropped somewhere. I am not using any signals, or overriding save() in the model. What else could be causing this problem? I've just started using DRF, so it might be something obvious. ===== This is the model: class Record(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='records') workday = models.ForeignKey(Workday, on_delete=models.CASCADE, related_name='records') description = models.CharField(max_length=128, blank=True, null=True) minutes_planned = models.IntegerField(default=0) minutes_worked = models.IntegerField(default=0) minutes_worked_store = models.IntegerField(default=0) user_generated = models.BooleanField(default=True) completed = models.BooleanField(default=False) and the serializer: class RecordSerializer(serializers.ModelSerializer): task … -
error django.db.utils.IntegrityError: NOT NULL constraint failed
I am really stuck here. I went back and edited some models that I made a while ago and now I can't get anything to migrate without getting "django.db.utils.IntegrityError: NOT NULL constraint failed: new__accounts_instrument.room_id" The model that seems to be causing problems: ...\acounts\models.py class Instrument(models.Model): LEVEL = ( ('HS', 'HS'), ('MS', 'MS'), ) event = models.ForeignKey(Event, blank=False, null=True, on_delete=models.PROTECT) name = models.CharField(max_length=200, blank=False, null=True) abbreviation = models.CharField(max_length=10, blank=False, null=True) level = models.CharField(max_length=200, blank=False, null=True, choices=LEVEL) room = models.ForeignKey(AuditionRoom, default=None, on_delete=models.PROTECT) I've tried deleting the migration history but that throws other codes so I "undo" it. I've tried dropping the instrument table but that didn't seem to matter. I'm very grateful for any pointers as I am pretty frustrated at the moment. Please let me know if you need more code snippets... THANK YOU -
Reference a django variable in html to perform a function
I am trying to to output a function on the string that a user selects in a dropdown form. I have a custom template tag that works when you feed it the right variable, but am not sure how to pass on the selected item to it. <select> {% for drink in drinks %} <option id="dropdown" value="{{drink.drink_name}}">{{drink.drink_name}}</option> {% endfor %} </select> <li>{{drink.drink_name|drink_joins}}</li> I know the list gives me an error because drink.drinkname is out of the loop but this is the logic I'm going for. Also fetching the selected value with JavaScript (document.getElementById("dropdown").value) only gives me the first item from the dropdown so that is a problem too. Any remedies? -
Django container is rejecting nginx containers traffic
I have a pretty simple setup, a single django container in a pod and an nginx container in another pod. I'm using nginx because I want to move the django app into production and I need an actual web server like nginx to put an ssl cert on the site. The problem is that it seems like django is rejecting all of the traffic from the nginx container as the web browser gets 502 bad gateway error when browsing to localhost and the nginx logs show: *3 recv() failed (104: Connection reset by peer) while reading response header from upstream I already have 127.0.0.1 and localhost added to the allowed hosts in django settings. Below is the kubernetes file with the nginx config that I'm loading through a config map. I've tried about 30 different nginx.conf configurations, this is just the most recent and simplest one. apiVersion: v1 kind: Service metadata: name: my-nginx-svc labels: app: nginx spec: type: LoadBalancer ports: - port: 80 selector: app: nginx --- apiVersion: apps/v1 kind: Deployment metadata: name: my-nginx labels: app: nginx spec: replicas: 1 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:latest ports: - containerPort: 80 … -
How to get difference between two annotate fields in django orm
The problem is that with this approach, annotate ignores equal amounts, and if you remove distinct=True, then there will be duplicate objects and the difference will not be correct. In simple words, I want to get the balance of the account by getting the difference between the amount in cash and the amount on receipts for this personal account queryset = PersonalAccount.objects.select_related( 'apartment', 'apartment__house', 'apartment__section', 'apartment__owner', ).annotate( balance= Greatest(Sum('cash_account__sum', filter=Q(cash_account__status=True), distinct=True), Decimal(0)) - Greatest(Sum('receipt_account__sum', filter=Q(receipt_account__status=True), distinct=True), Decimal(0)) ).order_by('-id') class PersonalAccount(models.Model): objects = None class AccountStatus(models.TextChoices): ACTIVE = 'active', _("Активен") INACTIVE = 'inactive', _("Неактивен") number = models.CharField(max_length=11, unique=True) status = models.CharField(max_length=8, choices=AccountStatus.choices, default=AccountStatus.ACTIVE) apartment = models.OneToOneField('Apartment', null=True, blank=True, on_delete=models.SET_NULL, related_name='account_apartment') class CashBox(models.Model): objects = None number = models.CharField(max_length=64, unique=True) date = models.DateField(default=datetime.date.today) status = models.BooleanField(default=True) type = models.BooleanField(default=True) sum = models.DecimalField(max_digits=10, decimal_places=2) comment = models.TextField(blank=True) payment_items = models.ForeignKey('PaymentItems', blank=True, null=True, on_delete=models.SET_NULL) owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, related_name='owner') manager = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='manager') personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True, on_delete=models.SET_NULL, related_name='cash_account') receipt = models.ForeignKey('Receipt', blank=True, null=True, on_delete=models.SET_NULL) class Receipt(models.Model): objects = None class PayStatus(models.TextChoices): PAID = 'paid', _("Оплачена") PARTIALLY_PAID = 'partially_paid', _("Частично оплачена") NOT_PAID = 'not_paid', _("Не оплачена") number = models.CharField(max_length=64, unique=True) date = models.DateField(default=datetime.date.today) date_start = models.DateField(default=datetime.date.today) date_end = models.DateField(default=datetime.date.today) … -
Posting Date Data to Django Model
I was wondering if any of you guys here knew how to fix this error, I have been dealing with it for quite a few hours, it has to do with posting json date (a date from a html date picker) to a backend model using the django web framework. Please let me know if my question is unclear. ViewOrders.html <form id="form"> <label for="start">Drop Off Date Selector:</label> <br> <input type="date" id="dropOffDate" name="drop_Off_Date" min="2022-01-01" max="3000-12-31"> <button type="submit" value="Continue" class="btn btn-outline-danger" id="submit-drop-off-date" >Submit Drop Off Date</button> </form> <script type="text/javascript"> var form = document.getElementById('form') form.addEventListener('submit', function(e){ e.preventDefault() submitDropOffData() console.log("Drop Off Date submitted...") }) function submitDropOffData() { var dropOffDateInformation = { 'dropOffDate':null, } dropOffDateInformation.dropOffDate = form.drop_Off_Date.value var url = "/process_drop_off_date/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'drop-off-date':dropOffDateInformation}), }) .then((response) => response.json()) .then((data) => { console.log('Drop off date has been submitted...') alert('Drop off date submitted'); window.location.href = "{% url 'home' %}" }) } </script> Views.py def processDropOffDate(request): data = json.loads(request.body) DropOffDate.objects.create( DropOffDate=data['drop-off-date']['dropOffDate'], ) return JsonResponse('Drop off date submitted...', safe=False) Models.py class DropOffDate(models.Model): dropOffDate = models.CharField(max_length=150, null=True) def __str__(self): return str(self.dropOffDate) Errors -
A good way to authenticate a javascript frontend in django-rest-framework
What's an excellent method to implement token-based httpOnly cookie authentication for my drf API for a javascript frontend I looked into django-rest-knox for token-based authentication but its built-in LoginView required the user to be logged in already. Why is that?. I want a good method to authenticate the user from the javascript frontend. Thanks! -
How to migrate from sqlite to postgres using a local sqlite database in Django?
I have a 'xxxxx.db' sqlite3 database and I want to move the data to PostgreSQL. I have done some research and seen a couple of options but none of them worked (PGloader etc.). What are some other options? I am using Windows but solutions in Linux are welcome as well. I have tried doing it in PowerShell(via Jupyter Notebook): !pip install virtualenvwrapper-win !mkvirtualenv [name] !pip install django !django-admin startproject [name] cd [name] !python manage.py startapp app !python manage.py inspectdb !python manage.py inspectdb > models.py !python manage.py migrate !manage.py runserver !python manage.py dumpdata > data.json But the dump does not include the data from my db, I have also changed the settings to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': absolute_path_to_db/db, } } Thanks in advance! -
How to make a drf endpoint that returns model fields with description and choices?
There are rest api endpoints being built for questionnaires, that accept only POST requests. The frontend should dynamically display the questionnaires based on their model fields, their descriptions, and possible choices. How to make such django rest framework endpoint, which returns model fields, their description and choices as json? It cannot be a hard coded json so when a model field description changes, it is reflected in the API response. -
Django Python besides uploading text, i would like to be able to upload image and videos
I work on a Social Media Website. I get the Base code from an Open Source Project on GitHub. On my Website you can only upload Text, and link some images, but these are not very user friendly. I would love to be able to upload images and videos besides the Text. When I watch Tutorials on YouTube, it's always very hard to implement that code to mine. Is there a way that someone could help me? The code of post_form.html, post_detail.html, forms.py, views.py, models.py, urls.py, admin.py, settings.py are under this text: post_form.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block title %}Post{% endblock %} {% block content %} <div class="m-auto w-100 container"> <div class="content-section"> <form action="" method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Post</legend> {{form.media}} {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-info" type="submit">Post</button> <a class="btn btn-danger" href="{% url 'blog-home' %}">Cancel</a> </div> </form> </div> </div> <!-- Modal --> <div class="modal fade" id="modalCrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Crop the photo</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" style="max-width: 100%; overflow:auto"> <img style="max-height:100%; max-width: 100%" src="" id="image"> </div> <div class="modal-footer"> <div class="float-left"> <button type="button" class="btn btn-primary … -
Input abc.png of type: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> is not supported
Unable to save image two times in django Im trying to save image through form in one model and add in another model. But at new_account.save() I get the above error. image_file = request.FILES.get('profile_image') ... ... instance.save() new_account = Account.objects.get(id=classroom_profile.user.id) new_account.profile_image.delete() new_account.profile_image = image_file new_account.save() -
`TransactionManagementError` when callinfg another model save function inside my custom save method for a model
While performing a save operation from the admin site the model when saving is raising a TransactionManagementError, The model has a custom save method in which there is another save function called for another model so just put it with the transaction.atomic(): solves the issue but atomic might affect performance or cause deadlock due to lock. Is there any other way I can override the admin save or only do this when the save call is coming from admin? -
What could be causing "connection refused" error when uploading file via form (post request) to Django app deployed on Heroku?
I have this working on google cloud but recently deployed my django app to Heroku. Everything is working fine except file upload here is debug log. I tried heroku run ls -l to create a files directory and confirmed /files directory it exists on server but I'm not sure why I get connection refused. Debug log is below it should just upload file submitted to /files directory so I'm not sure why it's refusing connection. OperationalError at /upload/ [Errno 111] Connection refused Request Method: POST Request URL: <redacted> Django Version: 4.0.5 Exception Type: OperationalError Exception Value: [Errno 111] Connection refused Exception Location: /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 450, in _reraise_as_library_errors Python Executable: /app/.heroku/python/bin/python Python Version: 3.10.5 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python310.zip', '/app/.heroku/python/lib/python3.10', '/app/.heroku/python/lib/python3.10/lib-dynload', '/app/.heroku/python/lib/python3.10/site-packages'] Server time: Mon, 11 Jul 2022 17:37:37 +0000 Traceback Switch to copy-and-paste view /app/.heroku/python/lib/python3.10/site-packages/kombu/utils/functional.py, line 30, in __call__ return self.__value__ … Local vars During handling of the above exception ('ChannelPromise' object has no attribute '__value__'), another exception occurred: /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 446, in _reraise_as_library_errors yield … Local vars /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 433, in _ensure_connection return retry_over_time( … Local vars /app/.heroku/python/lib/python3.10/site-packages/kombu/utils/functional.py, line 312, in retry_over_time return fun(*args, **kwargs) … Local vars /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 877, in _connection_factory self._connection = self._establish_connection() … Local … -
Django with ngrok. CSRF verification failed. Request aborted. Origin checking failed
I have a simple django project with user login/register capabilities that I wanted to view on mobile, the only way I know how to do this besides actually deploying the website is to use ngrok. So I ran ngrok http 8000 and added ALLOWED_HOSTS = ['*'] to my settings.py file. Went over to the url provided by ngrok, tried to login as one of the users I had created while running the project on localhost and upon submitting the form got the following error: CSRF verification failed. Request aborted. Origin checking failed - https://myurl.ngrok.io does not match any trusted origins. Not really sure what to do here, does django user auth not work with ngrok or do I just have to add something to my settings file to make this a 'trusted origin'? Thanks for any help. -
Retrieving Date Value and Assigning Date to Django Backend
I am trying to figure out a way to assign a date that I retrieve from the standard html date picker and then assign it to a backend model after a button of type 'submit' is clicked. I wrote some javascript but the value keeps being retrieved as NULL. I am relatively new to javascript so please bare with me. Attached are all the files that I have been working on, along with screenshots of the error. Please let me know if there is anything else you may need from me to help me with my question! vieworders.html <div class="row mb-4"> <label for="start">Drop Off Date Selector:</label> <br> <input type="date" id="dropOffDate" min="2022-01-01" max="3000-12-31"> <button type="submit" value="Continue" class="btn btn-outline-danger" id="submit-drop-off-date">Submit Drop Off Date</button> </div> <script type="text/javascript"> var date = document.getElementById("date"); date.addEventListener('submit', function(e){ e.preventDefault() submitDropOffData() console.log("Drop off data submitted...") }) function submitDropOffData() { var dropOffDateInformation = { 'dropOffDate':null, } dropoffDate.date = date.value var url = "/process_drop_off_date/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'dropoffDate':dropOffDateInformation}), }) .then((response) => response.json()) .then((data) => { console.log('Drop off date has been submitted...') alert('Drop off date submitted'); window.location.href = "{% url 'home' %}" }) } </script> views.py def processDropOffDate(request): data = json.loads(request.body) DropOffDate.objects.create( DropOffDate=data['dropoffDate']['date'], ) return JsonResponse('Drop off date … -
DRF multiple ManyToOne relations serializer
sorry my english is not good. Get request book_id(pk) How to I serialize ManyToOne fields using BookSerializer to retrieve something class Book(TimeStampedModel): name = models.CharField(max_length=25, null=False) owner = models.ForeignKey(User, on_delete=models.DO_NOTHING,unique=True) ... class Meta: db_table = 'books' class BookMember(TimeStampedModel): user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=False) book = models.ForeignKey(Book, on_delete=models.CASCADE, null=False) class Meta: db_table = 'book_member' class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=20, unique=True) email = models.EmailField(verbose_name=_('email')) ... class Meta: db_table = 'user' class BookSerializer(serializers.ModelSerializer): user = UserDetailSerializer(read_only=True, many=True, required=False) owner = UserDetailSerializer(read_only=True, many=True, required=False) class Meta: model = Book fields = '__all__' I need to book retrieve class BookViewSet(ModelViewSet): permission_classes = [AllowAny] queryset = Book.objects.all() serializer_class = BookSerializer renderer_classes = [JSONRenderer] def retrieve(self, request, *args, **kwargs): instance = get_object_or_404(self.queryset, many=True) serializer = self.get_serializer(instance) return serializer.data -
pytest: how to mock database query at module
I have a module with different functions inside and several global variables defined at the beginning of the module. module.py MIN_PLACE = 7 START_DAY = 4 func1(): pass func2(): pass func3(): pass .... tests.py @pytest.mark.django_db test_func1(): #logic ..... Tests have been written for this module (several dozen) and everything works. But I needed to make the variables dynamic, with the ability to change them from the django admin panel and store them in the database. MIN_PLACE: int = int(RedshiftQueryParam.objects.get(name=RedshiftQuery.MIN_PLACE).value) START_DAY: int = int(RedshiftQueryParam.objects.get(name=RedshiftQuery.START_DATE).value) And after that, all the tests fell down with an error message E RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. In order to use the database reference to test the function, the decorator @pytest.mark.django_db is used But what about when a call to the database occurs in the body of a module rather than in a specific function? Every time the pytest context enters the module, it tries to connect to the database. How can I fix this? Can this be done globally in one place so as not to have to fix all the test files ? -
Can I use redirect or render as a way to "refresh" the current web page I'm on in django?
I'm wondering if I can use the redirect()/render() function and point to the default page (http://127.0.0.1:8000) as a way to essentially refresh the page I'm on. I feel like it'd work but I'm not sure what to put in the parameters of the function, I've seen people say redirect("/path/") but that gives me an error the second I click my submission button. as well as if I need to change anything elsewhere within the framework. I also know you can return multiple items in python, but can I return the original item as well as a call to redirect()/render()? Here is my views.py file: from django.shortcuts import render from django.shortcuts import redirect from django.urls import reverse from django.views.generic.edit import FormView from django.views.decorators.csrf import csrf_exempt from .forms import FileFieldForm from django.http import HttpResponse from .perform_conversion import FileConverter import zipfile import io def FileFieldFormView(request, *args, **kwargs): form = FileFieldForm(request.POST) files = request.FILES.getlist('file_field') if request.method == 'POST': print(request) form = FileFieldForm(request.POST, request.FILES) if form.is_valid(): zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, "w", False) as zip_file: for f in files: fileconverter = FileConverter(f.name) fileconverter.run(f.file) for img_name, img in fileconverter.output.items(): data = io.BytesIO(img) zip_file.writestr(img_name, data.getvalue()) # Set the return value of the HttpResponse response = HttpResponse(zip_buffer.getvalue(), content_type='application/octet-stream') … -
Dynamically joining SQL Query using a string concatenation from a previous line
Effectively, I am using Django and django content types which references a table containing all the table's IDs. What I am trying to do is use the last column I am creating 'subquery' to be the query to use in joining on it. I can't tell if I am just not searching appropriately or if its not possible. I've looked at crosstab and I've looked at functions. This the query I am running so far select lookuptable.id, lookuptable.use_case_layer_id, use_case_choice_id, luc.project_name, choice.choice_name, lookuptable.utilized_model_object_id, lookuptable.utilized_model_id, dct.*, 'public.' || dct.app_label || '_' || dct.model as subquery -- <-- this line is the one I am trying from corelookup_lookuptable lookuptable inner join public.corelookup_lookupusecase luc on lookuptable.lookup_use_case_id = luc.id inner join public.corelookup_usecaselayerchoice choice on choice.id = lookup_use_case_id inner join public.django_content_type dct on lookuptable.utilized_model_id = dct.id id use_case_layer_id use_case_choice_id project_name choice_name utilized_model_object_id utilized_model_id id app_label model subquery 3691 1 36 PPM Operations 1 354 354 corelookup lookupcheckoutsection public.corelookup_lookupcheckoutsection 3 1 54 PPM Operations 6 112 112 aqe idarea public.aqe_idarea 4 1 54 PPM Operations 7 112 112 aqe idarea public.aqe_idarea 6 1 54 PPM Operations 9 112 112 aqe idarea public.aqe_idarea 7 1 54 PPM Operations 10 112 112 aqe idarea public.aqe_idarea 8 1 54 PPM … -
Django React div with id won't load from js file?
Very new to React + Django The frontend/src/components/App.js: import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class App extends Component { render() { return <h1>React App</h1> } } ReactDOM.render(<App />, document.getElementById('app')); The frontend/src/index.js: import App from './components/App'; Then I have the frontend/templates/frontend/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://bootswatch.com/5/cosmo/bootstrap.min.css"> <title>Lead Manager</title> </head> <body> <div id="app"></div> {% load static %} <script src="{% static "frontend/main.js" %}"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.5/dist/umd/popper.min.js" integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-kjU+l4N0Yf4ZOJErLsIcvOU2qSb74wXpOhqTvwVx3OElZRweTnQ6d31fXEoRD1Jy" crossorigin="anonymous"></script> </body> </html> When I run the server and go to localhost:8000: The <div id="app"></div> remains empty. No errors raised. I am not sure what the issue might be. I double checked the file against the tutorial I am following. -
python3-saml and Azure AD - missing a point
Good afternoon experts, I have a Django web application (it is not internet-facing) and so far I used the django.contrib.auth.backends.ModelBackend to authenticate the users. However I want to integrate this webapp to an existing SSO solution (like Azure AD) so I thought python3-saml would be a good library to be used (more specifically I use python3-saml-django but it is just a wrapper around python3-saml). Probably I am missing some fundamental point as I don't really understand how this should work. When I used ModelBackend then I had a login form where the user could type their username+password which was checked against Django database and the authentication was completed. Should the same work with SSO too? i.e. the login form appears, the user will type their credentials but they will be checked in Azure AD instead of Django auth tables? Or the custom login form of that specific auth solution (in this case Azure AD -> Microsoft login form) should be displayed...? The LOGIN_URL setting is configured in my Django app so if no user is logged in then automatically my login form appears. Also I set the AUTHENTICATION_BACKENDS setting and it points only to django_saml.backends.SamlUserBAckend. I configured AZure AD (registered … -
Django tailwind custom arbitrary colors not working
I've been using django with django-tailwind to build a website that involves color mixing. I take a bunch of colors from a database and mix them together. This results in new colors that I can't write down in the tailwind config and so I've been trying to use the arbitrary values custom colors from the documentation. The css for the color shows up correctly in my inspector but the color itself doesn't compile. I've also noticed that if I manually enter the color hex anywhere in the code (on another element for example), all elements with that specific color code get rendered correctly so I'm guessing it's something to do with django-tailwind not compiling the colors since they are determined during runtime or something. My django template code is as follows: {% for day_obj in days %} <div class="flex flex-col bg-[{{day_obj.day.color}}]"> and here it is from the chrome inspector But it doesn't work. However, this will render all the elements correctly that have that specific color code: #82e153. Elements that are rendered from before also tend to stick around after I remove the manually-entered-hex-code but usually just stop rendering after a while (I assume due to some sort of caching … -
Django changepassword validators overlap
[][1] used imported PasswordChangeForm , it generates 2 errorlist one from the validators and other from oldpassword error and they overlap https://i.stack.imgur.com/1J2vx.png -
django + S3 doens't work when updating Profile
I am working on a django web app, I wasn't working with S3 before but once I started using it, I can view css js and all static pictures that are located there also the default profile picture of users, Now the problem is users can't upload their profile pictures, once they click update and the page is refreshed their profile picture come back to default one and I lose all informations that has to be updated for profile. this is Profile model: class Profile(models.Model): gender = ( ('Female', 'Female',), ('Male', 'Male',), ) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") first_name = models.CharField(max_length=200,blank=True) last_name = models.CharField(max_length=200,blank=True) username = models.CharField(max_length=200) email = models.EmailField(max_length=200) birthdate = models.DateField(verbose_name=("birthdate"), null=True,blank=True) gender = models.CharField(max_length=60, blank=True, default='',choices=gender,verbose_name="gender") image = models.ImageField(upload_to='static/images/profile_pics/',default='static/images/profile_pics/profile.png',null=True, blank=True) conception = models.ManyToManyField(Conception,related_name="profileconceptions") bio = models.CharField(max_length=100, blank=True,default='') slug = models.SlugField(null=True, blank=True,allow_unicode=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) phoneNumber = PhoneNumberField(null=True, blank=False, unique=True) objects = ProfileManager() def __str__(self): #return f"{self.user.username}-{self.created.strftime('%d-%m-%Y')}" return f'{self.user.username},{self.id}' __initial_first_name = None __initial_last_name = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__initial_first_name = self.first_name self.__initial_last_name = self.last_name def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) SIZE = 300, 300 if self.image: pic = Image.open(self.image.name) pic.thumbnail(SIZE,Image.LANCZOS) pic.save(self.image.name) if self.slug == None: slug = slugify(self.user.username,allow_unicode=True) has_slug = Profile.objects.filter(slug=slug).exists() …