Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Task send_verify_email[dea32c62-98b6-4418-93af-5c5d0f0f20ad] raised unexpected: TimeoutError(110, 'Connection timed out')
After I enable celery in the terminal, I click Send email again and wait for a moment to get the result.My configuration file is also configured, and I will receive front-end requests, and the back-end server is normal, but there is still a timeout problem, I do not know why. [2024-05-13 23:09:54,387: INFO/MainProcess] Task send_verify_email[dea32c62-98b6-4418-93af-5c5d0f0f20ad] received [2024-05-13 23:12:05,560: ERROR/ForkPoolWorker-1] Task send_verify_email[dea32c62-98b6-4418-93af-5c5d0f0f20ad] raised unexpected: TimeoutError(110, 'Connection timed out') Traceback (most recent call last): File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/celery/app/trace.py", line 453, in trace_task R = retval = fun(*args, **kwargs) File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/celery/app/trace.py", line 736, in __protected_call__ return self.run(*args, **kwargs) File "/home/admin/haoke18/hk18/celery_tasks/email/tasks.py", line 27, in send_verify_email send_mail(subject, "", EMAIL_FROM, [to_email], html_message=html_message) File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.10/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.10/smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.10/smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/lib/python3.10/socket.py", line 845, in create_connection raise err File "/usr/lib/python3.10/socket.py", line 833, in create_connection sock.connect(sa) TimeoutError: [Errno 110] Connection timed out I configured Django with the correct email … -
Migrating from SQLite to MySQL Django (not working)
I'm trying to implement the MySQL instead of the SQLite, and the instructions are pretty straight forward, but, when I run the server again it stops after the system check identified no issues (0 silenced)., which indicates that it can't establish a connection to the database. but everything checks out. I did this step in the database migration: Installing Mysql server && mysqlclient Create a database and a user and grant all permissions to that database add to the setting.py file the database & user settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'auth', 'USER': 'admin', 'PASSWORD': 'password', 'HOST': '127.0.0.1', """localhost not working (Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2))""" 'PORT': '3306', } } Am I missing anything out? Why isn't it working? -
There is a problem with the booking, does not go to booking_confirmation
I have a form in my app and when i submit it, everything goes correct but it only goes to .../bookings and not .../bookings/booking_conifrmation.html. Here are the views.py and urls.py views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib import messages from datetime import timedelta from .forms import BookingForm from .models import Booking from blog.models import Car from django.urls import reverse from django.utils import timezone from django.utils.dateparse import parse_date import requests from .models import BusyDate import json from django.http import JsonResponse def booking_form(request): if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): car_id = form.cleaned_data['car'].id start_date = form.cleaned_data['period_start'] end_date = form.cleaned_data['period_end'] busy_date = BusyDate(car_id=car_id, start_date=start_date, end_date=end_date) #booking = Booking(car_id=car_id, start_date=start_date, end_date=end_date) busy_date.save() messages.success(request, "Your booking has been successfully submitted.") return redirect(reverse('booking_confirmation', kwargs={'car_id': car_id})) else: for field, errors in form.errors.items(): for error in errors: messages.error(request, f"Error in {field}: {error}") else: # Set default values for period_start and period_end start_time = timezone.now().strftime('%Y-%m-%d') end_time = (timezone.now().date() + timedelta(days=1)).strftime('%Y-%m-%d') initial_data = {'period_start': start_time, 'period_end': end_time} form = BookingForm(initial=initial_data) # Retrieve unavailable dates for selected car car_id = request.GET.get('car_id') # Assuming the car_id is passed in the request if car_id: try: car = Car.objects.get(id=car_id) start_date = timezone.now().strftime('%Y-%m-%d') end_date = (timezone.now().date() + timedelta(days=1)).strftime('%Y-%m-%d') response = requests.get( … -
getting error page not found while giving @login_reequired
views.py @login_required def transactions(request): user_transactions = Transactions.objects.filter(transaction_medium = request.user) return render(request,'transactions.html',{'user_transactions':user_transactions}) urls.py urlpatterns = [ path('',views.signup,name="signup"), path('login/',views.login,name="login"), path('add_transactions/',views.add_transactions,name="add_transactions"), path('transactions/',views.transactions,name="transactions"), ] error is Not Found: /accounts/login/ "GET /accounts/login/?next=/transactions/ HTTP/1.1" 404 2846 -
I am creating a dashboard view in django to show all the data of the user but it shows nothing when i use class based view..?
when i use the function based view it works fine. can anyone help me? this is the model class UserProfile(models.Model): @property def getter_signal_limit(self): return self.signal_limit user = models.OneToOneField(User, on_delete=models.CASCADE) webhook_url = serializers.SerializerMethodField() # "https://www.tradify.com/api/" + hashlib.sha256(str(User.username).encode()).hexdigest() signal_limit = models.IntegerField(default=50, validators=[MinValueValidator(1)]) signals_used = models.IntegerField(default=0) plan = models.CharField(max_length=12, choices=( ('Basic', 'Basic'), ('standard', 'Standard'), ('premium', 'Premium'), ('platinum', 'Platinum')), default='Basic') created = models.DateTimeField(auto_now_add=True, blank=True) timezone = timezone.get_current_timezone() this is the user serializer code class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = UserProfile fields = '__all__' # fields = ('user', 'signal_limit', 'signals_used', 'plan', 'created', 'webhook_url') # read_only_fields = ('user', 'created') def create(self, validated_data): user_data = validated_data.pop('user') user = UserSerializer.create(**user_data) user_profile = UserProfile.objects.create(user=user, **validated_data) return user_profile this is the Function based view login_required def dashboard(request): user_profile = request.user.userprofile context = { 'user_profile': user_profile, 'signal_limit': user_profile.signal_limit, 'signals_used': user_profile.signals_used, 'plan': user_profile.plan, 'webhook_url': user_profile.get_webhook_url(), 'timezone': user_profile.timezone, } return render(request, 'dash.html', context) and here is its html code <!-- dashboard.html --> <h1>Dashboard</h1> <p>Username: {{ user_profile.user.username }}</p> <p>Signal Limit: {{ signal_limit }}</p> <p>Signals Used: {{ signals_used }}</p> <p>Plan: {{ plan }}</p> <p>Webhook URL: {{ webhook_url }}</p> <p>Timezone: {{ timezone }}</p> while this code is not showing any data of the user Class based view: class DashboardView(LoginRequiredMixin, TemplateView): template_name = 'dashboard.html' … -
Django not creating a table in the Development Server
I've been trying to fix this problem, but couldn't find a solution, tried a bunch of fixes online. The problem I'm facing. I have a Django project running on Hawuei Cloud, I've made some changes and wanted to test it on the Development server before going to production. The project is running fine, BUT, there's a table that is not being created for some reason, so the parts of the project that uses that table, throws an error. But the thing is the changes I've made weren't on that table. I don't understand why that table isn't being created, I never had this issue. This is a small part of the model class Regime(models.Model): inventario = models.ForeignKey(Inventario, on_delete=models.CASCADE) nome = models.CharField(max_length=50) def __str__(self): return self.nome class Unidade(models.Model): empresa = models.ForeignKey(Empresa, on_delete=models.CASCADE) codigo = models.CharField(max_length=50) descricao = models.CharField(max_length=100) cnpj = models.CharField(max_length=20) def __str__(self): return self.descricao class Conta(models.Model): empresa = models.ForeignKey(Empresa, on_delete=models.CASCADE) codigo = models.CharField(max_length=50) descricao = models.CharField(max_length=100) def __str__(self): return self.descricao class Local(models.Model): empresa = models.ForeignKey(Empresa, on_delete=models.CASCADE) codigo = models.CharField(max_length=50) descricao = models.CharField(max_length=100) def __str__(self): return self.descricao The table Unidade is not being created, the other similar ones like Local and Conta work just fine. I've tried flushing the database, migrating … -
How to check if user is entering only numbers
I'm trying to update my registration system. I want user entering his age, but I don't know how to check if user entered only numbers. I will give snippet of my code, where it doesn't work my views.py: def Registration(request): if request.method == "POST": username = request.POST["username"] age = request.POST["age"] ... if username.isnumeric() == "True": messages.error(request, "Username can't be all number!") return redirect("/") if age.isnumeric() == "False": messages.error(request, "Age must be all numbers!") return redirect("/") ... messages.success(request, "Your account has been succesfully created") return redirect("/Login/") return render(request, "Registration.html") my registration.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width-device-width, initial-scale=1, maximum-scale=1" /> <link rel="stylesheet" type="text/css" href="https://bootswatch.com/5/solar/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> <title> view tasks </title> </head> <body> <div class="text-center"> <h1>Registrate here</h1> <form action="/Registration/" method="post"> {% csrf_token %} <label for"username">Username</label> <br> <input class="" type="text" id="username" name="username" placeholder="Create a username (letter and numbers only)" Required> <br> <br> <label for"age">Age</label> <br> <input class="" type="text" id="age" name="age" placeholder="Enter your age" Required> <br> <br> <label for"fname">First Name</label> <br> <input class="" type="text" id="fname" name="fname" placeholder="Enter your first name" Required> <br> <br> <label for"lname">Last Name</label> <br> <input class="" type="text" id="lname" name="lname" placeholder="Enter your last name" Required> <br> <br> <label for"email">Email</label> … -
How to manipulate pandas datafram from mysql?
I have a doubt with inserting pandas into mysql please answer sir @Henri @user:8510149 I have inserted now i want to manipulate it. Please help me regarding this issue and this is for a project that Im currently working on. .Awaiting your reply.... -
Problem with django translation detection in the templates
Here i generate my template from a http request so i have a custom method to generate my templates : def get_template(template, using=None): engines = _engine_list(using) for engine in engines: return engine.from_string(template) And here i pass the template : def get_template_names(self): print(self.html_template) return get_template(self.html_template, using=self.template_engine) and in my console i get : app-1 | {% load i18n static %} app-1 | app-1 | {%block content %} app-1 | <p>{{ _('Hello from the template')}}</p> app-1 | <p>{% translate 'hello my friends' %}</p> app-1 | app-1 | {%endblock%} Then i generate my .po file insinde a locale dir with django-admin makemessages -l fr So the problem is when the .po file is generated i don't get my strings Hello from the template and hello my friends while we are supposed to get the strings to translate automatically. PS: When i enter manually the string hello my friends or Hello from the template in the .po file and I add a translation. This is work well Where is the problem please I don't want to add strings manually anymore ? i try to get my custom strings to translate inside my custom template but i don't get them the .po file is empty -
How to change the attributes of Django login form
My site is RTL so I need to adjust the direction of some fields to LTR (username, email, password, etc). One of them is the Password Change form so this is what I do: forms.py from django.contrib.auth.forms import PasswordChangeForm class CustomPasswordChangeForm(PasswordChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['old_password'].widget.attrs.update({'dir': 'ltr'}) self.fields['new_password1'].widget.attrs.update({'dir': 'ltr'}) self.fields['new_password2'].widget.attrs.update({'dir': 'ltr'}) After creating the required view and URL path, that works perfectly and all 3 fields are LTR. The other one is the Login Form so I do the same thing: forms.py from django.contrib.auth.forms import AuthenticationForm class CustomAuthenticationForm(AuthenticationForm): def __init__(self, request=None, *args, **kwargs): super().__init__(request, *args, **kwargs) self.fields['username'].widget.attrs.update({'dir': 'ltr'}) self.fields['password'].widget.attrs.update({'dir': 'ltr'}) This time, the above code does not have any effect. Both fields are still RTL. So why it works for password change and not for login and what's the solution for login form? -
TemplateSyntaxError at /cart/ Invalid filter: 'mul' Reques
TemplateSyntaxError at /cart/ Invalid filter: 'mul' Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 5.0.6 Exception Type: TemplateSyntaxError Exception Value: Invalid filter: 'mul' Exception Location: C:\Users\denni\Desktop\Foods1\venv\Lib\site-packages\django\template\base.py, line 603, in find_filter Raised during: Foodies.views.view_cart Python Executable: C:\Users\denni\Desktop\Foods1\venv\Scripts\python.exe Python Version: 3.11.7 Python Path: ['C:\Users\denni\Desktop\Foods1\Foods', 'C:\Users\denni\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\denni\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\denni\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\denni\AppData\Local\Programs\Python\Python311', 'C:\Users\denni\Desktop\Foods1\venv', 'C:\Users\denni\Desktop\Foods1\venv\Lib\site-packages'] Server time: Mon, 13 May 2024 11:01:44 +0000 Error during template rendering I want after click on buy now it should give me result -
Issue concercing cookie setting in django on browser, works fine on postman
I am experiencing an issue, I am using django 5 for my backend and nuxt 3 for my frontend. I have this view in django: @action(detail=False, methods=['POST']) def login(self,request): username = request.data['username'] password = request.data['password'] user = authenticate(request,username=username, password=password) if user is not None: login(request,user) sessionid = request.session.session_key return Response({'message': "Logged in!", 'sessionid': sessionid}) else: return Response({'message': "Invalid credentials provided",'username': username, 'password': password}, status=status.HTTP_400_BAD_REQUEST) And when I do a post request with the proper credentials on postman, I get a 200 OK response, with the cookies being set. On the frontend I also get a 200 OK response and the set_cookie response headers for both the sessionid and csrftoken are there. However in all subsequent requests, the request cookies tab is empty and there is no 'cookie' header. I had solved this issue, at least I thought and was able to get the sessionid cookie to be set after changing some of it's settings. However the csrftoken was still not being set despite me giving it the same settings. During the process of trying to get the csrftoken to work, the sessionid stopped being set. I tried reverting it's settings back to how it were, that didn't work so I … -
Count the number of users following a ticker in django
I need to get the top stock tickers followed by users, the issue is when two users or more follow the same ticker, it get repeated when using the query Tickers.objects.annotate(followers=Count('users')).order_by('followers') as shown here: In this example, the ticker FDCFF needs to be the top ticker since two users are following it, instead it gets repeated and its not being shown as the top followed ticker. Models.py class Tickers(models.Model): symbol = models.CharField(max_length=100) name = models.CharField(max_length=100) users = models.ManyToManyField(User, related_name='tickers') views.py def index(request): tickers = Tickers.objects.annotate(followers=Count('users')).order_by('followers') context = { 'tickers': tickers, } return render(request, 'main_index.html', context=context) -
Access to ForeignKey fields of another model
I have project in Django Rest Framework where I need get access from Project to ProjectTemplate. But between I have Department model, so I can only connect with Department via ForeignKey. There is some solution how I can handle this? from django.db import models class ProjectTemplate(models.Model): name = models.CharField(max_length=125) desc = models.TextField() def __str__(self): return self.name class Department(models.Model): name = models.CharField(max_length=125) desc = models.TextField project_template = models.ForeignKey(ProjectTemplate, on_delete=models.SET_NULL, related_name='departments', null=True, blank=True, unique=True) def __str__(self): return self.name class Project(models.Model): name = models.CharField(max_length=125) desc = models.TextField() is_visible = models.BooleanField(default=True) project_temp = models.ForeignKey(Department, to_field='name', on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.name -
How properly configure Entity Attribute Value pattern in django?
I have a product model: class Product(models.Model): title = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) category = models.ForeignKey('Category', on_delete=models.CASCADE) price = models.FloatField() discount = models.IntegerField() # stands for percentage count = models.IntegerField() priority = models.IntegerField(default=0) brand = models.ForeignKey('Brand', on_delete=models.SET_NULL, null=True, blank=True) tags = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title Now I want to implement entity attribute value pattern as different products can have different specifications. I understood the traditional way of EAV. But I read in wikipedia as postgresql has jsonb column type and this allows performance improvements by factors of a thousand or more over traditional EAV table designs. My database in postgresql. So what is the best practice to implement EAV (or dynamic set relationship with attributes)? Should I just add like: class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) specifications = models.JSONField() And also I want to handle price and count (in stock) differently for each variant, let's say there are 10 shoes with size 10 and color red which price is 100 dollars and 2 shoes with size 9 and color blue which price is 120 dollars. -
Programming Error in MySQL LOAD DATA statement when using ENCLOSED BY
I am trying to run a SQL statement using cursor.execute LOAD DATA LOCAL INFILE '/home/ubuntu/test.csv' INTO TABLE app_data CHARACTER SET UTF8MB4 FIELDS TERMINATED BY ',' ENCLOSED BY "" LINES TERMINATED BY '\r\n' This runs using mysql command line but the ENCLOSED BY raises a ProgrammingError / OperationalError. Any help/pointers appreciated. I have already tried variations such as ENCLOSED BY '"'. -
How to start a Django Celery Shared task using redis-cli
i have a Celery task defined in django application as below from celery import shared_task @shared_task def save_notification(notification): print("Received notif", notification) for testing purpose in django container i type following command to start celery worker celery -A hello_django worker --loglevel=INFO it starts as expected and tasks is discovered, now the important thing i need to start the task using some arguments. So for testing i am using below command. redis-cli -n 0 RPUSH celery "{\"task\":\"notifications.tasks.save_notification\", \"args\":[\"I am notification\"]}" Commands publishes successfully and print some integer but on worker side it crashes and following error occurs [2024-05-13 13:03:55,610: CRITICAL/MainProcess] Unrecoverable error: KeyError('properties') Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/celery/worker/worker.py", line 202, in start self.blueprint.start(self) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 365, in start return self.obj.start() ^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/worker/consumer/consumer.py", line 340, in start blueprint.start(self) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.12/site-packages/celery/worker/consumer/consumer.py", line 742, in start c.loop(*c.loop_args()) File "/usr/local/lib/python3.12/site-packages/celery/worker/loops.py", line 97, in asynloop next(loop) File "/usr/local/lib/python3.12/site-packages/kombu/asynchronous/hub.py", line 373, in create_loop cb(*cbargs) File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 1344, in on_readable self.cycle.on_readable(fileno) File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 569, in on_readable chan.handlers[type]() File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 974, in _brpop_read self.connection._deliver(loads(bytes_to_str(item)), dest) File "/usr/local/lib/python3.12/site-packages/kombu/transport/virtual/base.py", line 1017, in _deliver callback(message) File "/usr/local/lib/python3.12/site-packages/kombu/transport/virtual/base.py", line 636, in _callback message … -
I created a django project to retrive the transaction data from database by verifying the user. But i am getting error like"AnonymousUser"
veiw.py this is views code def view_transaction(request): print(request.user) user_transactions = Transactions.objects.filter(user_account = request.user) return render(request,'transactions.html',{'user_transactions':user_transactions}) is the above code correct or not, i think when it check wheather user login is not present here. models.py class User(models.Model): name = models.CharField(max_length=45) phone = models.CharField(max_length=45) account_number = models.CharField(max_length=45,primary_key=True,blank=False,unique=True) user_id = models.CharField(max_length=45,unique=True) password = models.CharField(max_length=45) confirm_password = models.CharField(max_length=45) class Transactions(models.Model): transaction_number = models.AutoField(primary_key=True) user_account = models.ForeignKey(User,on_delete=models.CASCADE) date_of_transaction = models.DateField() transaction_type = models.CharField(max_length=20, choices=TRANSACTION_TYPES) transaction_medium = models.CharField(max_length=20, choices=TRANSACTION_MEDIUM) transaction_amount = models.DecimalField(max_digits=10,decimal_places=2) when i login using userid and password ,it shows some details about customer. I want transaction details in transactions.html,but i didn't get any, instead i got error like anonymous user. -
ProgrammingError: relation "users_customuser" does not exist
I have created a custom user as follows: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField(unique=True) USERNAME_FIELD="email" REQUIRED_FIELDS=["username"] def __str__(self) -> str: return self.email I have defined the model in my settings.py file as follows AUTH_USER_MODEL = "users.CustomUser" when I run the migrate command I get the above error I have tried running python manage.py migrate users --fake but the error still persists Internal Server Error: /api/register/ Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.errors.UndefinedTable: relation "users_customuser" does not exist LINE 1: SELECT 1 AS "a" FROM "users_customuser" WHERE "users_customu... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) … -
SimpleListFilter and M2M fields as JSON
My setup contains Product information that come from a JSON field and are linked to a Page in a m2m relation (Page like in a catalogue). class Page(models.Model): ... products = models.ManyToManyField(Product, related_name="%(class)s_name", related_query_name="product_page_qs", blank=True) class Product(models.Model): ... number = models.PositiveIntegerField() data = models.JSONField() I created a SimpleListFilter with text search to get a list of all pages that contain a given product (works just fine): class PageProductSearch(admin.SimpleListFilter): title = "product" parameter_name = "product" template = "search_filter.html" def lookups(self, request, model_admin): return ((None, None),) def choices(self, changelist): super().choices(changelist) return (*self.lookup_choices,) def queryset(self, request, queryset): value = self.value() if value: return queryset.filter(products=value) My problem here is, that I have to know the product.id in order to search for products. How can I extend my queryset filtering to search for a key in the jsonField? I tried: queryset.filter(products__contain=value) but got django.core.exceptions.FieldError: Unsupported lookup 'contain' for ForeignKey or join on the field not permitted. This might be because I am on SQLite. using Q and regex: queryset.filter(Q(data__regex=r'"name":.*"test"')) but this always leads to empty querysets. I liked the regex idea tough, because it is insensitive to data elements that might not contain the key name. -
Greets. Please help serve Media (Pro pics) on Website https://djangocareershifterswebsite.onrender.com. I have tried nGinx, deploy & redner docs.
All funtionality works except my profile pics being uploaded. So nginx just did not serve as the bucket, I have Linux machine and terminal on windows. I have PostgreSQL running on PG Admin 4. It shows my DB. Here is a link to my website. https://djangocareershifterswebsite.onrender.com. I deleted all my 6 of my failed deploy branches, I did deploy but still no profile pic. Here is my Github. https://github.com/GJprocode/DjangoCareerShiftersWebsite.main for production. https://github.com/GJprocode/DjangoCareerShiftersWebsite/tree/DeployV1 for deploy. Please provide setting.py for deploy( Import os to generate key and so on, getting data parse form sqlite db to postgreSQL etc.) Render.com Yaml file, and the.build file is static. Environmental variables. ALthough this method uses teh blue print tab. Thanks so much, or advise what works for you!! Then my website is complete. Last little bit. The functionality of my webiste worked with sqlite 3, admin and registering user and all collect static.css as per my website. Except serving media static. Thats it. Tried all the routes. PLease check mt deploy branch settings.py, render.yaml and advise how you did it. Thanks. -
NLTK package is not working in production but working in development
I have created a web-app using Django. I this web-app I want to add functionality to extract phrases from content. My code is working fine in development but not working in production. Using nltk package I have created a function which gives returns a list of phrases from content. below is my code: import nltk from typing import List def extract_phrases(content: str) -> List: # Tokenize text into sentences sentences = nltk.sent_tokenize(content) # Initialize list to store phrases phrases = set() # Iterate through each sentence for sentence in sentences: # Tokenize sentence into words words = nltk.word_tokenize(sentence) # Get part-of-speech tags for words pos_tags = nltk.pos_tag(words) # Initialize list to store phrases in current sentence current_phrase = [] # Iterate through each word and its part-of-speech tag for word, pos_tag in pos_tags: # If the word is a noun or an adjective, add it to the current phrase if pos_tag.startswith("NN") or pos_tag.startswith("JJ"): current_phrase.append(word) # If the word is not a noun or adjective and the current phrase is not empty, # add the current phrase to the list of phrases and reset it elif current_phrase: phrases.add(" ".join(current_phrase)) current_phrase = [] # Add the last phrase from the current sentence … -
Retrieve user data infos after authentification using OAuth 2.0
How can I retrieve user data information after authentication using Django and Google OAuth2 ? HTML <button> <a href="{% provider_login_url "google" %}"> <div class="connexion-type"> <div class="connexion-type-svg"> <svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="100" height="100" viewBox="0 0 48 48"> <!-- SVG paths --> </svg> </div> <div class="connexion-type-content">Login via Gmail</div> </div> </a> </button> </div> ** Django View:** @login_required def redirect_google_provider(request): print("Access to redirect_google_provider") if 'code' in request.GET: # Extract the authorization code code = request.GET['code'] # Debug print(f"Code is: {code}") # Exchange the authorization code for an access token token_url = 'https://oauth2.googleapis.com/token' client_id = 'YOUR_GOOGLE_CLIENT_ID' client_secret = 'YOUR_GOOGLE_CLIENT_SECRET' redirect_uri = 'YOUR_REDIRECT_URI' data = { 'code': code, 'client_id': client_id, 'client_secret': client_secret, 'redirect_uri': redirect_uri, 'grant_type': 'authorization_code', } response = requests.post(token_url, data=data) token_data = response.json() access_token = token_data.get('access_token') # Retrieve user information from Google API if access_token: user_info_url = 'https://www.googleapis.com/oauth2/v3/userinfo' headers = {'Authorization': f'Bearer {access_token}'} user_info_response = requests.get(user_info_url, headers=headers) user_info = user_info_response.json() email = user_info.get('email') # Check if the user exists in the system if email: user, created = User.objects.get_or_create(username=email, email=email) if created: # New user, save additional information if needed user.save() # Log the user in login(request, user) return HttpResponseRedirect('/home/') # Redirect to home page after successful login # If code is not present or user … -
I am using dart to develop a e-commerce flutter app , so in here when am trying build edit profile page , i need to pass token from login page
So I am using rest api as back end , I am unable to edit so I found that the token needs to be passed , from login to this change-profile api , so that the user can succesfully edit his or her details . Future updateProfile() async { String url = "http://167.71.232.83:8000/myprofile/${userId}/"; // Build the query parameters with updated user information Map<String, String> queryParams = { "email": _emailController.text, "password": passwordController.text, "repassword": repasswordController.text, "firstname": firstname.text, "lastname": lastname.text, "phonenumber": phonenumber.text, "state": state.text, "city": city.text, "Zip": zip.text, "mailing": _value.toString(), "referred_by": selectedItem, "flag": "business", "businessname": businesscontroller.text, }; String queryString = Uri(queryParameters: queryParams).query; url += '?' + queryString; try { final response = await http.put( Uri.parse(url), headers: { "Content-Type": "application/json", "User-Agent": "PostmanRuntime/7.28.4", "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Connection": "keep-alive", }, ); var data = jsonDecode(response.body); print(url); print(response.statusCode); print(data); if (response.statusCode == 200) { // Success _showSuccessDialog(); // Navigate to the next page or perform any other actions Navigator.push( context, MaterialPageRoute( builder: (_) => BottomPage(), ), ); } else { // Error _showErrorDialog('Failed to update profile. Please try again.'); } print(response.body); } catch (e) { print('Error updating profile: $e'); _showErrorDialog('Failed to update profile. Please try again.'); } } I attached the code snippet above … -
Error in importing latest DeepSpeechModel: CreateModel failed with 'Failed to initialize memory mapped model.' (0x3000)
Thanks for your time checking my post. In my Django project I created an API which is supposed be to trigged in view function where it runs the most recent deepspeech version (DeepSpeech: v0.9.3-0). Even though there is no problem with the backend and the request I sent from Insomnia is received from the server, and I have the latest TF version installed, I encounter the error below: linux@linux:~/docs/PROJECT$ cd /home/linux/docs/PROJECT ; /usr/bin/env /home/linux/docs/PROJECT/env_/bin/python /home/linux/.vscode/extensions/ms-python.debugpy-2024.6.0-linux-x64/bundled/libs/debugpy/adapter/../../debugpy/launcher 60057 -- /home/linux/docs/PROJECT/PROJECT/manage.py runserver 8001 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 13, 2024 - 03:49:36 Django version 4.2.13, using settings 'PROJECT.settings' Starting development server at http://127.0.0.1:8001/ Quit the server with CONTROL-C. TensorFlow: v2.3.0-6-g23ad988 DeepSpeech: v0.9.3-0-gf2e9c85 ERROR: Model provided has model identifier 'u/3�', should be 'TFL3' Error at reading model file PROJECT/files/deep_speech_models/deepspeech-0.9.3-models.pbmm Error initializing DeepSpeech model: CreateModel failed with 'Failed to initialize memory mapped model.' (0x3000) Below is the relevant part of my view function code where the error occurs: class ModifyNarrativeAPIView(APIView): permission_classes = [permissions.IsAuthenticated] def post(self, request, *args, **kwargs): voice_files = paths.saved_sound_files ear = Ear(DEEPSPEECH_MODEL_PATH, DEEPSPEECH_SCORER_PATH) for voice_file in voice_files: text = ear.convert_voice_to_text(voice_file) ... Thanks again.