Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy my Django project into plesk server and run it , give me a step by step process please
I need to know how deploy my project into plesk , i never done this before. I search in Youtube but i can't fine a video for it . chat gpt also not give a clear steps i have a plesk panel credentials and i verify the python installed or not , it instaled and pip also there i created a virtual environment too , i upload the django folder to plesk server, i don't know what to do next, the problem is i want to upload my django project to pleask that i don't know -
Unable to get the date from tempusdominus bootstrap4 plugin to Django form
Here is my html code. <div class="col-md-3"> <label> Approved Date:</label> <div class="input-group date" id="{{ form.ApprovedDate.id_for_label }}" data-target-input="nearest"> <input type="text" class="form-control datetimepicker-input" id="{{ form.ApprovedDate.id_for_label }}" name="{{ form.ApprovedDate.id_for_label }}" data-target="#{{ form.ApprovedDate.id_for_label }}"/> <div class="input-group-append" data-target="#{{ form.ApprovedDate.id_for_label }}" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> </div> and here is the Script Jquery <script> $(function () { $('#{{ form.ApprovedDate.id_for_label }}').datetimepicker({ format: 'DD-MM-YYYY' }); }) </script> My problem is that this field is not being passed to my django form which is of this code. class ProjectForm(forms.ModelForm): #views.py class Meta: model = Project fields = '__all__' def save(self, commit=True): instance = super().save(commit=False) instance.created_on = timezone.now() # Import timezone if not already imported instance.createdBy = 0 if commit: instance.save() return instance def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) I simply want to read value of this field so the same can be saved to db. by this code in views.py def create_project(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() # Save to the database with the modified fields return redirect('projects:project_list') # Redirect to the list view else: form = ProjectForm() return render(request, 'create_project.html', {'form': form}) I have tried many solutions like importing tempusdominus package but I … -
python setup.py egg_info did not run successfully : when trying to install psycopg2
I am facing this issue when trying to run psycopg2, any one with solution would be helpful, thanx! Collecting psycopg2==2.8.6 (from -r requirements.txt (line 45)) Using cached psycopg2-2.8.6.tar.gz (383 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [37 lines of output] running egg_info creating /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info writing /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/SOURCES.txt' /home/lungsang/Desktop/Contextus/env/lib/python3.8/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in `setup.cfg` !! parsed = self.parsers.get(option_name, lambda x: x)(value) Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed This error appears when i try to run psycopg2 and I upgraded setuptools, still not solved. -
copy to clipboard not working with django and js
Hi guys I created a basic copy to clipboard functionality using django and js, everything seems to be ok but when i try to copy my info i get this error This is the piece of code where I'm doing everything <table class="init-datatable display"> <thead> <tr> <th>Company</th> <th>Avt User Name</th> <th>Full Name</th> <th class="email-column">Email Address</th> <th>Expiration Date</th> <th>Avt Version</th> <th>License</th> <th>Generated User</th> <th>Copy information</th> </tr> </thead> <tbody> {% for item in object_list %} <tr> <td class="th-width">{{ item.user.company.name }}</td> <td class="th-width">{{ item.user.user_name }}</td> <td class="th-width">{{ item.user.full_name }}</td> <td class="th-width email-column">{{ item.user.email }}</td> <td class="th-width">{{ item.expire_date }}</td> <td class="th-width">{{ item.avt_version}}</td> <td class="th-width">{{ item.license_avt }}</td> <td class="th-width">{{ item.generated_user.username }}</td> <td class="th-width"> <button class="control button copy-btn btn" company-name="{{item.user.company.name}}" user-name="{{item.user.user_name}}" full-name="{{item.user.full_name}}" email="{{item.user.email}}" expire-date="{{item.expire_date}}">Copy information</button> </td> </tr> {% endfor %} </tbody> </table> <script> const copyBtns = [...document.getElementsByClassName("copy-btn")] copyBtns.forEach(btn => btn.addEventListener('click', ()=>{ const companyName = btn.getAttribute("company-name") const userName = btn.getAttribute("user-name") const fullName = btn.getAttribute("full-name") const email = btn.getAttribute("email") const expireDate = btn.getAttribute("expire-date") console.log(companyName) console.log(userName) console.log(fullName) console.log(email) console.log(expireDate) btn.textContent = "Copied" setTimeout(() => { btn.textContent = "Copy information" }, "1350"); navigator.clipboard.writeText(companyName) })) </script> If someone can tell me how to fix this or another way to tackle this feature of copying stuff from the HTML it would be … -
How to implement ForeignKey search in Django REST framework
When developing the API, I tried to implement a search system but encountered an error Unsupported lookup 'icontains' for ForeignKey or join on the field not permitted. Models class GroupTask(models.Model): UserToken = models.TextField(default="") NameGroupTask = models.TextField(null=True) StatusGroupTask= models.BooleanField(default=False) class Meta: ordering = ['NameGroupTask'] def __str__(self): return self.NameGroupTask[0:50] class TaskForGroup(models.Model): UserToken = models.TextField(default="") NameTaskForGroup= models.TextField(null=True) DescriptionTask = models.TextField(null=True) StatusTaskForGroup= models.BooleanField(default=False) Group = models.ForeignKey(GroupTask, on_delete = models.CASCADE) class Meta: ordering = ['NameTaskForGroup'] def __str__(self): return self.NameTaskForGroup[0:50] viewsets for output class TaskForGroupAPI(viewsets.ModelViewSet): # показываем что доступны все методы для работы с данными (post, get, put, delete запросы) queryset= TaskForGroup.objects.all() # указываем сериализатор serializer_class = TaskForGroupSerializer # устанавливаем классы для фильтрации filter_backends = (DjangoFilterBackend, SearchFilter) # указываем поле по которому проводить фильтрацию search_fields = ['Group',] def get_paginated_response(self, data): return Response(data) how am I trying to find the TaskForGroup I need http://127.0.0.1:8000/TaskForGroupAPI/TaskForGroupAPI/?search=5 -
Ajax Request is returning error with log: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
I have a Django application where I have an html page with two forms that I want to be submitted with two different ajax requests. The first request works perfectly fine, but for some reason the second request results in an error response I'm printing out to the console like this: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} abort : ƒ (a) always : ƒ () complete : ƒ () done : ƒ () error : ƒ () fail : ƒ () getAllResponseHeaders : ƒ () getResponseHeader : ƒ (a) overrideMimeType : ƒ (a) pipe : ƒ () progress : ƒ () promise : ƒ (a) readyState : 4 responseText : "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n setRequestHeader : ƒ (a,b) state : ƒ () status : 200 statusCode : ƒ (a) statusText : "OK" success : ƒ () then : ƒ () [[Prototype]] : Object I have no clue how to debug this... The first ajax request is just to partially fill the second form. The second form is a Model Form that is supposed to add an instance off my model in my view. View: def canadaTaxEntries(request): newest_record = LAWCHG.objects.aggregate(Max('control_number')) newest_control_number = newest_record["control_number__max"] print(newest_control_number) today = date.today().strftime("1%y%m%d") … -
How get Nearby place information's like school, hospital, malls and cinema hall in django
I am creating a real estate rental project and in that I want to show a property and nearby places to that particular property to the users using latitude and longitude of the property. I have no idea how to do that, so can you please tell all steps including what required files I need to install as well. Please show me complete guide with code. -
Why is DRF's router selectively not redirecting to a trailing slash?
Desired behavior For router endpoints to append a trailing slash if one is not provided. E.g. /api/customers would redirect to /api/customers/ Actual behavior A 404 is returned if a trailing slash isn't applied to the endpoint. E.g. /api/customers return a 404 response Additional context APPEND_SLASH is set to True CommonMiddleware is set The trailing slash works on non-DRF endpoints. E.g. /admin redirects to /admin/ The trailing slash works on one set of ViewSet endpoints. The user ViewSet works. E.g. /users redirects to /users/ The user app is the last app in the project alphabetically. None of the other ViewSets registered redirect to the trailing slash. Code project_name/urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from rest_framework import routers from user.views import UserViewSet, LoginView, logout_view from customer.views import CustomerViewSet from intake.views import IntakeViewSet from extraction.views import ExtractionViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='users') router.register(r'customers', CustomerViewSet, basename='customers') router.register(r'intakes', IntakeViewSet, basename='intakes') router.register(r'extractions', ExtractionViewSet, basename='extractions') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), path('api/login/', LoginView.as_view()), path('api/logout/', logout_view), ] if settings.DEBUG: # Add dev static files urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Add debug toolbar patterns urlpatterns.append(path('__debug__/', include('debug_toolbar.urls'))) TLDR Only one set of endpoints registered to DRF's … -
How to manage List an Dict in Django views and Template?
When I iterate through a Query in Django my Dict only update the last item. Does anyone knows how to add all Query data on it. It is wierd because if I create a list with the same Query it does get all data (as you can see just bellow vendor number 5 has two opening_hours ins List but not in Dict): Query with a Dict: dict_today_open_hour = {} for t in v.today_opening_hours: dict_today_open_hour.update({t.vendor.id:{'today_from_hour': t.from_hour, 'today_to_hour': t.to_hour,}}) The Dict result is: {1: {'today_from_hour': '07:00', 'today_to_hour': '20:00'}, 5: {'today_from_hour': '22:00', 'today_to_hour': '23:00'}} Same Query with a List: list_today_open_hour = [] for t in v.today_opening_hours: list_today_open_hour.append({t.vendor.id:{'today_from_hour': t.from_hour, 'today_to_hour': t.to_hour,}}) List result: [{1: {'today_from_hour': '07:00', 'today_to_hour': '20:00'}}, {5: {'today_from_hour': '09:00', 'today_to_hour': '19:00'}}, {5: {'today_from_hour': '22:00', 'today_to_hour': '23:00'}}] As you can see in the List result I got all data from the Query but in the Dict result I only get the last item from vendor id number 5. Does anyone knows if it is possible: 1-) Get all data in the Dict Query like the data i got from List? If so how to do it? 2-) Is it possible to user the Query List Result in template and filter it with the … -
adding field to django user model - how to automatically create object instance?
I am attempting to add a field 'balance' to the default django user model, and i've done so with this code: class UserBalance(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) but my problem is that when I create a new user, I need to manually add a value for the balance in the django admin console otherwise I can't use it in html template tags, whereas I want it to just automatically be created and added as 0 to the user's profile once they create it. What is the easiest way to do this? User account that I manually added balance via admin console User account freshly created -
setting en-US.UTF-8 in pycharm until the end of times
I am having hell with the compilemessages in Django translation as every time I write that function it complains of the following: UnicodeEncodeError: 'latin-1' codec can't encode character '\u201c' in position 5: ordinal not in range(256) investigating on the matter I went in my terminal (inside my venv) python import locale locale.getdefaultlocale() and I was furious to be slapped with this: ('en_US', 'ISO8859-1') which means: ISO/IEC 8859-1 encodes what it refers to as "Latin alphabet no. 1", so, I went: locale.setlocale((locale.LC_ALL, 'en_US.UTF-8') and then verified again that it had changed to UTF-8 and it had. So, I opened another terminal (as I didn't want to close the python shell) and tried compilemessages and I got the same error because the default ISO8859-1 was still there. I went to the Pycharm settings and changed the interpreter to python 3.11 however, when I opened a python shell, it continued showing 3.9 Naturally this is driving me insane because it just bulks at whatever I say. To make matters worse, while I always get this long set of errors File "/home/alvaralexandrovich/PycharmProjects/Carpeta9Abril/venv9Abril/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/alvaralexandrovich/PycharmProjects/Carpeta9Abril/venv9Abril/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alvaralexandrovich/PycharmProjects/Carpeta9Abril/venv9Abril/lib/python3.9/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/alvaralexandrovich/PycharmProjects/Carpeta9Abril/venv9Abril/lib/python3.9/site-packages/django/core/management/base.py", … -
Why Amazon S3 not serve images on my Django blog?
I have a blog app wrote in Django and deployed with Heroku. Now I want to keep the images that the users upload with the blog post and I have a default image if the user don't want a specific picture. When I used whitenoise the pictures were there, but after a logout, login they were disappeared and the default were there only. I tried set up an s3 storage to keep all the images, but now all images are gone. I don't know if I should delete whitenoise from middlewares. I changed the media and the statics url too to the s3 bucket. Here is the source of the page, the files are in the s3 storage theoreticaly But when I click one of the images link, I got an access denied: I have a favicon, a css and a javascript in the statics and they are working, so I think the setting of the s3 storage is ok and the problem is image format specific. When I execute collectstatic, it said that it uploaded the files to tmp. Is it ok? Here is my s3 bucket: I tried to manually upload my static folder, but did not serve … -
Why do I get "Failed to load PDF document" when I try to open a modified PDF?
I am new to web development and trying to create a language translation app in Django that translates uploaded documents. I relies on a series of interconversions between pdf and docx. When my code ouputs the downloaded translated document I get "Error Failed to load PDF document" in my browser. Here is my code: from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect from .models import TranslatedDocument from .forms import UploadFileForm from django.core.files.storage import FileSystemStorage import docx from pdf2docx import parse from docx2pdf import convert import time #remove # Create your views here. @csrf_protect def translateFile(request) : file = '' if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file = (converter(uploaded_file_path)) response = HttpResponse(file, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response else: form = UploadFileForm() return render(request, 'translator_upload/upload.html', {'form': form}) def reConverter(inputDocxPath): return convert(inputDocxPath) def translateDocx(aDocx, stringOfDocPath): docx_file = stringOfDocPath myDoc = docx.Document(docx_file) #translation logic myDoc.save(stringOfDocPath) return reConverter(stringOfDocPath) #stringOfDocPath is used as convert() requires file path, not file object(myDoc) def converter(inputPdfPath): # convert pdf to docx pdf_file = inputPdfPath docx_file = inputPdfPath + '.docx' … -
Django - ModelForm does not update on form submission
I have a form for when a user makes a form submission an object with a bunch of fields are supposed to get updated in my application. Currently, when a user makes a form submission with this form a new object gets made and I don’t know why. I receive an error that says “get() returned more than one User_Info -- it returned 2!” How do my I make my current form on the myaccount_edit.html page update the object correctly with my current code? The fields that get updated in the object are based on the logged in user. I've tried many things but I'm kinda lost. The form is located on myaccount_edit.html. Where the form data display is on myaccount.html. That data displays correctly when there isn't an error. Screenshot attached. Any help is gladly appreciated. Thanks! Views: def account_view_myaccount(request): if request.user.is_authenticated: user_profile = User_Info.objects.filter(user=request.user) context = { 'user_profile': user_profile } return render(request, "myaccount.html", context) def account_view_myaccount_edit(request): form = HomeForm(request.POST or None, request.FILES or None) user_profile = User_Info.objects.filter(user=request.user) obj, created = User_Info.objects.update_or_create(user=request.user) user = request.user if request.method == "POST": # checking if request is POST or Not # if its a post request, then its checking if the form … -
Django can't update a related model field based on another model field in Django
Hello everyone I'm trying to update one of the table CashAdmin from fields cash_user based on my table PickUp based on fields is_finished and user as the foreign Key. But for some reason is not working. This is the code: Model of PickUp model.py from gc import is_finalized from django.db import models from django.contrib.auth.models import User class PickUp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_finished = models.BooleanField (default=False) quantity = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) Model of CashAdmin model.py from django.db import models from django.contrib import auth from django.contrib.auth.models import User class CashAdmin(models.Model): cash_user = models.FloatField() user = models.ForeignKey('auth.User', on_delete=models.CASCADE) The is the views file for PickUp. views.py from multiprocessing import context from django.shortcuts import render, redirect, HttpResponse from pickup.forms import CreatePenjemputanForm from pickup.models import PickUp from cash.models import CashADmin from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.core import serializers from django.contrib.auth.decorators import login_required from django.contrib import messages import datetime from django.views.decorators.csrf import csrf_exempt from PickUp.decorators import admin_only # Create your views here. def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' @admin_only def update_pickup(request, id): pick_up = PickUp.objects.get(pk=id) if pick_up.is_finished: pick_up.is_finished = False else: pickup.is_finished = True cash_user = pickup.quantity * 12500 if pick_up.is_finished else cash_user cash_admin, created = CashAdmin.objects.get_or_create(user=pick_up.user) cash_admin.cash_user = cash_admin.cash_user + … -
Can't save field with Djongo and AutoField
This Model generate id_num: class Docahdl(models.Model): id_num = models.AutoField(primary_key=True) data_alter_doca = models.CharField(max_length=20) data_input = models.CharField(max_length=16) handling = models.IntegerField() doca_id = models.CharField(max_length=20) user_id = models.CharField(max_length=80) def __str__(self): return str(self.id_num) But this don't generate id_num: class SlaCD(models.Model): id_num = models.AutoField(primary_key=True) negocio = models.CharField(max_length=10) tipo_sla = models.CharField(max_length=50) data_inicio = models.DateTimeField() data_fim = models.DateTimeField() quantidade = models.FloatField() umd = models.CharField(max_length=10) def __str__(self): return str(self.id_num) Can't have two or more AutoField using Djongo? When I create a instance and save Docahdl save the id_num on MongoDB, but SlaCD not. -
run a docker-compose from crontab
I have a command docker-compose -f docker-compose-deploy.yml run --rm app sh -c "python manage.py runcrons" that works if I run it from terminal. Now I want to run this command from a crontab but I am a bit at a loss of how I should write this. I have tried a bunch of things based on things I have found here: */5 * * * * cd /home/ec2-user/legend-of-solgard; docker-compose -f docker-compose-deploy.yml run --rm app sh -c "python manage runcrons” */5 * * * * /usr/bin/docker-compose -f /home/ec2-user/legend-of-solgard/docker-compose-deploy.yml exec -T app run --rm app sh -c "python manage runcrons” But nothing works. -
why docker raises 'chunked'Error while fetching server API version: HTTPConnection.request() got an unexpected keyword argument 'chunked'?
I have been trying to build a docker service which would run django. but keep getting docker.errors.DockerException: Error while fetching server API version: HTTPConnection.request() got an unexpected keyword argument 'chunked' Dockerfile FROM python:3.7-alpine USER root ENV pythonunbuffered 1 RUN mkdir app COPY ./new /app COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt WORKDIR /app RUN adduser -D user USER user cmd ['python','manage.py','runserver'] docker-compose version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - "./src:/app" command: > sh -c "python manage.py runserver 0.0.0.0:8000" Is there a connection error?why does this keep happening? -
com_error at /translator/translator_upload/ (-2147221008, 'CoInitialize has not been called.', None, None)
I am new to web development and trying to create a language translation app in Django that translates uploaded documents. It relies on a series of interconversions between pdf and docx. When my code ouputs the downloaded translated document I sometimes get a com_error at /translator/translator_upload/ (-2147221008, 'CoInitialize has not been called.', None, None). Here is the full error message: Exception Location: C:\Users\John\tutorial-env\Lib\site-packages\win32com\client\dynamic.py, line 86, in _GetGoodDispatch Raised during: translator_upload.views.translateFile Python Executable: C:\Users\John\tutorial-env\Scripts\python.exe Python Version: 3.11.4 Python Path: ['C:\\djangoProjects\\mysite', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311', 'C:\\Users\\John\\tutorial-env', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\win32', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\win32\\lib', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\Pythonwin'] Here is my code: from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect from .models import TranslatedDocument from .forms import UploadFileForm from django.core.files.storage import FileSystemStorage import docx from pdf2docx import parse from docx2pdf import convert import time #remove # Create your views here. @csrf_protect def translateFile(request) : file = '' if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file = (converter(uploaded_file_path)) response = HttpResponse(file, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response else: form = UploadFileForm() return render(request, 'translator_upload/upload.html', {'form': form}) def reConverter(inputDocxPath): return convert(inputDocxPath) def translateDocx(aDocx, … -
How can we call middleware before urls.py
Middleware `class NetworkCheckMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): domain = request.get_host() if not self.is_valid_domain(domain): return HttpResponseForbidden("Invalid Network") response = self.get_response(request) return response def is_valid_domain(self, domain): networkDomainModel = NetworkDomainModel.loadNetworkByDomain(domain) if networkDomainModel is None: return False obj = NetworkComponent() obj.setupNetwork(networkDomainModel.network_id) return True` NetworkComponent Class contain getId() methods urls.py `if NetworkComponent().getId() is not None: print(NetworkComponent().getId())` Getting None value while running the server Please help me out -
htmx:targetError with {% block content %}
im using htmx with Django. I have the problem, as soon as i add my `{% extends base.html' %} {% load static %} {% block content %} {% endblock content %}` the hx-target leads to a htmx:targetError. This works (search_results.html): <h1>Search Results</h1> {% if results %} <ul> {% for supplier in results %} <li> <strong>Supplier Number:</strong> {{ supplier.supplier_number }}<br> <strong>Name:</strong> {{ supplier.name }}<br> <strong>Street:</strong> {{ supplier.street }}<br> <!-- Weitere Felder hier einfügen --> <a href="{% url 'supplychainmanagement:add_order' %}?supplier_name={{ supplier.name }}" class="select-supplier" hx-get="{% url 'supplychainmanagement:add_order' %}?supplier_name={{ supplier.name }}" hx-target="#bestellungen-list" hx-boost>Lieferant auswählen</a> </li> {% endfor %} </ul> {% else %} <p>No results found.</p> {% endif %} ** this doesnt** (search_results.html): {% extends 'base.html' %} {% load static %} {% block content %} <h1>Search Results</h1> {% if results %} <ul> {% for supplier in results %} <li> <strong>Supplier Number:</strong> {{ supplier.supplier_number }}<br> <strong>Name:</strong> {{ supplier.name }}<br> <strong>Street:</strong> {{ supplier.street }}<br> <!-- Weitere Felder hier einfügen --> <a href="{% url 'supplychainmanagement:add_order' %}?supplier_name={{ supplier.name }}" class="select-supplier" hx-get="{% url 'supplychainmanagement:add_order' %}?supplier_name={{ supplier.name }}" hx-target="#bestellungen-list" hx-boost>Lieferant auswählen</a> </li> {% endfor %} </ul> {% else %} <p>No results found.</p> {% endif %} {% endblock content %} this is my base.html: <!DOCTYPE html> <html lang="en"> {% load static %} … -
Check duplicate data in database using Django
I have a problem which I want to check if data is duplicate based on name and date_travel, let say I add an item name Lebron James and choose multiple date flatpickr like 24-08-2023, 25-08-2023 and the expected result should return a JsonResponse says Duplicate date travel since In the image below the date 24-08-2023 already exist under the name of Lebron james but my problem it always return to else statement evein it has duplicate travel, hope someone helps me thanks in advance Here's what I've Tried I've plan to split and used loop in every date and return in if existed/duplicate in database but it won't work @csrf_exempt def item_add(request): employeename = request.POST.get('EmployeeName') travel_date = request.POST.get('DateTravel') # Split the date string into individual dates individual_dates = travel_date.split(',') for date in individual_dates: cleaned_date = date.strip() query = """ SELECT date_travel FROM tev_incoming WHERE name = %s AND date_travel LIKE %s; """ with connection.cursor() as cursor: cursor.execute(query, [employeename, cleaned_date]) results = cursor.fetchall() if results: return JsonResponse({'data': 'error', 'Duplcate date travel':results}) else: return JsonResponse({'data': 'success', 'message': "Unique travel and name"}) Html input <input type="text" class="form-control" name="DateTravel" placeholder="DD-MM-YYYY" id="dateField"/> script $('#dateField').flatpickr({ mode: 'multiple', allowInput: true, dateFormat: 'd-m-Y', locale: { firstDayOfWeek': 1 // … -
Django Autocomplete Light Select2 generates multiple selectboxes for declarative field
I was expecting to see a single functioning widget, but instead have two partially functioning ones. I have a Work and a Parent Work; each Work can have 0 or 1 ParentWork. models.py class ParentWork(UUIDModel): url_name = "parent_work_detail" class Work(models.Model): parent_work = models.ForeignKey(ParentWork, models.SET_NULL, null=True, blank=True) ... other fields I am using DAL for forms: forms.py class ParentWorkForm(forms.ModelForm): related_works = forms.ModelMultipleChoiceField( label="Related Works", queryset=Work.objects.all().order_by("title"), required=False, widget=autocomplete.ModelSelect2Multiple(url="autocomplete_work"), ) class Meta: model = ParentWork exclude = [] required = ["name"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # for the Parent Works update form, set the initial value of the related_works field try: instance = kwargs.get("instance") if instance: self.fields["related_works"].initial = instance.work_set.all() except Exception as e: print(e) I have to declare related_works on the ModelForm as it is stored on the Work, not ParentWork. Relevant snippet from parent_work_form.html template: {% block content %} <div class="admin-container"> <form method="post" action="." class="mt-4" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div class="mt-10 w-full flex justify-between"> {% if object %} <a href="{% url "parent_works_delete" object.uuid %}" class="text-gray-400 my-auto">Delete</a> {% else %} <span></span> {% endif %} <span> <a href="{% url "parent_works_list" %}" class="cancel">Cancel</a> <button>Save</button> </span> </div> </div> </form> {% endblock %} {% block extra_scripts %} <!-- parent form --> {% … -
Error with downloading "pip install uwsgi" for django project
I have a django project, where I needed to download uwsgi for production use. When trying to download the package, I get the following error (venv) C:\Users\basti\OneDrive - Sofiehøj Ejendomsadministration\OneDrive\PrimusWeb\Main\primusweb-new\portfolio>pip install u wsgi Collecting uwsgi Using cached uwsgi-2.0.22.tar.gz (809 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [8 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\basti\AppData\Local\Temp\pip-install-ds7pxw97\uwsgi_ebb78347cc174fc080e8b57246882331\setup.py", line 3, in <module> import uwsgiconfig as uc File "C:\Users\basti\AppData\Local\Temp\pip-install-ds7pxw97\uwsgi_ebb78347cc174fc080e8b57246882331\uwsgiconfig.py", line 8, in <module> uwsgi_os = os.uname()[0] AttributeError: module 'os' has no attribute 'uname'. Did you mean: 'name'? [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. (venv) C:\Users\basti\OneDrive - Sofiehøj Ejendomsadministration\OneDrive\PrimusWeb\Main\primusweb-new\portfolio> I have tried to search for similar problems, but I can't find any. I have also asked chatGPT for any help, but it doesn't lead anywhere. I know it has something to do with the … -
Django models sorting by address
I need to create a model for an Event. The event must have an address so that in the future I can sort the models by address (by city). How to do it? How to sort models by city if the address is written in one line? Or would it be better to make a separate field for the city? class TeamEvent(models.Model): title = models.CharField(max_length=255) logo = models.ImageField(blank=True, null=True) description = models.TextField(null=True, blank=True) date = models.DateTimeField() address = models.CharField(max_length=500, null=True, blank=True) teams = models.ManyToManyField(Team, blank=True, null=True) cat = models.ForeignKey(Category, on_delete=models.DO_NOTHING) def __str__(self): return self.title def get_absolute_url(self): return reverse('TeamEventDetail', kwargs={'pk': self.pk})