Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django and Javascript ReferenceError: function is not defined at HTMLButtonElement.onclick
So I have index.js in static/network/index.js and I would like the functions I define there to run in Django templates. The file is linked by and {% load static%} but unfortunately after adding a button with the onliclick parameter in the console to any place in the template, it appears error "ReferenceError: function is not defined at HTMLButtonElement.onclick" layout.html {% load static %} // This is where static files should be loaded. <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Social Network{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'network/styles.css' %}" rel="stylesheet"> <script src="{% static 'network/index.js' %}"></script> // And this is where the static files should also be loaded. </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Network</a> <div> <ul class="navbar-nav mr-auto"> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'profile' user.username %}"><strong>{{ user.username }}</strong></a> </li> {% endif %} <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}" >All Posts</a> </li> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'followers_view' %}">Following</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}">Log Out</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Log In</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Register</a> … -
How do I change FilePathField to FileField in a Django Model dependant on the instance of a related Model?
I am trying to create a directory based on the instance of a created participant. This directory will be used to upload files for that participant. I'm trying to convert a desktop app into a Django web app and I'm new to Django. Any help will be greatly appreciated. Thanks in advance. My code: def processed_path(report_folder_name): s_id = report_folder_name processed_file_path = os.path.join(settings.MEDIAFILES_DIR, 'processed', s_id) processed_file_path = str(processed_file_path) if not os.path.exists(processed_file_path): os.mkdir(processed_file_path) return processed_file_path class Participant(models.Model): id = models.BigAutoField(primary_key=True, unique=True, editable=False) participant_id = models.CharField(default="Participant", max_length=100) location = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True, null=True) # isansys_file_upload = models.FileField(null=True, blank=True, upload=isansysFilePath) def __str__(self): return str(self.participant_id) class ProcessedDataFile(models.Model): participant = models.ForeignKey(Participant, on_delete=models.CASCADE) processed_folder_name = Participant.participant_id processed_file_upload = models.FileField(null=True, blank=True, upload_to='processed/') processed_file_path = models.FilePathField(null=True, blank=True, path=processed_path) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.processed_file_path) -
Can Django see in inner directories 'management/commands' a commands
Whether can Django see a command which is situated like management/commands/other_directory/my_command.py? I just wanna sort them by their actions. -
Django request.body format
When I try to print request.body, the below is printed b'----------------------------914826831994362856243559\r\nContent-Disposition: form-data; name="release_date"\r\n\r\n2003-06-01\r\n----------------------------914826831994362856243559\r\nContent-Disposition: form-data; name="fanmodel"\r\n\r\nfan234code\r\n----------------------------914826831994362856243559\r\nContent-Disposition: form-data; name="country_code"\r\n\r\nAO\r\n----------------------------914826831994362856243559--\r\n' My post request data is available here but along with a lot other data. I want to understand what is that other data and how can I format it ? -
how can I create a category for ungrouped data?
I'm trying to create a category for scraped data that isn't grouped but I get this error. I'm wondering if there is a way I can get around it. Traceback (most recent call last): File "C:\Users\MUHUMUZA IVAN\Desktop\JobPortal\test.py", line 128, in <module> the_category = Category.objects.get(title="Others") File "C:\Users\MUHUMUZA IVAN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\MUHUMUZA IVAN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 397, in get raise self.model.DoesNotExist( jobapp.models.Category.DoesNotExist: Category matching query does not exist. for test_job in final_jobs: if 'Manager' in test_job['title']: the_category = Category.objects.get(title='Manager') elif 'Engineer' in test_job['title']: the_category = Category.objects.get(title= 'Engineer') elif 'Architect' in test_job['title']: the_category = Category.objects.get(title='Architect') else: the_category = Category.objects.get(title="Others") I know it says there is no query matching Others, how can I correct this. -
Django - separated settings by environment. Not finding variable from base settings
I've split my django environment as per this post. In settings/base.py I have BASE_DIR specified: BASE_DIR = Path(__file__).resolve().parent.parent.parent In settings/__init__.py I have: from .base import * env = os.environ['ENV'] ... if env == 'test': from .test import * ... In settings/test.py I have DATA_VOLUME_BASE_DIR = BASE_DIR / 'scanned_images'. I expect that Django loads the settings module, imports settings/base.py, checks the environment ('test'), imports settings/test.py (which works) and the variable is available (which isn't). My stacktrace: sid_test_web | Traceback (most recent call last): sid_test_web | File "/code/manage.py", line 22, in <module> sid_test_web | main() sid_test_web | File "/code/manage.py", line 18, in main sid_test_web | execute_from_command_line(sys.argv) sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_ sid_test_web | utility.execute() sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 363, in execute sid_test_web | settings.INSTALLED_APPS sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__ sid_test_web | self._setup(name) sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 69, in _setup sid_test_web | self._wrapped = Settings(settings_module) sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 170, in __init__ sid_test_web | mod = importlib.import_module(self.SETTINGS_MODULE) sid_test_web | File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module sid_test_web | return _bootstrap._gcd_import(name[level:], package, level) sid_test_web | File "<frozen importlib._bootstrap>", line 1050, in _gcd_import sid_test_web | File "<frozen importlib._bootstrap>", line 1027, in _find_and_load sid_test_web | File "<frozen importlib._bootstrap>", … -
add to cart button is not responding
my add to cart button is not responding. I have applied javascript on my add to cart button, In cart button I have assigned attribute i.e data-product the value that is {{product.id}}. <div class="card-body"> <h5 class="card-title fw-bold text-uppercase">{{product.name}}</h5> <p class="card-text"><h4 style="font-size: 1rem; padding: 0.3rem; opacity: 0.8;">$ {{product.price}} </h4></p> <button data-product={{product.id}} data-action="add" class = "btn btn-outline-secondary add-btn update-cart">ADD TO CART</button> </div> </div> above is my code for products.html and this my code for javascript. var updateBtns = document.getElementsByClassName('update-cart') for(var i = 0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) }) } The console is not showing any thing even though I click on Add to Cart button several times -
When will the "raise_exception=True" pass through the is_valid() function?
My Serializer.py in this MovieSerializer I will check if "name" and "description" is same or not, if same then raise an error. class MovieSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=80) description = serializers.CharField(max_length=300) def create(self, validated_data): return Movie.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.save() return instance # object level validation def validate(self, data): if data['name'] == data['description']: raise serializers.ValidationError("Name and Description can not be Same.") else: return data My views.py in serializer.is_valid() not pass raise_exception=True, when 'name' and 'description' is same it return a formated error message. output : class MovieListAV(APIView): def post(self, request): serializer = MovieSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My another serializer validate "password" and "confirm_password" same or not, if different then raise an error. class UserPasswordChangeSerializer(serializers.Serializer): password = serializers.CharField(write_only=True, style={'input_type':'password'}) confirm_password = serializers.CharField(write_only=True, style={'input_type':'password'}) class Meta: fields = ['password', 'confirm_password'] def validate(self, attrs): password = attrs.get('password') password2 = attrs.get('confirm_password') if password != password2: raise serializers.ValidationError({'password':'Password and Confirm Password Should be Same!'}) user = self.context.get('user') user.set_password(password) user.save() return attrs My other view serializer.is_valid() not pass raise_exception=True, when "password" and "confirm_password" is dirrerent it can't return any formated error message. but when I use "raise_exception=True" as a … -
How to add data dynamically to specific column in jQuery DataTable which is already initialised?
In jQuery DataTable, i want to add data to specific columns dynamically after table is initialised, I don't want to reinitialise table again, just want to add row data to specific columns dynamically.