Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cache response from a request in python
I'm writing some backend scripts in python that have to be coupled with a web interface that uses django. The web application allows to view layers that comes from different web services. As part of my tasks I developed a tool that request elevation data from a geoserver (a WCS service) and then, based on the a previous line drew by a user in the front end, is able to generate a cross section of the underlying data. So, in short: when a user draws a line over a layer and then clicks draw-profile, my function request the data, intersects the line when the associated raster/layer and returns a figure to the front-end. The problem with that approach is that each time the user clicks draw-profile, the request is made again, which takes some time. When the request is made, the data is stored in a DTM object (class that I made) in a self.raster property. A simplified version of the function that requests the data is shown below. def get_dtm_from_wcs100( self, raster_source: str = "YY", layer: str = "XX", format: str = "image/tiff", version: str = "1.0.0", resx: int = 1, resy: int = 1, ) -> None: """ … -
Telegram chat bot using python-telegram-bot | Messages between clients and operators are being messed
We have 3 operators and I want them to be busy if they entered to chat with someone. When chat is ended with client, operator will be free for other clients and can chat. I accidentally removed the part of code where operator after entering to chat will become busy (is_available=False) and after ending chat becomes available (is_available=True). Stack: Django, python-telegram-bot models.py from django.db import models class CustomUser(models.Model): tg_id = models.IntegerField() tg_first_name = models.CharField(max_length=500, blank=True, null=True) tg_username = models.CharField(max_length=500, blank=True, null=True) name = models.CharField(max_length=500, blank=True, null=True) choosen_lang = models.CharField(max_length=50, blank=True, null=True) phone_number = models.CharField(max_length=50, blank=True, null=True) status = models.CharField(max_length=500, blank=True, null=True) is_operator = models.BooleanField(default=False, blank=True, null=True) is_supervisor = models.BooleanField(default=False, blank=True, null=True) is_available = models.BooleanField(default=True, blank=True, null=True) def __str__(self): return self.tg_first_name class Chat(models.Model): is_closed = models.BooleanField(default=False) client = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='client_of_chat', blank=True, null=True) operator = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='operator_of_chat', blank=True, null=True) created = models.DateTimeField(auto_now_add=True) class Appeal(models.Model): custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) body = models.TextField(blank=True, null=True) def __str__(self): return self.body buttons.py from main.models import * lang_btn = [ ["O'zbek"], ["Русский"], ] main_page_btn_uz = [ ["Savol"], ["Shikoyat"], ] main_page_btn_ru = [ ["Вопрос"], ["Жалоба"], ] chat_btn_uz = [ ['Onlayn opertor'], ] chat_btn_ru = [ ['Онлайн-оператор'], ] main_btn_operator = [ ["Открытие чаты"], ["Закрытие чаты"], ] … -
TypeError: user.models.CustomUser() got multiple values for keyword argument 'email'
So, I'm trying to create a custom user model in Django for a personal project, but the terminal is throwing this error while trying to create a super user via python3 manage.py createsuperuser Traceback (most recent call last): File "/home/Henkan/main_store/manage.py", line 22, in <module> main() File "/home/Henkan/main_store/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 87, in execute return super().execute(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 232, in handle self.UserModel._default_manager.db_manager(database).create_superuser( File "/home/Henkan/main_store/user/managers.py", line 18, in create_superuser return self.create_user(email, password = None, **extra_fields) File "/home/Henkan/main_store/user/managers.py", line 9, in create_user user = self.model(email=email, **extra_fields) TypeError: user.models.CustomUser() got multiple values for keyword argument 'email' Here's the managers.py code; from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password = None, **extra_fields): if not email: raise ValueError('Email is required') extra_fields['email'] = self.normalize_email('email') user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self.db) def create_superuser(self, email, password = None, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) return self.create_user(email, password = None, **extra_fields) -
No static files over Nginx + Django
I know there are many such questions. But I've tried a lot of what I've found and nothing helps. I have a combination of Django + uWSGI + Nginx + PostgreSQL. Static file was collected by python manage.py collectstatic in movies_admin/static directory. I'm logging into Django admin at a local address via nginx 127.0.0.1/admin. The page itself is loaded, but only the text, fields and the like. No graphics - that my problem. My docker-compose file: version: '3' services: django: restart: always build: movies_admin/. env_file: - .env ports: - "8000:8000" container_name: work_django depends_on: - postgres postgres: restart: always env_file: - .env image: 'postgres:${PG_VER}' environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} container_name: work_database ports: - "5432:5432" volumes: - ${DB_VOLUME_CATALOG_PATH}:/var/lib/postgresql/data/ nginx: image: 'nginx:${NGINX_VER}' volumes: - ${NGINX_CONF_FILE}:/etc/nginx/nginx.conf:ro - ${NGINX_CONFD_CATALOG}:/etc/nginx/conf.d:ro - ${STATIC_PATH}:/var/www/static/:ro container_name: work_nginx depends_on: - django ports: - "80:80" I checked. The static directory is mounted in the '/var/www/static/' directory of the nginx container. My site.conf: server { listen 80 default_server; listen [::]:80 default_server; server_name _; location /static/ { alias /var/www/static/; } location @backend { proxy_pass http://django:8000; } location ~* \.(?:jpg|jpeg|gif|png|ico|css|js)$ { log_not_found off; expires 90d; } location / { try_files $uri @backend; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; … -
can't find the page URL
I got the same error while writing code. enter image description here started making this project using a video tutorial on YouTube I think the problem is in the Url files, but I can’t find this problem myself. Essentially the problem is that when I go to the site and press a certain button, this error appears and does not find this page, why? my urls.py there may be a mistake here, but that's for sure from django.urls import path from . import views urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('register/', views.registerPage, name="register"), path('', views.home, name='home'), path('room/<str:pk>/', views.room, name="room"), path('profile/<str:pk>',views.userProfile,name="user-profile"), path('create-room/', views.createRoom, name="create-room"), path('update-room/<str:pk>/', views.updateRoom, name="update-room"), path('delete-room/<str:pk>/', views.deleteRoom, name="delete-room"), path('delete-message/<str:pk>/', views.deleteMessage, name="delete-message"), ] my views.py from django.shortcuts import render, redirect from django.db.models import Q from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth import authenticate,login,logout from .models import Room, Topic, Message from django.contrib.auth.forms import UserCreationForm from .forms import RoomForm #rooms = [ # {'id': 1, 'name': 'Lets learn python!' }, # {'id': 2, 'name': 'Design with me' }, # {'id': 3, 'name': 'Frontend developers' }, #] def loginPage(request): page = 'login' if request.user.is_authenticated: return redirect('home') if request.method == … -
Best approach to build a filterable table with Django
I have created a Template where you have a HTML-table and a iframe that's rendering pdf's that a user has previously uploaded: The goal is that a user can match the table entries to a pdf / multiple pdf's. This part is done. But now I would like to know what's the best approach to filter my table data. I have created the table this way: {% extends "website/base.html" %} {% block content %} {% load static %} {% load evidence_extras %} <script src="{% static 'evidence/matching_final.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'evidence/css/style.css' %}"> <script src='https://cdnjs.cloudflare.com/ajax/libs/axios/1.6.8/axios.js'></script> <div class="container"> {% csrf_token %} <div class="row"> <div class="col-8"> <div class="row"> <div class="col-12"> <table class="table"> <thead class="table-dark"> <td> id </td> ....... </thead> <tbody> {% for piece in transactions %} <tr onclick="handleRowClick(this, {{piece.id}})"> <td> {{ piece.id }} </td> ...... </tr> {% endfor %} </tbody> </table> </div> </div> <div class="row"> <div class="col-12"> <button onclick="handleMatch(this)" class="btn btn-primary" style="width: 100%;">Match</button> </div> </div> </div> <div class="col-4 overflow-scroll" style="height: 60em;"> {% for evidence in evidences %} <div class="row"> <div class="col-12"> <div class="card" id="evidence_{{evidence.id}}"> <div class="card-header">{{ evidence.name}}</div> <div class="card-body"> <iframe src="/evidence/pdf/{{evidence.id}}" id="pdf_frame" width="100%" height="400"></iframe> <ul> <li maxlength="20"> file: {{evidence.file}} </li> <li maxlength="20"> hash: {{evidence.hash}} </li> </ul> <div class="row"> <div class="col-6"> <button … -
Django model.objects.filter SQL searching more columns than given
So I am trying to use this def get_queryset(self, *args, **kwargs): return OrderItem.objects.filter(order_id=self.kwargs['pk']) To search my OrderItem by object and return only the ones linked to a specify order by an order_id. However using the Django debug_toolbar I can see what the sql query is doing and it is doing the following: SELECT "littlelemonAPI_orderitem"."id", "littlelemonAPI_orderitem"."order_id", "littlelemonAPI_orderitem"."menuitem_id", "littlelemonAPI_orderitem"."quantity" FROM "littlelemonAPI_orderitem" WHERE ("littlelemonAPI_orderitem"."order_id" = 2 AND "littlelemonAPI_orderitem"."id" = 2) LIMIT 21 In this case I passed 2 as the PK in my API endpoint but I don't understanding why it is searching by the id when I only want it to search by the order_id. These are my database tables: enter image description here enter image description here Also these are how these two models are defined: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) delivery_crew = models.ForeignKey(User,on_delete=models.SET_NULL,related_name='delivery_crew',null=True) status = models.BooleanField(db_index=True, default=0) total = models.DecimalField(max_digits=6,decimal_places=2) date = models.DateField(db_index=True,auto_now_add=True) def __str__(self): return f"{self.id}" class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADEAlso) menuitem = models.ForeignKey(MenuItem,on_delete=models.CASCADE) quantity = models.SmallIntegerField() class Meta: unique_together = ('order','menuitem') def __str__(self): return f"{self.order_id}"``` And these are the serializers I am and will be using but I am not sure how these would cause this issue: class OrderSerialzier(serializers.ModelSerializer): user = UserSerializer class Meta: model = … -
Python Reply To an email message
I have a Django app which we developed to manage our Hotel reservation inquiries and requests. We are receiving Emails directly from our django-mailbox modal. Now the problem I am facing is that when I receive an email, I want to reply to the same email message so that when the recipient opens that email they can see the previously sent or received message on the same page, like Gmail. How to do that here is my code: def reply_inquiry_email_to_hotel(request, reservation_pk): try: reservation = Reservation.objects.get(pk=reservation_pk) rooms = ReservationRoom.objects.filter(reservation=reservation) hotel = reservation.hotel email_server = CompanyEmailServer.objects.get(company=reservation.company) # Set email settings settings.EMAIL_HOST = email_server.email_server settings.EMAIL_PORT = email_server.email_port settings.EMAIL_HOST_USER = email_server.email_username settings.EMAIL_HOST_PASSWORD = email_server.email_password settings.EMAIL_USE_TLS = email_server.email_use_tls settings.EMAIL_USE_SSL = email_server.email_use_ssl settings.DEFAULT_FROM_EMAIL = "Reservations | " + reservation.company.name_en + " <" + email_server.email_username + ">" subject = f'New Reservation Request No: {reservation.reservation_no} For {hotel.name_en} From {reservation.guest_name} On {reservation.request_date}' html_message = render_to_string('email/message.html', {'reservation': reservation, 'message': request.POST['message']}) plain_message = strip_tags(html_message) to_email = [hotel.email] headers={ 'In-Reply-To': request.POST['in_reply_to'], 'References': request.POST['in_reply_to'] } email = EmailMultiAlternatives(subject, plain_message, settings.DEFAULT_FROM_EMAIL, to_email, headers=headers) email.attach_alternative(html_message, "text/html") email.send(fail_silently=False) mailbox = Mailbox.objects.get(pk=email_server.mailbox.pk) mailbox.record_outgoing_message(email.message()) messages.success(request, _('Email sent successfully')) return redirect(reverse('hotel_reservation_mailbox', args=[reservation.pk,])) except Exception as e: print(('Failed to send email: ') + str(e)) return redirect(reverse('hotel_reservation_mailbox', args=[reservation.pk,])) Send message as … -
Django CSRF_TRUSTED_ORIGINS and http/2
I suspect websites that use http/2 protocol are not sending the Host header in the requests, eg going to /admin/ This leads to Django complains about Origin checking failed - does not match any trusted origins) even though posting to the exact same domain. This error won't come up with websites that using http/1 protocol on Django 4.2 Apart from adding the actual domain to CSRF_TRUSTED_ORIGINS, is there anything else I can do? -
Summernote Widget not displaying on inheriting from UpdateView
urls.py path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), views.py: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = PostForNewsFeed fields = ['post','title','content', 'tags','visibility'] template_name = 'feed/create_post.html' widgets = { 'content': SummernoteWidget(), } def form_valid(self, form): if form.is_valid(): data = form.save(commit=False) data.user_name = self.request.user data.save() messages.success(self.request, f'Posted Successfully') return redirect('home2') def test_func(self): post = self.get_object() if self.request.user == post.user_name: return True return False @python_2_unicode_compatible class PostForNewsFeed(models.Model): post = models.CharField(max_length=50, choices=POSTTYPE_CHOICES, default='Just a Mesage') #fullname = models.CharField(max_length=50, blank=True, null=True, default=None) title = models.CharField(max_length=100, blank=False, null=False) content = models.TextField(default=None) Summernote Widget wont render on PostupdateView -
continues error on "Could not find 'Price' Did not find price on detail page" in django
im begginer in django , leanring through coursera , django for everyone course , while doing my assignment repeated error throwing contiusely while submitting this is error,and i checked everthing but its still throwing error but "price" is there in web here my view.py in django- from ads.models import Ad from ads.owner import OwnerListView, OwnerDetailView, OwnerCreateView, OwnerUpdateView, OwnerDeleteView class AdListView(OwnerListView): model = Ad class AdDetailView(OwnerDetailView): model = Ad class AdCreateView(OwnerCreateView): model = Ad fields = ['title', 'text', 'price'] class AdUpdateView(OwnerUpdateView): model = Ad fields = ['title', 'text', 'price'] class AdDeleteView(OwnerDeleteView): model = Ad and here is my ad_detail.html --- {% extends "base_menu.html" %} {% block title %}{{ settings.APP_NAME }}{% endblock %} {% load humanize %} <!-- https://docs.djangoproject.com/en/3.0/ref/contrib/humanize --> {% block content %} <span style="float: right;"> ({{ ad.updated_at|naturaltime }}) {% if ad.owner == user %} <a href="{% url 'ads:ad_update' ad.id %}"><i class="fa fa-pencil"></i></a> <a href="{% url 'ads:ad_delete' ad.id %}"><i class="fa fa-trash"></i></a> {% endif %} </span> <h1>{{ ad.title }}</h1> <p> {{ ad.text }} </p> <p> {{ ad.price }} </p> <p> <input type="submit" value="All Ads" class="btn btn-primary " onclick="window.location.href='{% url 'ads:all' %}';return false;"> </p> {% endblock %} im using pythonanywhere for django and assignment python manage.py check --ok python manage.py makemigrations --ok python … -
Django Rest filter and filerset_class not working in custom action method
I'm having issues getting the filterset_class work in my view's action method. When I filter the data in /api/measurement/aggregated_data everything works fine, but I need to use these filters in my action method as well, so I can download the results. Here's my views.py: class AggregatedDataViewSet(ReadOnlyModelViewSet): serializer_class = AggregatedDataSerializer queryset = AggregatedData.objects.all() filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter] filterset_class = AggregatedDataFilter search_fields = ['parameter__measurand__name', 'river_site__lawa_code'] @action(detail=False, methods=['get'], url_path='download') def download(self, request, *args, **kwargs): qs = self.filterset_class(self.get_queryset()) # rest of the code... I apply filters in filterset_class in /api/measurement/aggregated_data and the url changes as well and will look something like this: http://127.0.0.1:8003/api/measurement/aggregated_data/?parameter__lawa_code=1234&sample_medium=&sampling_type=&year_from=2015&year_to=2015&river_site=BVNM When I click the download action, qs returns all data, so the filters are not applied. I want these filters in the url to be applied to the download method as well, but somehow they are not recognized by it. What is going wrong here and what is the best way to do what I am expecting? -
ModuleNotFoundError: No module named 'django.utils.six.moves'
While deploying my Django code on AWS EC2 server I'm getting the error below. I uninstalled six many times and deleted the cache folder and installed different versions of six but none of working. I have been facing this issue for the last 2 days but still haven't gotten a solution, please help me to get rid from this. May 22 17:06:33 ip-172-31-7-56 gunicorn[73506]: from storages.backends.s3boto3 import S3Boto3Storage May 22 17:06:33 ip-172-31-7-56 gunicorn[73506]: File "/home/ubuntu/lighthousemedia/.venv/lib/python3.12/site-packages/storages/backends/s3boto3.py", line 12> May 22 17:06:33 ip-172-31-7-56 gunicorn[73506]: from django.utils.six.moves.urllib import parse as urlparse May 22 17:06:33 ip-172-31-7-56 gunicorn[73506]: ModuleNotFoundError: No module named 'django.utils.six.moves' -
TypeError at /post/guest/2 __init__() takes 1 positional argument but 2 were given
urls.py path('post/guest/<int:pk>', PostDetailViewGuests, name='post-detail-guests'), class PostDetailViewGuests(HitCountDetailView): model = PostForGuestsFeed template_name = 'feed/post_detail.html' context_object_name = 'post' slug_field = 'slug' # set to True to count the hit count_hit = True def get_context_data(self, **kwargs): context = super(PostDetailViewGuests, self).get_context_data(**kwargs) context.update({ 'popular_posts': PostForGuestsFeed.objects.order_by('-hit_count_generic__hits')[:3],'page_title': 'Shared Post' }) return context template file: <a class="btn btn-info btn-sm" href="{% url 'post-detail-guests' post.id %}" >Read More &rarr;</a > -
How to retrieve Django Post parameters
I'm sending data from Javascript like this: let payload = { cmd: document.getElementById('cmdInput').value } console.log('Sending payload', payload) fetch('/runNgen/', { method: "POST", body: JSON.stringify(payload), headers: { "Content-Type": "application/json" } }) The Post operation seems to work. But on the Django side, I have @api_view(['POST']) def run_ngen(request): print("params", request.POST.keys()) and the parameters are empty. What am I doing wrong? -
Saving a fabri.js canvas to postgres database
I'm trying to save my canvas and few other data to my postgres database. In the React frontend i created an interface and a method to send my data to the Django backend. The problem I got, is that I always get the following message from the server: {sucess: false, error: "Canvas() got unexpected keyword arguments: 'data'"} error: "Canvas() got unexpected keyword arguments: 'data'" sucess: false Here is my frontedn code: import { Button } from "@mui/material"; import fabric from "fabric/fabric-impl"; import { saveCanvasData } from "../api/CanvasApi"; import { Canvas } from "../model/Canvas"; export const SaveCanvasButton = ({ fabricRef, }: { fabricRef: React.MutableRefObject<fabric.Canvas | null>; }) => { const handleClick = () => { const jsonCanvas = JSON.stringify(fabricRef.current?.toJSON()); const canvasData: Canvas = { aedate: new Date(), aeuser: "test", data: jsonCanvas, edate: new Date(), euser: "test", pid: "test", }; console.log(canvasData); if (canvasData) { saveCanvasData(canvasData); } }; return ( <Button onClick={handleClick} color="inherit"> Canvas Speichern </Button> ); }; Backend Code: from django.db import models from django.core.validators import RegexValidator # Validierung des Inputs gem. Datenmodell mit regulären Ausdrücken ID_validator = RegexValidator( regex=r"^\d{0,7}[1-9]$", message="Die ID muss eine Länge von 8 haben und darf nicht mit Null beginnen.", code="invalid_id", ) class Canvas(models.Model): # CID = models.CharField(max_length=8, … -
Pre-populate edit form with existing product description in Django
I'm building a Django inventory app and have a Product model with various fields. I've implemented an edit button for each product row that allows users to update information. However, when clicking the edit button, the form appears empty for all fields. I want the edit form to automatically display the existing product information for each field, so users only need to modify specific details. This eliminates the need to retype everything. I've searched the Django documentation on forms, but I'm unsure how to achieve this pre-population for the edit functionality. How can I pre-populate the edit form with the existing product information in my Django inventory app? def edit_product(request, pk): product = get_object_or_404(Product, pk=pk) if request.method == 'POST': form = ProductForm(request.POST, instance=product) if form.is_valid(): form.save() return redirect('product_list') else: form = ProductForm(instance=product) return render(request, 'inventory/edit_product.html', {'form': form}) -
How to authenticate users in Django and store data in Supabase in real-time?
I have a Django server with a user database stored in MySQL. I'm using Django Rest Framework and Django Allauth for user authentication. I want to build another application for storing user questions. The data for these questions should be stored in Supabase. I want to authenticate users with the Django server, and only authenticated users with the required authorization should be able to ask questions in the other application. Here's what I want to achieve: User logs in through the Django server (using Django Allauth). Once authenticated, the user can ask questions in the other application. The questions are stored in Supabase in real-time. Only authenticated users with the required authorization can ask questions. I'm not sure how to integrate Django with Supabase and handle real-time data updates. I also want to ensure that the authentication and authorization processes are secure and efficient. I have checked the documentation of supabase but I haven't found any information about third party authentication except the social the authentication that's what I noticed, maybe I missed someting. Any guidance or resources on how to achieve this would be greatly appreciated. Thanks in advance! P.S: I want to take advantage of the real time … -
Why is my Django mode object not appending my random ID generated tag to my URL?
Right, I am literally about to loose my temper. I have a Django model, with an object. I have a fucntion which generated a random ID, appends it to the model object and places it on the end of the URL. Thats the theory anyway, but just like everything else in my life, nothing works. I have a great big neon sign that is only invisible to me which stated "Please piss this guy off as much as you possibly can!" You have no idea how sick to death I am of this. It's so silly! It's so unfair and I am going to fume. In my urls.py I have: ``from django.urls import path, include from . import views urlpatterns =[ path('',views.careers, name="careers"), path('apply/<str:careers_reference>',views.apply), ]`` In my views.py I have: `from django.shortcuts import render, redirect, get_object_or_404 from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from . models import Careers import logging from xxxx import utils def apply(request, careers_reference): career_detail = get_object_or_404(Careers,careers_reference = careers_reference) template = loader.get_template('careers-details.html') context = { 'career_detail' : career_detail, } return HttpResponse(template.render(context, request))` In my models.py, I have `from django.db import models from . import utils # Create your models here. … -
Adding extra layer of security(OTP) to a website
I’m unable to use Django admin to add device. I have a feeling the problem is in the urls.py file. This is the content From django.contrib import admin from django.urls import path from django_otp.admin import OTPAdminSite admin.site__class__=OTPAdminSite urlpatterns = [ path(‘admin/‘, admin.site.urls), ] I tried logging in to the localhost:8000/admin/. Although it was successful, it prompted ‘choose device’ when I haven’t created one. -
Using F result for get key
I have dict like {product_id: count}. For example cart_items = {1: 150}. This dict represents customer basket. I also have product model with count field. It's representing stock balances. I want to get products that is in dict and update their quantity according to values in dict. I get products like this : products = Product.objects.filter(id__in=cart_items) And I want to update the quantity like this: products.update(count=dict.get(F("id")) But it doesn't work. Thx! -
hy,im beginner in django- error acqures regularly like this"Could not find 'Price' Did not find price on detailage" cld someone pls hlp me this
enter image description here my ad_detail.html in django-using pythonanywhere {% extends "base_menu.html" %} {% block title %}{{ settings.APP_NAME }}{% endblock %} {% load humanize %} <!-- https://docs.djangoproject.com/en/3.0/ref/contrib/humanize --> {% block content %} <span style="float: right;"> ({{ ad.updated_at|naturaltime }}) {% if ad.owner == user %} <a href="{% url 'ads:ad_update' ad.id %}"><i class="fa fa-pencil"></i></a> <a href="{% url 'ads:ad_delete' ad.id %}"><i class="fa fa-trash"></i></a> {% endif %} </span> <h1>{{ ad.title }}</h1> <p> {{ ad.text }} </p> <p> {{ ad.price }} </p> <p> <input type="submit" value="All Ads" class="btn btn-primary " onclick="window.location.href='{% url 'ads:all' %}';return false;"> </p> {% endblock %} my views.py from ads.models import Ad from ads.owner import OwnerListView, OwnerDetailView, OwnerCreateView, OwnerUpdateView, OwnerDeleteView class AdListView(OwnerListView): model = Ad class AdDetailView(OwnerDetailView): model = Ad fields = ["title", "text", "price"] class AdCreateView(OwnerCreateView): model = Ad fields = ["title", "text", "price"] class AdUpdateView(OwnerUpdateView): model = Ad fields = ["title", "text", "price"] class AdDeleteView(OwnerDeleteView): model = Ad it shows "could not price in detail"...im begginer just started to learn django someone pls help me on this -
telegram bot using python-telegram-bot django
I have a Telegram bot using the python-telegram-bot library and Django. The bot is run and messages are processed via a webhook pythonanywhere. I used the free plan and the bot was working perfectly, but I needed to upgrade the account to access external sites. After upgrading to the Hacker plan, issues started occurring with message processing and improper tracking. How can I resolve this issue? Could it be related to high CPU usage or SSH settings? Thank you. .................... -
Axios Error. IDE only do underline at 'corsheaders'. Typo: In word 'corsheaders'
Environment: Mac OS m2. Framework : Django, Vue. IDE : PyCharm. Library : opencv-python==4.6.0.66. mediapipe-silicon==0.8.10.1. keras==2.9.0. keras-tuner==1.1.3. tensorflow-macos==2.15.1. numpy==1.23.3. scikit-learn==1.1.2. pandas==1.4.3. matplotlib==3.6.0. seaborn==0.12.0. yellowbrick==1.5. Django==4.2.13. djangorestframework==3.14.0. django-cors-headers==3.13.0. django-extensions==3.2.1. protobuf==3.20. Hello, Hi, I'm studying with using someone else's repository regarding pose detection. I haven't been able to fix the issue for weeks regarding the axios network error. axios error in web(chrome). A network error occurs when I press the 'process' button that performs the core function. I mailed about the error to original author of repository, but didn't get answer. I looked it up a lot, and search it, then I found maybe it's a CORS-related problem, and the answers said me that the "If you write about the corsheader in settings, then the problem will solve". but that part has already been written. "corheaders" in settings. and others, "corheaders" in settings_2. "corheaders" in settings_3. While going through the code, I found that only 'corsheaders' are underlined on the IDE. wave underline only under "corsheaders". I thought maybe there's something wrong, so IDE don't recognize the corsheads and just judge it as a simple 'typo'. Is there anyone who can help with this? It's urgent because it's related to my university … -
Google OAuth 2.0 redirect_uri_mismatch
I'm getting a Google OAuth 2.0 redirect_uri_mismatch error. I receive this error when I add https://domain-name.com and https://domain-name.com/oauth/complete/google-oauth2/, but I can log in with Google when I run these URLs locally (http://127.0.0.1:8000 and http://127.0.0.1:8000/oauth/complete/google-oauth2/). Is there a mistake I might be missing? (Note: I'm using the Python Django library) Btw: Verification Status Verification in progress The Trust and Safety team has received your form. They will reach out to you via your contact email if needed. The review process can take up to 4-6 weeks. Expect the first email from our Trust and Safety team within 3-5 days. Your last approved consent screen is still in use I've tried to resolve the issue by ensuring that the redirect URIs specified in the Google Developer Console match those used in my Django application settings. I've also verified that the URIs are correct for both the production server and the local development environment. Additionally, I've double-checked the client ID and client secret provided to ensure they are accurate. Despite these efforts, I'm still encountering the redirect_uri_mismatch error. I expected that configuring the redirect URIs correctly would resolve the issue, but it persists.