Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make elasticsearch query to filter specified user out?
I have no idea how to work with elasticsearch, but what I want to do is this: We have companies, which has applications which are created by users Let's say I have a list of all companies now I want to make a filter that when I'm providing user_id, qs returns only those companies where user didn't create application, so the cases where company.application.user.id = user_id exists should be excluded i tried updating existing qs this way: ` def get_queryset(self): .... user_id = self.kwargs.get('user_id') if user_id: qs_dict["query"]["bool"]["filter"].append( { "bool": { "must_not": [ { "terms": { "company.application.user.id": [user_id], }, }, ], }, }, ) ` but i only see an error because "bool" expects true/false, but gets list ([user_id]) instead -
django.db.utils.ProgrammingError: relation " " does not exist when running pytest
I am experiencing a very funny bug in Django. I have gone every way possible including resetting migrations. I have written a pytest for a Django project however the above error occurs when running. -
Paginator only working for one web page django
Paginator is only working for the first index page but it doesn't work on the profile page def profile(request, profile): cur_profile = User.objects.get(username=profile) user_posts = Posts.objects.filter(creator=cur_profile.id).all().order_by('-id') follow_num = cur_profile.following.all().order_by('id') following_num = cur_profile.followers.all().order_by('id') paginator2 = Paginator(user_posts, 5) page_numberr = request.GET.get(paginator2) page_objj = paginator2.get_page(page_numberr) return render(request, "network/profile.html", { "profile": profile, "cur_profile": cur_profile, "user_posts": user_posts, "follow_num": follow_num.count(), "following_num": following_num.count(), "page_objj": page_objj }) my html is this <div class="pagination"> <span class="step-links"> {% if page_objj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_objj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_objj.number }} of {{ page_objj.paginator.num_pages }}. </span> {% if page_objj.has_next %} <a href="?page={{ page_objj.next_page_number }}">next</a> <a href="?page={{ page_objj.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> My first page had the same variable names so i changed them but it didn't work -
Streaming video delay during openCV rtsp streaming
In 'python - django', I created a video streaming on the HTML screen using rtsp and opencv. Initially, the video is output immediately after running the server, but as time passes, the request time increases when re-outputting a new video?? Because of the delay, the video is output late. Also, when you restart the django server, the video is displayed immediately again at first, but becomes slower over time. I am aware that it may not be a code problem. I am not an English speaker, so please understand any translation errors. ---------views.py---------- video_capture_lock = threading.Lock() def gen(camera_id): video_path = f'rtsp://61.84.128.127:554/chID={camera_id}&streamType=main' with video_capture_lock: if camera_id in camera_dict: camera_dict[camera_id].release() del camera_dict[camera_id] cap = cv2.VideoCapture(video_path) camera_dict[camera_id] = cap while True: success, frame = cap.read() if success: reframe = cv2.resize(frame, dsize=(0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) ret, jpeg = cv2.imencode('.jpg', reframe) frame = jpeg.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') else: print(f"Failed to read frame for camera {camera_id}") cap.release() time.sleep(1) cap = cv2.VideoCapture(video_path) camera_dict[camera_id] = cap def streaming(request, camera_id): return StreamingHttpResponse(gen(camera_id), content_type='multipart/x-mixed-replace; boundary=frame') @csrf_exempt def stop_streaming(request): if request.method == 'POST': camera_id = int(request.POST.get('camera')) if camera_id is not None and camera_id in camera_dict: camera_dict[camera_id].release() del camera_dict[camera_id] return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'error', … -
When a user clicks or select the user profile picture in Django, user details should appear
When I select or click the logged user profile image, a multivaluedict key error appears. I want to be able to show and edit user details. when I call objects.all() it shows all user details,but ineed only logged user detail Here is my view.py def profile(request): if request.session.has_key('id'): uid = request.GET.get('sid') if uid is not None: try: profile = registertb.objects.get(id=uid) return render(request, 'profile.html', {'profile': profile}) except registertb.DoesNotExist: return HttpResponse("User not found.") else: return HttpResponse("Sid parameter is missing.") else: return HttpResponseRedirect('/') And here is my html code: <body> {% if profile %} <form action="/myprofile/?sid={{ profile.id }}/" method="post" enctype="multipart/form-data"> {% csrf_token %} <div id="profile-container"> <input type="file" id="image-input" name="user_image" accept="image/*" onchange="displayUserProfile()"> <img id="profile-image" src="{{ profile.user_image.url }}" alt="Profile Picture"> <label for="name">Name:</label> <input type="text" id="name" name="name" value="{{ profile.User_name }}" placeholder="Your Name" required> <label for="email">Email:</label> <input type="email" id="email" name="email" value="{{ profile.email }}" placeholder="Your Email" required> <!-- Other profile fields --> <button type="submit">Update Profile</button> </div> </form> <script> function displayUserProfile() { var input = document.getElementById('image-input'); var image = document.getElementById('profile-image'); // Assuming you're using FileReader to read the selected image var reader = new FileReader(); reader.onload = function (e) { image.src = e.target.result; }; reader.readAsDataURL(input.files[0]); } </script> {% endif %} </body> </html> So this my code -
Celery instead of Async views with asyncio in django
I am new to django! (So basically i am seeking suggestions for this approach). In my project i had so many views and each view had atleast 1 database i/o and as all my views are synchronous i find this is not efficient way, So to make it efficient :- 1.)I can use asyn views with await asyncio on Database update operations (create, update, delete records), but read operations should be done synchronously as it should be delivered to frontend. 2.)I can use celery tasks to do Database update operations and do DB read operations normally. suggest me which approach is better/efficient and are they both logically same for the above usecase? -
Alignment and Table Issues when Copy-Pasting from Doc to Summernote Editor
I am experiencing alignment and table-related issues when copying and pasting content from a document into the Summernote editor. The issues persist when displaying the data on the website. I believe this is a significant problem that needs attention. Steps to Reproduce: Copy content from a document. Paste the content into the Summernote editor. Observe alignment and table issues. Expected Behavior: I expect the copied content to be displayed correctly in terms of alignment and table formatting on the website. Actual Behavior: While copy and paste from doc it is showing alignment and lot of issues in website. -
how to get internship in technical field? [closed]
how to get internship in technical field in 1 year of college as my dream is to become data scientist what kind of filed i can choose for internship? I have learned python,html,css,javascript and basics in django. I have done two websites using html,css,python and django by using this any possible to get internship in technical field? -
My delete button does not delete the right post
I have this delete button with a dialog on it but the button does not get the id of the post right and I think it always starts to delete from the first post so I end up deleting them all also every user can see the delete button on other users post too I want them to only see the delete button on their own posts with every account that they log in I will appreciate your help my views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .forms import PostForm from .models import post from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin def detail(request, id): poost = get_object_or_404(post, pk=id) return render(request, "posts/detail.html", {"post": poost}) @login_required() def delete(request, id): poost = get_object_or_404(post, pk=id) poost.delete() messages.error(request, f'Post deleted!') return redirect("/") @login_required() def new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): form.instance.author = request.user form.save() messages.success(request, f'Post created!') return redirect("/") else: form = PostForm() return render(request, "posts/new.html", {"form": form }) my post.html (where delete button is) {% if user.is_authenticated %} <a href="#myModal" class="btn btn-danger btn-small" id="deleteButton" data-toggle="modal" data-target="#myModal">Delete <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 16"> <path d="M5.5 5.5A.5.5 0 0 1 … -
Determining the index of an item in a ManyToManyField and performing an operation from that
I've been working with Django and I can't perform an operation based on the index of an item in a ManyToManyField. I have the following code block {% load mathfilters %} {% for article in articles %} <a href="{{ article.get_absolute_url }}">{{ article.article_title }} - {% for i in article.article_author.all %} {% if i == article.article_author.all.{{article.article_author.all.answer_set.count|sub:1}} %} {{i}}, {% else %} {{i}} {% endif %} {% endfor %} </a> {% endfor %} I want it to display a comma after the author's name indicating that there is another author, but only if that author is not the last author listed in the ManyToManyField. I cannot figure out how to get this to work. -
Django Progress bar and results backend not updating even though the celery worker shows updates?
I'm new to using Celery with Django and using RabbitMQ as a message broker, and I'm having trouble being able to get a progress bar of sorts working. I have a function in the views.py, called running_tagging, which runs a celery task, gpt_manager. With my current setup, the docker containers for RabbitMQ, the celery worker and the django app all spin up without a problem. I can also run the view that triggers the celery task successfully, and see in the celery logs that the job is proceeding as it should. However, the responses that come back when I'm looking at the Network tab in dev tools do not show any updates, and the django admin panel also doesn't show the new task result etc. I'm not 100% sure whether it's an issue, but I've also had trouble with understanding whether I need django-celery or just celery for this, and have been having some issues with version compatibility when trying to install both. If it's any help these are the versions of any packages related to django and celery that I have installed currently: celery==3.1.26.post2 celery-progress==0.3 Django==4.2.7 django-celery==3.3.1 django-celery-results==2.5.1 here is the function from my views.py file: obj_pk = request.session.get('theme_finder_object_pk') … -
Why doesn't django-modeltranslation add fields to the admin panel?
I wanted data in my Django database to be translated to one more language in some cases, and to achieve that I decided to use the django-modeltranslation library. The setup went ok, but the translation fields were never actually added to the models. I followed the installation steps and created a translation.py file with the following content: from modeltranslation.translator import translator, TranslationOptions from .models import * class WorkTranslationOptions(TranslationOptions): fields = ('title', 'text') # Select here the fields you want to translate class CategoryTranslationOptions(TranslationOptions): fields = ('name',) translator.register(Work, WorkTranslationOptions) translator.register(Category, CategoryTranslationOptions) My models.py file looks like this: from django.db import models from django.utils import timezone # Create your models here. class Category(models.Model): name = models.CharField(max_length=20, unique = True) def __str__(self): return f"{self.name}" class Work(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) app_name = models.CharField(blank=True, null=True, max_length=50) title = models.CharField(max_length=50, blank=False) date = models.DateField(blank=False, null=False, default=timezone.now) icon = models.ImageField(upload_to='works/', blank=False, null=False) text = models.TextField(blank=False) url = models.CharField(blank=True, null=True, max_length=50) def __str__(self): return f"{self.title}" Running the python manage.py makemigrations command went fine and returned no exceptions, as well as the migrate command: screenshot But for some reason none of those fields were actually added to the models: I can't see them in the admin panel. How … -
Django admin does not access after authenticate with custom User
I create a custom model for User, By this I can create superuser from command line, and its create successfully. But when I try to login in django admin it does not redirect to the django admin itself. I already verified that it is authenticating properly. Here is the backend authentication created from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.db.models import Q User = get_user_model() class AuthBackend(ModelBackend): supports_object_permissions = True supports_anonymous_user = False supports_inactive_user = False def get_user(self, nif): try: return User.objects.get(nif=nif) except User.DoesNotExist: return None def authenticate(self, request, username=None, password=None, **kwargs): print('inside custom auth') try: user = User.objects.get( Q(nif=username)) print(user) except User.DoesNotExist: print('teste') return None if user.check_password(password): print('ok', user, password, **kwargs) print(self.user_can_authenticate(user)) return user else: print('nok', user, password) return None My app is on apps/usuarios. Here is my configuration on settings: DEBUG = True ALLOWED_HOSTS = [] AUTH_USER_MODEL = "usuarios.User" AUTHENTICATION_BACKENDS = [ #"django.contrib.auth.backends.ModelBackend", "apps.usuarios.backend.AuthBackend", ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.usuarios.apps.UsuariosConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'setup.urls' I think it is a problem with redirection but I can't figured what is causing this. What I am missing? In the authentication … -
Django not processing javascript files
New to django here. I'm having trouble connecting with javascript code from django python. I think I've followed the documentation on project configuration. HTML template: <!DOCTYPE html> <html lang="en"> <body> Test template<br> {% csrf_token %} {% load static %} {{ form | safe }} <script type="text/javascript" src="{% static '/grid_1/test_script.js' %}"></script> Test template end<br> </body> View function: def test_view(req: djhp.HttpRequest): form = forms.TestForm(); vals = dict() vals["test_val"] = "This is a test" return djsc.render(req, "test_template.html", vals) JavaScript code: alert("test script start") var x = "{{ test_val }}" alert(x) The second javascript alert displays "{{ test_val }}" instead of "This is a test". So it looks like django is not processing the .js file. Any help for this newbie is much appreciated! -
I cannot perform migrations in django + docker + postgresql
I have two Docker containers on a virtual machine with Debian OS - one with Django and the other with PostgreSQL. Here is the code of the docker-compose.yml file: version: "3.9" services: server: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app/ networks: - my_network ports: - 8000:8000 depends_on: - pgdb pgdb: image: postgres networks: - my_network environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: pgdb volumes: - pgdbdata:/var/lib/postgresql/data/ ports: - 5432:5432 volumes: pgdbdata: null networks: my_network: driver: bridge Here is an excerpt from the settings.py file responsible for connecting to the database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'pgdb', 'PORT': '5432', } } When I run docker-compose up, both services start without errors. I can connect to my database from outside using pgadmin and access my website. However, when I attempt to run migrations in Django, it raises an error: django.db.utils.OperationalError: could not translate host name "pgdb" to address: Name or service not known. Originally, I didn't specify in Docker Compose that these containers belong to the same network. Attempting to add the same network to both of them didn't make any difference. -
LookupError: App <name_app_django> doesn't have a <Class_name_model> model
I have a problem when refactor existing project in Django from collection of all models from different applications into one models.py file, as the models were duplicated with different variations of the fields so after I commented the models in the stat_table app which I moved to the common models.py I got an error: LookupError: App 'stat_table' doesn't have a 'SolarStationAddInfo' model. Problem: LookupError: App 'stat_table' doesn't have a 'SolarStationAddInfo' model how fix it ? For answer and advice by this error and topics i not found how to fix in my case, and I want to share the solution to this error and what led to it by community maybe the solution will help someone Solution: As it turned out, when starting the stat_table application, the Redis data was accessed using the 'stations' key, and objects of the SolarStationAddInfo class were packed into it And these Redis objects were created before my refactoring (by import that referred to the old models.py file in the stat_table application). The solution turned out to be quite simple: change the imports to the SolarStationAddInfo class launch the function that recreated it Redis objects by the key 'stations' and now, when accessing Redis, the … -
Problem changing format in django project
I have a problem with frontend development. Let me bring you up to date: I have a table on the site that imports data from the database, I need this data to be changed by an operator, I created a Change button after which a popup appears, in the Date field I was able to change the format and screw the date selection through the calendar, but I changed the format in the Estimated time field It doesn’t work in any way, it always says Invalid date.I'm new to programming, so don't judge too harshly :) Thanks for your time Here's the code: </thead> <tbody> {% for order in orders %} <tr> <td>{{ order.status }}</td> <td>{{ order.date|date:"Y-m-d"}}</td> <td>{{ order.preferred_time|time:"H:i" }}</td> <td>{{ order.cargo_type }}</td> <td>{{ order.cargo_quantity }}</td> <td>{{ order.order_number }}</td> <td>{{ order.cargo_weight }}</td> <td>{{ order.driver_name }}</td> <td>{{ order.vehicle_license_plate }}</td> <td>{{ order.vehicle_type }}</td> <td>{{ order.shipper }}</td> <td>{{ order.transport_company_name }}</td> <td> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editOrderModal" onclick="openEditModal('{{ order.id }}', '{{ order.status }}', '{{ order.date }}', '{{ order.preferred_time }}', '{{ order.cargo_type }}', '{{ order.cargo_quantity }}', '{{ order.order_number }}', '{{ order.cargo_weight }}', '{{ order.driver_name }}', '{{ order.vehicle_license_plate }}', '{{ order.vehicle_type }}', '{{ order.shipper }}', '{{ order.transport_company_name }}')">Edit</button> </td> </tr> {% endfor %} </tbody> </table> … -
Как достать Id запроса у юкассы [closed]
Короче суть вопроса.У меня есть админка и туда приходят новые заказы,но они туда приходят в любом случае,успешно ли либо не успешно оформлен заказ,в чем суть мне нужно проверять статус заказа после его оплаты и добавлять данные в админку,но чтобы проверить статус заказа нужно запомнить id самого заказа,во первых даже если я пытаюсь его запомнить таким образом payment_id = request.POST.get('payment_id'),то ничего не выходит(payment_id = request.POST.get('id') так тоже).Так Payment.find_one(payment_id) он выводит такую ошибку ValueError at /orders/create/ Invalid payment_id value payment_id = request.POST.get('payment_id') payment = Payment.find_one(payment_id) if payment_id.status == 'succeeded': то есть по сути я хочу вот так сделать,но каждый раз выходит ошибка.Помогите пожалуйста,уже очень долго мучаюсь с этим,если что это Юкасса -
Web scraping from cardboard.market and want to pull the cheapest price value for any given search
I am developing a website using Django for sports cards and my goal is to be able to display the lowest price of any given card using Selenium with ChromeDriver. For example I am using the soccer player David Seaman from the card set 1990 Pro Set. I created a function that should go to https://cardboard.market/, search for the card, sort by the lowest price first, then pull the value of the first card in the results (this is the cheapest card). It currently is not working, it is returning a blank error message that looks like this: Error: Message: Any ideas of what the problem could be or if there are any other ideas of accomplishing this goal please let me know! This is what I currently have: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def get_lowest_card_price(card_name): base_url = "https://cardboard.market/" search_url = f"{base_url}search?q={card_name}" try: # Set up ChromeDriver driver_path = "C:/Webdrivers/chromedriver.exe" service = ChromeService(driver_path) driver = webdriver.Chrome(service=service) # Navigate to the search URL driver.get(search_url) # Wait for the sorting button to be clickable sorting_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CLASS_NAME, … -
How to install django specific version?
how To install specific Django Version i am getting only latest django version and i want an older version for my project work and that specific version is required for my working enviornment want to downlod Django older version -
Should I use chunks() or save() to save files in Django?
I'm a little confused. When saving an uploaded file in Django should I save it using FileSystemStorage( fs.save() ) or should I use chunks? I just want to ensure that I use chunking to save files that are large so that they don't impact performance. But I'm also reading here that files over 2.5MB are streamed to memory by default so does that make chunking obsolete? -
Why is my Multiple Select Field only returning one value?
I am a beginner in Django and web development in general. I have this page in which the user will choose which tags they'd like to search for and the program will search for images which contain that tag. Here's the form page: <form action="{% url 'search' %}" method="post"> {% csrf_token %} <select name="psearch" id="psearch" multiple> {% for tag in tags %} <option value="{{tag.name}}">{{tag.name}}</option> {% endfor %} </select> <button type="submit">Search</button> </form> Which produces this: However, when I try to obtain the choices for the actual search it seems to only return one value. Here's the actual view which will require this information. def search_view(request): if request.method == 'POST': psearch = request.POST['psearch'] images = Image.objects.filter(tags__name = psearch) return render(request, 'search.html', {'psearch':psearch, 'images': images}) else: return render(request, 'search.html', {}) I have tried printing the actual result of psearch, for testing, here's an example: I selected 'Praia' and 'Barco', however the according to the terminal outcome was just Barco: How can I make this return as a list of all selected objects? -
NoReverseMatch at /seller_page/2/
by clicking the close button only the seller should be able to close the auction, but here the keys are displayed for everyone and when you click on them, this error occurs. What's wrong? File "C:\Users\Desktop\work on it\commerce\auctions\views.py", line 195, in seller_page return render(request, 'auctions/product_detail.html', {'seller_offers': seller_offers}) Thanks in advance for taking the time to respond:) views.py: def seller_page(request, product_id): seller_offers = get_object_or_404(Bid, pk=product_id) if request.method == 'POST': offer_id = request.POST.get('offer_id') offer = get_object_or_404(Bid, pk=offer_id) offer.is_closed = True offer.save() return render(request, 'auctions/product_detail.html', {'seller_offers': seller_offers}) product_detail.html: <ul> {% for offer in offers %} <li>{{ offer.user.username }} offered ${{ offer.offered_price }}</li> <form method="post" action="{% url 'seller_page' offer.id %}"> {% csrf_token %} <input type="hidden" name="offer_id" value="{{ offer.id }}"> <button type="submit">Close Offer</button> </form> {% endfor %} </ul> urls.py: path('seller_page/<int:product_id>/', views.seller_page, name='seller_page'), -
What can I do to accept only one image in the image field in the django admin panel
class Image(models.Model): title = models.CharField(("title"), max_length=50,blank=True) image = models.FileField(("image"), upload_to=generate_filename, max_length=100) def __str__(self): return self.title In the admin panel, images can be added to this section more than once, what I want is to enter an image only once and then remove the add image button. accept only one image How can I do this? -
Loop through list of tupples and return matching tupple value in Django
I have been struggling with this for hours, I have a variable : numbered_objects = [(index + 1, obj) for index, obj in enumerate(carts)] that makes me a list like this from my Model : [(1, <CalculatedNumbers: one>), (2, <CalculatedNumbers: two>), (3, <CalculatedNumbers: three>), (4, <CalculatedNumbers: four>), ...] and I have another variable : 'usernobat' that returns me a number How can I go through my list of tupples, find the matching tupple index that is matching 'usernobat' and return its data ? I have tried for loops like this : matching_object = None for obj in range(len(numbered_objects)): for key in numbered_objects[obj]: if key == usernobat: matching_object = key break but they all return None