Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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() … -
Send email and sms django phone auth
I'm using the django-phone-auth library for authentication, but I can't figure out how to send email verification and phone verification # for email from django.dispatch import receiver from phone_auth.signals import verify_email @receiver(verify_email) def verify_email_signal(sender, user, url, email, **kwargs): ... # Send email ... #for phone from django.dispatch import receiver from phone_auth.signals import verify_phone @receiver(verify_phone) def verify_phone_signal(sender, user, url, phone, **kwargs): ... # Send SMS ... the documentation says this. How can i send email and phone ?? please help me )) -
How to change DRF endpoints's required fields
I am using jwt.io on my DRF project. As you know jwt.io has already a Login API view called 'TokenObtainPairView' and it requires 2 fields: username and password. But in our project, we want users to log in with their email instead of their username. I handle this with the following code: class LoginAPIView(TokenObtainPairView): def post(self, request, *args, **kwargs): email=request.data['email'] request.POST._mutable = True profile=ProfileModel.objects.get(email=email) request.data['username']=profile.username request.POST._mutable = False return super().post(request, *args, **kwargs) It works but on my swagger when front-end devs check the endpoint they see that the endpoint requires 2 fields: username and password. But I want them to see required fields such as email and password. here is the how my endpoint look like Is there any way to change its required fields? -
ModuleNotFoundError: No module named 'learning_logs.urls'
I'm working on a Django project from a book right now. The version is a little outdated so I've been trying to follow the documentation for the more up to date version on some things. I'm running into an issue adding the urls. It says: ModuleNotFoundError: No module named 'learning_logs.urls' My urls.py code: from django.contrib import admin from django.urls import path from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls')) ] Is there any other code I need to add? Thanks for any help! -
How to place cursor at end of text in input field after form submission using html and javascript?
I've created a text input form in html that sends user input words via POST method to Django views.py file. Here is the code for this form <form method="POST" action="search"> {% csrf_token %} <input type="search" name="search" value="{{form.search.value}}" placeholder="Search here..." autofocus x-webkit-speech/> </form> The value attribute takes the value returned by Django after a submit. Here is the code of my Django views.py file: from django.shortcuts import render import requests from bs4 import BeautifulSoup as bs from search.models import MyForm def index(request): return render(request, 'index.html') def search(request): if request.method == 'POST': search = request.POST['search'] form = MyForm(request.POST) max_pages_to_scrap = 15 final_result = [] for page_num in range(1, max_pages_to_scrap+1): url = "https://www.ask.com/web?q=" + search + "&qo=pagination&page=" + str(page_num) res = requests.get(url) soup = bs(res.text, 'lxml') result_listings = soup.find_all('div', {'class': 'PartialSearchResults-item'}) for result in result_listings: result_title = result.find(class_='PartialSearchResults-item-title').text result_url = result.find('a').get('href') result_desc = result.find(class_='PartialSearchResults-item-abstract').text final_result.append((result_title, result_url, result_desc)) context = {'final_result': final_result, 'form':form} return render(request, 'index.html', context) else: return render(request, 'index.html') When I submit the form, the value of the input field is well preserved but the cursor goes from the final position to the initial position. To solve this problem, I inserted a javascript script created in this article, in my index.html file … -
_wrapped_view() missing 1 required positional argument: 'request'
below is my code, just trying to include a decorator but getting the above error, have used the decorator elsewhere with no issues. class AudienceListView(ListView): model = Audience template_name = 'audience/list.html' @method_decorator(company_user_has_permission('audiences_view')) def get_queryset(self): queryset = super().get_queryset() company = Company.get_current(self.request) return queryset.filter(company=company) \ .annotate(total_deals=Count("deals"), total_contacts=Count("contacts")) \ .order_by('-id') -
ArrayField in Django model does not validate
My model has an attribute: regione = ArrayField( models.IntegerField( default=0, choices=REGIONE_CHOICES ), blank=True, null=True, default=None ) where REGIONE_CHOICES is ((1, 'opt1'), (2, 'opt2')) and so on. In my ModelForm for my Model I specify a widget for it: class Meta: model = Mymodel fields = [some_fields, 'regione'] widgets = { 'regione': forms.SelectMultiple(choices=REGIONE_CHOICES) } The choices are displayed correctly on the front-end and I can select multiple, but clicking submit doesn't go through, I get Item 1 in the array did not validate as an error in the form. -
Django broken response with file data
In my project I use AWS S3 Bucket for media files. Project contains media_app application, that provide get and post requests to files in remote storage (all requests go through server, so media_app is kinda proxy between frontend and AWS S3. Today I faced with problem. When I try to get media file from AWS S3, Django correctly download it from remote bucket, save it in /tmp/ dir, get correct response metadata, but response itself is broken: it cause infinite response "in progress" state on frontend side (Tried with Postman and Swagger). "In progress" means "frontend application wait until response will be recieved", but on backend side there is no infinite loop. Django can provide next responses even if I use dev test server (Is is means, that no workers are blocked, cause django test server have only one worker). Information about request and response (Django Silk): There is a part of my view, that provide image download: from django.http import Http404, StreamingHttpResponse from wsgiref.util import FileWrapper class ImageDetailAPIView(DetailDownloadAPIView): queryset = Image.objects.filter(is_soft_deleted=False)\ .prefetch_related('thumbnails') serializer_class = ImageSerializer @swagger_auto_schema(responses=image_detail_responses) def get(self, request, *args, **kwargs): try: instance = self.get_object() except Http404: raise FileNotFoundException service = ImageDownloadService(instance) chunk_size = 8192 file_path, status_code = service.download() … -
Why I get error raise ImproperlyConfigured
I want to add info in database using django-seed. seed.py from django_seed import Seed from models import Employee seeder = Seed.seeder() seeder.add_entity(Employee, 5) inserted_pks = seeder.execute() When I try to start command: python3 seed.py I've got this error: Traceback (most recent call last): File "seed.py", line 2, in <module> from models import Employee File "/home/kaucap/test/myproject/app_worker/models.py", line 4, in <module> class Employee(models.Model): File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/db/models/base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/apps/registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 67, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Can anyone explain why I have this error and how I can fix it? -
Render Django Template after AJAX POST
I'm using django and ajax to build a small app. I send some data by ajax: // send search post when clicking the button $("#search-button").click(function(){ $.post( "{% url 'search-index' %}", { query: $("#query").val() }, function(data, status){ console.log("success") } ) }) And I generate some new data according to the query, which I'd like to display in the html template: def view(request): if request.method == "POST": query = request.POST["query"] hits = search(query) return render(request, "search/index.html", {"hits": hits}) {% if hits %} <div class="container"> {% for hit in hits %} <div> <a href="">{{ hit.title }}</a> </div> <div> <p>{{ hit.abstract }}</p> </div> {% endfor %} </div> {% endif %} However, I find django is not rendering the template, I got an empty html page after this post request. I don't want to append the data using jquery. I prefer to modify the html in the template. Any solution? Thanks in advance. -
Where to store dictionary in Django
I have a dictionary that I get from the local delivery company API. I want to use it in my app to populate the city select field. I don't want to get this data every time when a user loads the page. So I need to store it somewhere and update it once a day. What is the best way to do this using Django? url = 'https://api.novaposhta.ua/v2.0/json/' data = { "apiKey": "apiKey", "modelName": "Address", "calledMethod": "getCities", "methodProperties": {} } city_list_json = requests.post(url, json=data).text city_dict = {d['Ref']: d['Description'] for d in json.loads(city_list_json)['data']} -
TimeoutError while sending mails
I have a Django project where the users can launch a task that's executed using Celery, and then they receive a mail when this task is finished. My issue lays in my mails that are not sent everytime. Some emails are not sent and in the console I have a TimeoutError: [Errno 10060] WSAETIMEDOUT. I don't know if that can help but I noticed that when I start trying to send mails, the first ones raise this error, and after some time of trying to send mails, like maybe 15mn, the mails are sent successefully and I get no error afterwards. I've tried every solution I was able to find here on SO as well as on GitHub, but none of the solutions provided seemed to work for me. I'm using gmail with a double authentication. I have this in my settings.py file : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my-email-account' EMAIL_HOST_PASSWORD = 'my-password' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'emaildetest81@gmail.com' My email sending function : from django.core.mail import EmailMessage from django.conf import settings def send_output_file(mail): header = "Result of task execution" body = "Your task has finished executing !" email = EmailMessage(header, body, settings.DEFAULT_FROM_EMAIL, [mail,],) … -
Django rest framework APIView Pagination EmptyPage
Successfully made pagination work and here is my code: from rest_framework import pagination class CustomPagination(pagination.PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 10 page_query_param = 'p' class PaginationHandlerMixin(object): @property def paginator(self): if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator = None else: self._paginator = self.pagination_class() else: pass return self._paginator def paginate_queryset(self, queryset): if self.paginator is None: return None return self.paginator.paginate_queryset(queryset, self.request, view=self) def get_paginated_response(self, data): assert self.paginator is not None return self.paginator.get_paginated_response(data) and this my view class: class OrderOntrackViewPaginated(APIView, PaginationHandlerMixin): queryset = Order.objects.filter(~Q(staged__iexact="offtrack")).values().order_by('-id') serializer_class = OrderSerializer pagination_class = CustomPagination permission_classes = (permissions.AllowAny,) http_method_names = ['get'] def get(self, request): results = self.paginate_queryset(self.queryset) serializer = self.serializer_class(results, many=True) return self.get_paginated_response(serializer.data) my question is if I can handle EmptyPage so if max page is for example 3 and user puts ...?p=4 in the request, I could return a valid response. -
Django best way to communicate between two domain servers
I have a requirement in which an admin domain for example 'domainA' where the admin can login and he can restrict the user access to domainB,domainC.... What is the best way to achieve this. Current functionality is that each users are created in each domain and assigned in respective groups.So my question is from domainA how can I add or remove users from domainB,domainC.. from domainA -
Getting this error when i am run migrate i check in below path but i don't what to change there
File "C:\Users\shubham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\dateparse.py", line 116, in parse_datetime return datetime.datetime.fromisoformat(value) TypeError: fromisoformat: argument must be str PS E:\Django\login> -
how to send an email verification from admin when an email is updated
I joined a project where the code is written on django 2+. It's a system for patient and doctors. When a doctor registered a patient, this one gets an email confirmation with a link. Once he clicks on it she can use the platform. On her user interface in settings, a patient can update her email and she will get a new link to her new email to confirm that it is her email. Before she clicks on the confirmation link, the email attribute is not changed. only the email candidate is updated and to this one the email is sent. (if I change the email attribute to the email_candidate one so if she made a mistake on the her email_candidate she won't be able to log in anymore) Then after the click, the patient email will become the email candidate one. All this works on the Patient Support Admin interface, an agent can help patients to update their email also. But when the action is requested of send an email confirmation the email candidate is not chosen. only the user email is chosen and to it the email confirmation is sent. I really don't understand how to call maybe … -
Field 'codigo_cad' expected a number but got <Customer: 1>
I have no idea how to fix this: I'm having problems when pulling the costumer.codigo_cad, because I have the str functionality that only sends a string, and the object is requesting an int, whenever I try to move this part the error becomes bigger, like the location reads as if was a table object, and not an int, thanks in advance to anyone who helps me *my models return str(self.codigo_cad) def get_aniversario(self): return f'{self.aniversario_cad.strftime("%d/%m/%Y") if self.aniversario_cad != None else "30/12/1899"}' # clica na pessoa e retorna os detalhes dela def get_customer_url(self): return f'/customer/{self.codigo_cad}' # clica em vendas e retorna as vendas da pessoa def get_sale_customer_url(self): return f'/venda/?customer_sale={self.codigo_cad}' ** my views ** order_forms = Venda() item_order_formset = inlineformset_factory(Venda,ItemVEN,form=ItemVenForm,extra=0,can_delete=False,min_num=1,validate_min=True) venda = get_object_or_404(Venda,pk=pk) # recupera venda #desconto = f'{venda.desconto_ven:,}' # formata desconto cliente = get_object_or_404(Customer,pk=venda.cliente_ven) # para recuperar os dados do cliente da venda clientes = Customer.objects.all().order_by('pk') # para o modal clientes produtos = Produto.objects.all().order_by('pk') # para o modal produtos itens = ItemVEN.objects.filter(num_ven_ite=pk) # recupera itens venda itens_venda = []``` -
Use viewset and serializer without model
I want to return the CPU usage and Memory usage by viewset. class StatusViewSet(viewsets.ViewSet): serializer_class = StatusSerializer def list(self, request): // get CPU/Memory usage here somehow. below line is dummy. status_data= {"memory":80,"cpu":80} serializer = StatusSerializer( instance=status_data, many=True) return Response(serializer.data) class StatusSerializer(serializers.Serializer): cpu = serializers.IntegerField(read_only=True) memory = serializers.IntegerField(read_only=True) What I have done is like this below. I just want to return {"memory":80,"cpu":80} however it returns blank value. [ {}, {} ] I suspect I should return the data to serializer in another way instance=status_data, however how can I do this? -
AttributeError: 'Settings' object has no attribute 'STRIPE_PUBLIC_KEY'
stripe.api_key = settings.STRIPE_SECRET_KEY I am using dgango and its my first project and shows error after adding the above line in views.py file: File "C:\Users\iamab\AppData\Local\Programs\Python\Python310\lib\site-packages\django\conf_init_.py", line 80, in getattr val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'STRIPE_PUBLIC_KEY' -
How can I create fake db using django-seed with code?
I need to create fake database. If I use command: python3 manage.py seed api --number=15 it works fine. But how can I create fake DB using with code? There some example of code: from django_seed import Seed seeder = Seed.seeder() from myapp.models import Game, Player seeder.add_entity(Game, 5) seeder.add_entity(Player, 10, { 'score': lambda x: random.randint(0, 1000), 'nickname': lambda x: seeder.faker.email(), }) inserted_pks = seeder.execute() How can I run it after start my server?