Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Сelery starting task every milisecond
Celery task schedule worked fine considerate amount of time. Now one of tasks launches and finishes successfully every couple of milliseconds. Did some search at git/stack and found that some older celery versions suffered from this, but now its fixed. Some users experienced this problem due to celery and django TZ difference, but this is not the case. celery version - 5.2.7 broker - redis flower screen -
The transition effect in in sign in and sign up page not working in django
My friend created a Sign in and sign up page which changes dynamically [https://github.com/codecxAb/anytimeFitness] I have done the django integration but it doesn't seem to change dynamically and instead giving and error "GET /signin/%7B%%20static%20'js/signin.js'%7D HTTP/1.1" 404 2792 My django project [https://github.com/RynoCODE/Gym-Website] -
Django graphene performance issue not related to the db but to the rendering
In Sentry APM I am able to see that most of the time spent was in the view.render I am assuming that this part is where the result from the db are being formatted but can't understand why it is taking a lot of time: -
Like count not showing in html and want to know if my models are set up properly
This is my models.py and index.html and views.py I tried the above and I am expecting to get total like count in my index page but i am only getting 0 likes why is that happening. And how do I fix it. `from django.contrib.auth.models import AbstractUser from django.db import models from datetime import datetime from django.contrib.auth import get_user_model class CustomUser(AbstractUser): profile_picture = models.ImageField( upload_to="profile_pics/", blank=True, null=True ) # Add any other custom fields as needed def __str__(self): return self.username class Post(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=1000) content = models.TextField() created_at = models.DateTimeField(default=datetime.now, null=True, blank=True) likes = models.ManyToManyField( get_user_model(), related_name="liked_posts", blank=True ) class Like(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return f"{self.user.username} likes {self.post.title}"` and this is my index.html `{% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <h2>Welcome to the Home Page!</h2> {% for post in posts %} <!-- Display post details as needed --> <div> <h3>{{ post.title }}</h3> <small>{{post.created_at}}</small> <p>{{ post.content }}</p> <form id="likeForm{{ post.id }}" data-post-id="{{ post.id }}" method="post"> {% csrf_token %} <input type="submit" value="Like post"> <span id="likeCount{{ post.id }}">{{ post.likes.count }}</span> Likes </form> </div> {% endfor %} <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function () { $('form[id^="likeForm"]').submit(function (event) { … -
Django Auth Ldap on Windows
Is there any way to make django ldap authentication I am trying to pip install django-auth-ldap but keep getting Could not build wheels for python-ldap, which is required to install pyproject.toml-based projects then I searched and find this project but those settings configuration wont work. Reading docs. but when I try to install ldap but it isn't working... Any help would be appreciated, thanks from now :) I've tried installing django-auth-ldap and django-python3-ldap but neither installing or configuring didn't work... -
Calculating fees for smart contracts, such as USDT-TRC20, on the Tron blockchain
I'm currently engaged in a blockchain project, and one of the key components involves the creation of withdrawal transactions. However, I'm facing the challenge of displaying the transaction fee before broadcasting it to the blockchain. I am well aware of the intricacies involved in calculating smart contract fees on the Tron blockchain. Do you have any suggestions on how to obtain the necessary energy and bandwidth for a withdrawal and how to calculate the transaction fee? I am using tronpy and haven't found a helpful method for this purpose I did not found any helpful way for get contracts fee -
Django Q implement to send periodic emails
I have a Django project with several merchant accounts. When they log in using a URL, a certain view is called that aids with login and authentication. In addition, the same method determines if the merchant's plan expires in a month. If so, the function notifies you by email about the same problem. The problem now is that the view function won't execute if the user doesn't log in, which means he won't get any mail. Can I then have an automatic feature that delivers the mail and verifies each merchant? To notify merchants of their plan expiration even if they don't log in, I want a function in Djnago-Q to run even if the URL is not hit and after a set amount of time. -
Django Custom User Model Admin
In a simple self-training using Django, I'm facing the following problem: 1- I've written a custom user model with two extra fields: phone +fuck 2- I've created a custom admin using custom forms 3- In settings: added AUTH_USER_MODEL = "accounts.CustomUser" where accounts is the app name 1- In admin panel, when trying to add a new user, it doesn't display any of the extra fields and this is a problem, also in the case of editing an existing user. 2- In admin: the last statement is: admin.site.register(CustomUser, CustomUserAdmin) but if i replace it with: admin.site.register(CustomUser), every thing is well and it executed as expected enter image description here [[enter image description here](https://i.stack.imgur.com/qgh3r.png)](https://i.stack.imgur.com/mXrK4.png) -
Create a for loop in python django with 20 teams of 100 matches of 10 rounds of matches
Create a for loop in Python Django with 20 teams, each playing 100 matches of 10 rounds. Ensure that no matches are repeated, and in each rounds, no teams are repeated across the 10 rounds. if n == 2: pair = [(1, 3), (4,5), (6,7), (8,9), (10,11),(12,16),(14,15),(13,17),(18,19),(2,20)] elif n == 3: pair = [(12,13), (16,17), (2,8), (9,14), (4,19),(10,15),(5,11),(14,20),(1,7),(3,18)] elif n == 4: pair = [(4,6), (5,7), (8,10), (15,20), (13,16),(14,18),(3,9),(1,19),(2,12),(11,17)] elif n == 5: pair = [(12, 15), (7, 9), (17, 19), (4, 8), (6, 10), (13, 18), (2, 3), (14, 16), (11, 20), (1, 5)] elif n == 6: pair = [(10, 13), (5, 9), (2, 7), (14, 19), (1, 8), (6, 12), (17, 20), (4,18), (11, 15), (3, 16)] elif n == 7: pair = [(4, 15), (9, 20), (3, 14), (1, 10), (7, 17), (2, 16), (5, 18), (6, 8), (11, 13), (12, 19)] elif n == 8: pair = [(4, 14), (9, 18), (5, 17), (1, 11), (7, 16), (3, 19), (6, 20), (8, 15), (10, 17), (2, 13)] elif n == 9: pair = [(3, 13), (9, 19), (1, 16), (5, 10), (6, 11), (2, 4), (8, 12), (7, 14), (15, 17), (18, 20)] elif n … -
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 :( …