Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Button troubleshooting in Django
By pressing the button, the sale is over and the highest price is announced as the winner. Here, the button performs the function of the button defined at the beginning of the template file. views.py: def page_product(request, productid): product = get_object_or_404(Product, pk=productid) off = Bid_info.objects.get(product=product) bid_max = Bid_info.objects.filter(product_id=productid).latest('bid_price') if request.user == off.seller: close_button = True off.bid_price = bid_max Bid_info.checkclose = True messages.success(request, f"The offer was closed at {bid_max} $") else: close_button = False context = { 'product' : product, 'form': form, 'off' : off, 'close_button' : close_button, 'bid_max' : bid_max } return render(request, 'auctions/page_product.html', context) def bid(request, bidid): product = get_object_or_404(Product, pk=bidid) if request.method == 'POST': user = request.user if user.is_authenticated: bid_price = Decimal(request.POST.get("bid_price", False)) other_off = Bid_info.objects.filter(product=product).order_by("-bid_price").first() if Bid_info.checkclose == True: messages.warning(request, "it sells.") else: Bid_ = Bid_info(product=product, seller=request.user, bid_price=bid_price) Bid_.save() return redirect('page_product', bidid) page_product.html: <form method="post"> {% csrf_token %} {% if close_button %} <button type="submit" class="btn btn-primary">Close</button> {% else %} <p> {{off.seller}} is seller!</p> {% endif %} </form> -
Trying get excel table with using padnas from django project
I try get data from table in my Django project from local server But have a problem after run programm with pandas code: c:\Users\kadzutokun\Desktop\tables.py:3: FutureWarning: Passing literal html to 'read_html' is deprecated and will be removed in a future version. To read from a literal string, wrap it in a 'StringIO' object. tables = pd.read_html( C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py:666: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup. soup = BeautifulSoup(udoc, features="html5lib", from_encoding=from_encoding) Traceback (most recent call last): tables = pd.read_html( File "C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py", line 1245, in read_html return _parse( File "C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py", line 1008, in _parse raise retained File "C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py", line 988, in _parse tables = p.parse_tables() File "C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py", line 248, in parse_tables tables = self._parse_tables(self._build_doc(), self.match, self.attrs) File "C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py", line 603, in _parse_tables raise ValueError("No tables found") ValueError: No tables found PS C:\Users\kadzutokun> & C:/Users/kadzutokun/AppData/Local/Programs/Python/Python310/python.exe c:/Users/kadzutokun/Desktop/tables.py c:\Users\kadzutokun\Desktop\tables.py:3: FutureWarning: Passing literal html to 'read_html' is deprecated and will be removed in a future version. To read from a literal string, wrap it in a 'StringIO' object. tables = pd.read_html( C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py:666: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass … -
Html Not Rendering in Django
I have a simple Html with CSS which I am trying to render using urls.py and views.py from django.shortcuts import render import re # Create your views here. # checks valid email def is_valid_email(email): # Define the regex pattern for email validation pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' return re.match(pattern, email) def home(request): return render(request,'index.html') def signup(request): return render(request,'signup.html') def signin(request): return render(request, 'signin.html') and the urls.py being from django.urls import path from . import views urlpatterns = [ path('', views.home), path('signup/', views.signup), path('signin/', views.signin), ] The home is rendering successfully but the signing and signup is not rendering showing the following error I have urls.py on project level as from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) would appreciate any help!!! -
When checking data in the Django REST Framework, a TypeError error is detected: string indexes must be integers
Ошибка при валидации данных в Django REST Framework с использованием метода validate_qr Я пытаюсь провести валидацию данных в Django REST Framework с использованием метода validate_qr, но столкнулся с ошибкой TypeError: string indices must be integers. Код метода validate_qr: def validate_qr(self, data): cat = data['category'] cat_int = int(cat) pr = data['price'] pr_int = int(pr) di = data['id'] di_int = int(di) if data['qr'] != f"{cat_int}C{pr_int}P{di_int}I": raise serializers.ValidationError("QR код не соответствует стандартам") return data` ` Проблема: При попытке преобразовать строковые индексы в числа для доступа к данным в словаре, получаю ошибку. Я пробовал использовать int() для преобразования строковых значений в числа, но это не решило проблему. Вопрос: Как мне правильно выполнить валидацию QR кода, учитывая указанную ошибку? -
Automated mail in Django
I have a Django project and multiple merchant accounts when they log in via a URL, a particular view is called which helps in authentication and login. The same function also checks whether the merchant's plan will expire in a month. If yes the function sends an email referring to the same issue. Now the issue is if the user never logs in the view function runs and hence he never receives the mail. So can i have a automated function which checks for every merchant and delivers the mail. I want a function that runs even if the URL is not hit, and after specific time interval, so merchants should be notified about their plan expiry, even if they don't login. -
how to use supervisord module to run celery worker in python django in production cpanel
I want to use celery for sending mail Asynchronoulsy I donot know whats the problem if any one knows how to solve this please help me I have done it using celery sending mails Asynchronoulsy but when I use it in production it is not working and I donot know how to run two terminal at a time -
TypeError: requires_system_checks must be a list or tuple. in Django - `python manage.py harvest`
I'm trying to integrate Aloe for BDD testing in a Django 5.0 project, but I'm encountering a TypeError related to requires_system_checks. This issue arises when I attempt to run Aloe tests using the command python manage.py harvest. Here are the details: Environment: Django Version: 4.2.8 Aloe Version: 0.2.0 Python Version: 3.9 Django Settings: In my settings.py, I have the following setup for testing: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'aloe_django', 'django_nose', 'rest_framework', 'ad_manager', ] TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' When I run python manage.py harvest, I encounter the following error: Traceback (most recent call last): ... File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 284, in __init__ raise TypeError("requires_system_checks must be a list or tuple.") TypeError: requires_system_checks must be a list or tuple. **Attempts to Resolve: ** I've confirmed that Aloe is correctly installed and appears in the installed apps. I've also tried running the tests without specifying a custom test runner, but the issue persists. **Questions: ** What could be causing this TypeError in Django 4 when running Aloe tests? Is there a specific configuration or setup required for Aloe to work with Django 4? Has anyone else encountered this issue with Aloe and Django, and how was it resolved? Any help or … -
The request is delayed until it reaches the middleware
I am using the Django Framework, and every time I deploy to production, there's a temporary delay of requests before they reach the middleware. What can I check to identify the cause of this issue? -
why pagination buttons appear vertically?
I made these pagination buttons but they appear like this picture and not beneath my posts what should I do? if I need to upload another part of code please let me know They look like this welcome.html {% extends 'base.html' %} {% block title %}My Blog{% endblock %} {% block content %} {% for post in posts %} {% include 'posts/post.html'%} {% endfor%} {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a> {% endif %} {% endif %} {% endblock %} views.py from django.shortcuts import render, redirect from django.http import HttpResponse from datetime import datetime from posts.models import post from django.contrib.auth import authenticate, login from django.contrib import messages from django.contrib.auth.decorators import login_required from django.views.generic import ListView # Create your views here. … -
django rest framework, how to protect my API? [duplicate]
I have an API that uses django-cors-headers to limit its access. This works up to a certain point, however, if I try to make a GET request directly in the browser or using any script, like the requests library for example, I can get a response with status 200 and with all the data from the endpoint. How can I protect my API so that it cannot be accessed by anyone? I tried configuring django-cors-headers in different ways, but it doesn't work. -
How to add item in cart and display it without refresh?
I have a button which adds item to the cart. How do I fix my code to display item on html page if quantity is less than one? Now my code adds item on the server and send Json Object to the client, but it doesn't show on the page. Seems like I need to display item with AJAX and JQUERY? I am quite new to Jquery and Ajax, so I'd be grateful to find a solution here! base.html {% if cart|length == 0 %} <div class="card-basket__body prod-tab" id="test"> <div class="prod-tab__body"> <p style="margin-top:20px;">В настоящий момент в корзине нет товаров...</p> </div> </div> {% else %} {% for item in cart %} <div class="card-basket__head"> <div class="card-basket__point" id="productAmount_{{item.product.id}}">{{ item.quantity }} шт.</div> <div class="card-basket__remove" data-type="popup-remov">Delete</div> </div> <div class="card-basket__body prod-tab"> <div class="prod-tab__body"> <div class="prod-tab__name"> <picture> <source srcset={% static item.product.image.first %} type="image/webp" /> <img src={% static item.product.image.first %} alt="" class="prod-tab__img" /> </picture> <div class="prod-tab__about"> <h3>{{ item.product.name }}</h3> <p class="prod-tab__category">{{ item.product.category }}</p> <p class="prod-tab__category" id="ID_ml">{{ item.product.ml }} мл.</p> <div class="price">{{ item.product.price }} RUB</div> <div class="quantity__row"> <form action="{% url 'remove_cart' %}" method="post" class="removeCartClass"> {% csrf_token %} {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.update }} <input type="hidden" name="product_id" value="{{ item.product.id }}" id="remove_{{item.product.id}}"> <input type="submit" value="-" class="quantity__number-minus"> </form> <span class="quantity__input" id="quantityID_{{item.product.id}}">{{ item.quantity … -
Why is my page either not loading anything or giving me Template does not exist error? Django-React integration
The templates section in settings.py Static files path File structure indes.html urls.py error `I believe the error is occuring either because my static files aren't loading correctly or my routes are bad and index.html is just not getting picked up at all, as mentioned I do get a blank page this happens when I just put index.html in quotation marks in urls.py. I tried changing the file paths and fixing it, making sure css mime type is css and am expecting the page to load which either gives me an error or a blank screen.` -
error: src refspec main does not match any error: failed to push some refs to 'github.com:dani75576vjh/REG_APIS.git'
git add . 2. git commit -m "Your Message Here" 3. git push origin main Method 2 Commands 1. git add . 2. git commit -m "Your Message Here" 3. git push origin HEAD:main Method 3 Commands 1. git add . 2. git commit -m "Your Message Here" 3. git push origin HEAD:master , what should error: src refspec main does not match any error: failed to push some refs to 'github.com:dani75576vjh/REG_APIS.git' -
Using Mezzanine (Django) and updating to django 5.0 : I get "TypeError: QuerySet._clone() got an unexpected keyword argument '_search_terms'"
I'm installing mezzanine vie netbsd packages because I found that's the easiest for netbsd. I'm stuck on the following error message. I've found great answers for every other upgraded code like modules that have changed. I am consulting the django docs, but I thought I'd start by asking in this forum how to change the code to give the right search terms. I assume that changinge mezzanine/core/managers.py is the way to go. I've used mezzanine for a long time and hope that it gains new life. An anecdote: I got hired to manage an electric assist cargo bike company for a home valet compost service and I found that the management used mezzanine(django) for their website. When I asked about contributing to the website, the young snobs snubbed me without giving me a chance. but anyway: TypeError: QuerySet._clone() got an unexpected keyword argument '_search_terms' I haven't tried anything here other than researching the source code. I will keep exploring it. -
How can I access foreign key methods in a Django model?
I have a table Product which contain only the price of the products and a table Discount which contains the percentage of the discount associated to the products. I want to access the function apply_percentage in the final_price method. In the real code I have different type of Discount for each product, the situation explained is a generalization to let you understand the problem. This is my models.py file: class Product(models.Model): price = models.FloatField("Price") def final_price(self): **return apply_percentage(self.price)** class Discount(models.Model): percentage = models.FloatField("Percentage") product = models.ForeignKey(Product) def __str__(self): return self.percentage def apply_percentage(self, price): return (price - (price*self.percentage)) I use Django (4, 1, 12, 'final', 0) with Python 3.10.12. Thank you very much in advance! -
Django - TemplateSyntaxError: 'socialaccount' is not a registered tag library while running tests
I'm trying to run Django tests but I'm encountering with this error - django.template.exceptions.TemplateSyntaxError: 'socialaccount' is not a registered tag library., but normally it have to work because I'm using custom settings while running tests. I have 2 authentication methods: default Django's auth and allauth's "Login with google". I wanna test only Django's default auth and not allauth login. For that, I'am using tests_settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', # I'm using here only needed apps 'apps.userauth', 'apps.spacefy', ] IS_TEST_CONFIG = True # I just override existing settings.py Here is my view I wanna test: class CustomLoginView(LoginView): form_class = CustomAuthenticationForm redirect_authenticated_user = True template_name = 'apps.userauth/login.html' success_url = "home" def get_context_data(self, **kwargs): context = super(CustomLoginView, self).get_context_data(**kwargs) context['is_test'] = settings.IS_TEST_CONFIG def form_invalid(self, form): messages.error(self.request, message=( "Please enter a correct email and password.Note that both fields may be " "case-sensitive. (You can also try to login with google)")) return self.render_to_response(self.get_context_data(form=form)) Actually my tests:: class TestCustomLoginView(TestCase): def setUp(self): CustomUser.objects.create_user( email='test@gmail.com', password='<PASSWORD>' ) self.email = "test@gmail.com" def test_form_invalid(self): response = self.client.post(path='/auth/login/', data={ 'email': self.email, 'password': 'invalid_password' }) self.assert ... Also I'm using if statement in my template to prevent the errors like I'm encountering (but it doesn't work :( … -
403 Authentication Credentials not provided NextJS Django
FRONTEND: useEffect(() => { async function fetchProfile() { try { const response = await fetch("/api/user_profile", { headers: { 'Content-Type': 'application/json'}, credentials: 'include' }); const data = await response.json(); setUserProfile(data); } catch(err){ console.error("Error fetching profile data", err); } } fetchProfile(); },[]); useEffect(() => { // Log the user profile state console.log(userProfile); }, [userProfile]); import { cookies } from 'next/headers' export async function GET(request: Request) { const cookieStore = cookies(request); const sessionID = cookieStore.get('sessionid')?.value; const csrfToken = cookieStore.get('csrftoken')?.value; const response = await fetch('http://127.0.0.1:8000/auth/profile/', { headers: { 'Content-Type': 'application/json', 'Cookie': `sessionid=${sessionID}; csrftoken=${csrfToken}`, }, }); const response_data = await response.json(); return Response.json({ response_data }); } BACKEND: class UserProfileView(views.APIView): permission_classes = [permissions.IsAuthenticated] def post(self, request, *args, **kwargs): user_profile, _ = UserProfile.objects.get_or_create(user = request.user) serializer = UserProfileSerializer(user_profile, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, *args, **kwargs): user_profile = get_object_or_404(UserProfile, user=request.user) serializer = UserProfileSerializer(user_profile) return Response(serializer.data) class LoginView(views.APIView): permission_classes = [permissions.AllowAny] def post(self, request, *args, **kwargs): username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user is None: return Response({'error': 'Invalid Credentials'}, status=status.HTTP_401_UNAUTHORIZED) login(request, user) return Response({'message': 'User logged in successfully'}) The problem is I cannot access my user profile endpoint even with passing the details. I have a … -
Using pytest to test django packages
I have created a Django package (a Django App) that adds functionality to Django when installed and referenced in settings.py INSTALLED_APPS of the Django project. I am familiar with writing tests for Django using pytest, and the pytest-django plugin. As the pytest-django plugin provide fixtures such as a web client to interact with the django project. However I never wrote tests for a Django package. How do I use pytest and pytest-django plugin to test my Django package, without having a real django project that has settings.py that loads the package? -
How can i set dependencies between event after data load in scheduler pro in bryntum?
In Bryntum Scheduler Pro, in project object i load data by a url then i set dependencies between event by dependency_dict(which i pass from my backend) i try this code, but it show error like TypeError: scheduler.dependencies.addDependency is not a function, How can i set dependency between event after load data? project: { transport: { load: { url: path, } }, listeners: { load: function (project) { var response = project && project.response; var dependency_dict = response.dependencies.rows; if (dependency_dict) { dependency_dict.forEach(function (dependency) { scheduler.dependencies.addDependency(dependency.fromEvent,dependency.toEvent); }); } }, }, autoLoad: true, resourceStore: { modelClass: ResourceModel }, eventStore: { modelClass: EventModel, }, } i also try this var dependency_dict = response.dependencies.rows; if (dependency_dict) { dependency_dict.forEach(function (dependency) { project.dependencyStore.add(dependency); }} give me same error TypeError my backend code : https://codefile.io/f/lXVaNcJZ4z my scheduler pro code : https://codefile.io/f/OZFfMIHQ3H -
Set table width with pandas set_table_styles
I'm trying to set the table width using set_table_styles, but it doesn't work. I tried to find information about this in the documentation, but there is no example there. I looked into this issue, but it didn't help either. https://stackoverflow.com/questions/74046791/set-width-to-100-fill-container-with-pandas-set-table-styles Part of my code: turnover = pd.pivot_table(data_for_turnover, columns=['Date'], values=['Turnover', 'Sales', 'Stocks'], aggfunc='sum') table_style = {'selector': 'table','props': [('width', '100%')]} turnover = turnover.style.format('{:.0f}') turnover.set_table_styles([table_style]).to_html() Next I display using Django, but the width (I also tried change border, margin) does not change. If I try to change the th or td styles, they are applied. Please help me find, if not a solution, then a reason. -
Django Channels Web Socket Connection Keeps Closing
I created the following consumers in my django application to handle real time notifications: class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = f"notification_{self.scope['url_route']['kwargs']['user_id']}" await self.channel_layer.group_add(self.room_name, self.channel_name) await self.accept() # other methods below and i have my routing to this consumer here: from django.urls import re_path, path from .consumers import NotificationConsumer websocket_urlpatterns = [ path('notification/<int:user_id>/', NotificationConsumer.as_asgi()), ] Then i am connecting to this in the frontend with javascript: const websocketProtocol = window.location.protocol === "https:" ? "wss" : "ws"; const wsEndpoint = `${websocketProtocol}://${window.location.host}/notification/{{request.user.id}}/`; const socket = new WebSocket(wsEndpoint); socket.onopen = (event) => { console.log("WebSocket connection opened!"); }; socket.onclose = (event) => { console.log("WebSocket connection closed!"); }; It works locally on my computer but when i hosted it on a live domain, each time i load the page where this web socket was created, i get the following error in the console: tutor-message-list/:236 WebSocket connection to 'wss://www.youvarsity.org/notification/2/' failed: and then the close event fires off and logs to the console: WebSocket connection closed! It worked locally and i have tried debugging but i do not know how to solve this. Please help -
How to reference to multiple users in Django
I want to create projects page where user can reference multiple users(there no limit to number of users to reference). How can I do that? Is it possible? I thought that i can use for loop but i can't imagine how to do that -
Foreign key constraint failed when changing data form admin panel
i was trying to insert some test data through the admin panel but I keep getting stuck on the FOREIGN KEY constraint failed error. I'm trying to create an Event this is how my class looks: from django.db import models from datetime import datetime, timedelta # Create your models here. class Event(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=200) start_time = models.DateTimeField() end_time = models.DateTimeField() email = models.EmailField(blank=False, max_length=254) phone = models.CharField(max_length=15) def get_events_from_weekday(weekday): index_week = weekday.weekday() week_start = weekday - timedelta(days=index_week) week_end = week_start + timedelta(days=6) return Event.objects.filter(start_time__range=[week_start, week_end]) def get_event_from_start_time(start_time): return Event.objects.filter(start_time=start_time) Also for my customer class i cannot create an object through the admin panel. But I can create a customer through my register page. This is my customer model from django.utils import timezone from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager from django.contrib.auth.models import BaseUserManager from django.core.mail import send_mail from django.conf import settings # Create your models here. class CustomerManager(BaseUserManager): def _create_user(self,name, last_name, email, phone, password, **extra_fields): if not email: raise ValueError('Customers must have an email address') user = self.model( email=email, name=name, last_name=last_name, phone=phone, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self,name, last_name, email, phone, password, **extra_fields): extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_staff', False) return self._create_user(name, last_name, email, … -
Getting 504 error around 15 seconds Django IIS
I am running a Django website o windows server using IIS. The problem is that I am getting 504 gateway error at around 15 seconds (15.3 and 15.6) some times. I have increased IIS Connection time-out to 360 seconds. But the error occurs again and some times it occurs at around 100 s. I want to know what settings has been set to 15, and how should I resolve the problem? -
Why doesn't my Django app work, 404 Page not found
I know somebody has asked this question this is the link to it, but none of the solutions there worked for me so I had to open a new question. When I run my code I get this error message: Using the URLconf defined in storefront.urls, Django tried these URL patterns, in this order: admin/ playground/ The empty path didn’t match any of these. here is my storefront urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')), ] and here is my playground urls.py: from django.urls import path from . import views # URL conf module urlpatterns = [ path('hello/', views.say_hello) ] also here is my playground views.py: from django.shortcuts import render from django.http import HttpResponse def say_hello(request): return HttpResponse('Hello World') Can somebody tell me what could be the problem? Thank you.