Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
0 I converted my python file into .exe file
0 I converted my python file into .exe file. Before converting into .exe file it gives full output but after creating into .exe file it is not giving full output can anyone help me resolve this issue? it is like if i click that file it should connect the opc server and fetch the data and insert it into the database but while executing the python code it's working but if I click the .exe file after converting it is not working.. pip install pyinstaller pyinstaller --onefile opc.py pyinstaller --hiddenimport win32timezone -F opc.py -
I am not able to Overriding django model
I have a django model that has multiple fields class data(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) pj = ArrayField(models.IntegerField(), null=True, blank=True) name = models.CharField(max_length=225) explain = models.TextField(max_length=50, null=True) def save(self, *args, **kwargs): self.name=f"new {name}" super(data, self).save(*args, **kwargs) when i save the data model the name is not getting changed to "new name" it is getting saved as "name" I want the new naming convention to reflect. -
Need example of pytest test upload file to graphql
I am trying to run pytest and upload a file to my /graphql endpoint. I have read the official doc, but it does not cover my question. Then I tried ask chatbot. The answer contains error. It raises the error from server is not running. I have experience test uploading the file with djangoREST. I don't need to run an actual server during the test. Therefore I think gql will do the same thing. query mutation ExcelUploadFile($file: Upload!, $orderType: String!, $saleOrg: String!, $uploadType: UploadType!, $distributionChannel: String!, $division: String!) { uploadExcel( file: $file orderType: $orderType saleOrg: $saleOrg uploadType: $uploadType distributionChannel: $distributionChannel division: $division ) { status rows errors { field code message __typename } __typename } } variables { "file": null, "orderType": "ZP30", "saleOrg": "0254", "uploadType": "GROUP", "distributionChannel": "10", "division": "00" } Here is my pytest code. from io import BytesIO import openpyxl import pytest import requests from django.core.files.uploadedfile import InMemoryUploadedFile from requests_toolbelt.multipart.encoder import MultipartEncoder from scgp_po_upload.implementations.excel_upload import validate_excel_upload_file from scgp_po_upload.tests.fixtures import client_query # URL of your GraphQL endpoint GRAPHQL_ENDPOINT = "http://localhost:8000/graphql/" # Mutation query UPLOAD_MUTATION = """ mutation ExcelUploadFile($file: Upload!, $orderType: String!, $saleOrg: String!, $uploadType: UploadType!, $distributionChannel: String!, $division: String!) { uploadExcel( file: $file orderType: $orderType saleOrg: $saleOrg uploadType: $uploadType … -
Need to update Drop down used in HTML + Django
I have developed Django web application and in that I have used drop down field using the code: <select id="countrynamew" name="countrynamew" value="{{countrynamew}}"> <option value="Abkhazia">Abkhazia</option> <option value="Afghanistan">Afghanistan</option> <option value="Albania">Albania</option> <option value="Algeria">Algeria</option> </select> How can I able to assign the selected value from Python code. And I have tried the code: countrynamew = 'Abkhazia' out = ('countrynamew': countrynamew) return render(request, 'xxx.html', out ) But, it does not assigns the value and how can I assign the value? Please suggest -
Django CSRF error with request on multiple tabs simultaneously
I am working on a Django project and have encountered an issue with CSRF tokens when rendering a page with a form. To reproduce the issue, I added a 5-second delay when rendering the page. Here is the scenario: I open the URL with the form in the first browser tab. Within 5 seconds, I open the same URL in a second tab, ensuring that the first request hasn't yet completed. As a result, the first tab generates a csrftoken, and the second tab overrides it. However, the csrfmiddlewaretoken in the form on the first tab remains bound to the old csrftoken. When I submit the form from the first tab, a CSRF error occurs due to the mismatch. Could you please help to fix this issue? Thanks in advance! -
Automatically create a free trial Stripe checkout
We use Stripe for our checkout and have a free trial enabled. So when a user comes to the site to enable the free trial they just enter their email in the checkout. What I would like is to tie the start of the free trial with creating an account on my site. Since I get the user's email with account creation I would like to create the free trial programmatically and remove that step. Is that possible? Here is my code to create the checkout session. def create_checkout_session(request, app_type): subscription_plan_duration = SubscriptionPlanDuration.objects.filter().first() user_subscription = UserSubscription.objects.create( subscription_plan_duration_id = subscription_plan_duration.id, user_id = request.user.id, app_type = app_type, is_active = False #True - change for 3. ) discount_coupon = DiscountCoupon.objects.filter(subscription_plan_duration_id = subscription_plan_duration.id).first() checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': subscription_plan_duration.price_id, 'quantity': 1, }, ], metadata={ "user_subscription_id": user_subscription.id }, mode="subscription", # discounts=[{ # 'coupon': discount_coupon.coupon_id, # }], subscription_data={ "trial_period_days": 30, "trial_settings": { "end_behavior": { "missing_payment_method": "cancel" } } }, payment_method_collection="if_required", allow_promotion_codes=True, success_url=settings.APP_END_POINT + '/stripe/success', cancel_url=settings.APP_END_POINT + '/stripe/cancel-subscription/' + app_type ) return redirect(checkout_session.url) -
Heroku Postgres not working on Heroku Server [Django]
I have a Django project, where I am using Redis/Celery to call some API's. I've set up my settings.py file to connect to the Postgres database and when running the Django project locally (with Redis/Celery running locally) the data is stored in the database no problem. When I push the application to Heroku, the data doesn't save to the database. I'm not sure if this sounds like a problem with the code itself, or the settings of the server causing this (Redis/Celery on Heroku). I am using a Heroku Postgres Database. Settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': 5432, } } db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) # The URL of the broker for celery to use CELERY_BROKER_URL = os.getenv('REDIS_URL', 'redis://localhost:6379/0') # The URL of the backend you want to use in case you wish to store the result of a task CELERY_RESULT_BACKEND = os.getenv('REDIS_URL', 'redis://localhost:6379/0') # The tasks you need to schedule CELERY_BEAT_SCHEDULE = { 'add_data': { 'task': 'comparasion.tasks.add_data_util', # Name of task 'schedule': 60.0 # Time in seconds } } Also the procfile: release: python manage.py migrate web: gunicorn Soccer.wsgi --log-file - worker: celery -A Soccer worker --loglevel=info beat: celery … -
request.session['some_variable'] TypeError: Object of type Decimal is not JSON serializable
I´m updating some code from Django 1.8 and python 2.7 to django 5.0 and python 3.11, in the old version in some functions are make session variables that store decimal values and after that make a redirect like this: request.sessions['decimal_var'] = 1.00 return HttpResponseRedirect('/somepage/') This works fine in the old version so the 'decimal_var' can be used in the redirected page, but in the new version (Django 5.0) if I pass any session variable with decimal value gives me this error: File "C:\Python311\Lib\json\__init__.py", line 238, in dumps **kw).encode(obj) ^^^^^^^^^^^ File "C:\Python311\Lib\json\encoder.py", line 200, in encode chunks = self.iterencode(o, _one_shot=True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python311\Lib\json\encoder.py", line 258, in iterencode return _iterencode(o, 0) ^^^^^^^^^^^^^^^^^ File "C:\Python311\Lib\json\encoder.py", line 180, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Decimal is not JSON serializable One option is just pass int or string values, but i think this is not a real solution and why the new versions can´t manage the decimal values and the old can, this could bring more problems if is a need to use decimal values. Is there a way to manage the decimal values in the session variables? -
Django Axes works, but doesn't store Access attempts nor failures
I apologize in advance, I am new to all of this (Stack, Django and Axes). I am creating a simple website where you can create users, and I implemented django axes. It works in a sense that it locks you out after failed attempts based on username and IP. It even logs them in Admin panel under Axes' own "Access logs". But the "Access attempts" and "Access failures" are empty. Below is my users/views.py code and under it is users/urls.py: @axes_dispatch def login(request): if request.user.is_authenticated: return redirect('home') if request.method == 'POST': form = UserLoginForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) if user is not None: auth_login(request, user) messages.success(request, f'Welcome back, {username}!') return redirect('home') # successful login redirect else: # signal for failed attempt signals.user_login_failed.send( sender=user.__class__, request=request, credentials={'username': username} ) messages.error(request, 'Invalid username or password.') else: # signal for invalid signals.user_login_failed.send( sender=None, request=request, credentials={'username': request.POST.get('username')} ) messages.error(request, 'Invalid username or password.') else: form = UserLoginForm() return render(request, 'users/login.html', {'form': form}) Here is the users urls.py: urlpatterns = [ path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), path('register/', views.register, name='register'), path('change_profile/', views.profile, name='change_profile'), path('change_password/', views.change_password, name='change_password'), path('lockout/', views.lockout, name='lockout'), ] -
Reverse for 'topics' not found. 'topics' is not a valid view function or pattern name
<p> <a href="{% url 'learning_logs:index' %}">Learning Log</a> <a href="{% url 'learning_logs:topics' %}">Topics</a> </p> {% block content %}{% endblock content %} I get that error: Reverse for 'topics' not found. 'topics' is not a valid view function or pattern name. at this line: <a href="{% url 'learning_logs:topics' %}">Topics</a> Here I creat views: from django.shortcuts import render from .models import Topic # Create your views here. def index(request): """Main page for app Learning Logs""" return render(request, 'learning_logs/index.html') # A view of topics def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic':topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) Here is a template of topics: {% extends "learning_logs/base.html" %} {% block content %} <p> Topics </p> <ul> <!--this is a for loop which iterates through topics--> {% for topic in topics %} <li> <a href = "{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a> </li> {% empty %} <li>No topic has been added yet</li> </ul> {% endblock content %} I am new to Django and I don't understand why this problem appeared. -
Making map with markers and popups
I want to show a map in the frontend with some markers on it. Also I want to write an event for every marker so when you click, you see a popup. Is that possible with javascript? How? Wich library I have to use? Thanks! -
Separate Django API and Django regular templates views
I'm starting a project which will have a website and a mobile app. I want these two to use the same backend, which I'll code in Django, specifically django-ninja. For the website front-end, I want to use Django also as I'm familiar with it already and I feel it suits my needs for this project. The question is: should I create 2 separate Django projects, one dedicated to the API, and one dedicated to the "Front-end", or have them both in the same project? -
Problem django-autocomplete-light! new version chrome
I have a django application with python 3.7 and Django 2.2.10, which uses django admin, with the materialize css subscript for the templates. From the latest Chrome updates, the behavior of forms in modal is showing a rendering problem. A widget was customized to fit the forms: class Select2Widget(Select2WidgetMixin): def _get_language_code(self): return 'pt-BR' @property def media(self): """Return JS/CSS resources for the widget.""" return forms.Media( js=( 'autocomplete_light/jquery.init.js', STATIC_URL + 'js/select2.full.js', # 'vendor/select2/dist/js/select2.full.js', 'autocomplete_light/autocomplete.init.js', 'autocomplete_light/forward.js', 'autocomplete_light/select2.js', 'autocomplete_light/jquery.post-setup.js', ), css={ 'screen': ( 'vendor/select2/dist/css/select2.min.css', 'admin/css/autocomplete.css', 'autocomplete_light/select2.css', ), }, ) autocomplete_function = 'select2' """ retorna queryset na ordem que foi selecionado no field """ class QuerySetSelect(WidgetMixin): def filter_choices_to_render(self, selected_choices): preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(selected_choices)]) """Filter out un-selected choices if choices is a QuerySet.""" self.choices.queryset = self.choices.queryset.filter(pk__in=[c for c in selected_choices if c]).order_by(preserved) class ModelSelect2(QuerySetSelectMixin, Select2Widget, forms.Select): ... class ModelSelect2Multiple(QuerySetSelectMixin, Select2Widget, forms.SelectMultiple): ... class Select2Multiple(Select2Widget, SelectMultiple): ... Use below in forms class PessoaForm(ModelForm): ativo = forms.BooleanField(required=False) cpf_cnpj = BRCPFCNPJField(label='CPF/CNPJ', max_length=14) logradouro = forms.ModelChoiceField(queryset=Logradouro.objects, required=False, label='CEP', widget=ModelSelect2(url='logradouro_autocomplete', attrs={'data-placeholder': 'Informe o CEP', 'style': 'width: 100%;', 'data-minimum-input-length': 8, 'class':'material-ignore', 'material-ignore': True}),) municipio = forms.ModelChoiceField(queryset=Municipio.objects, label='Município', required=False, widget=ModelSelect2(url='logradouro_municipio_autocomplete', forward=['logradouro'], attrs={'style': 'width: 100%;', 'data-placeholder': 'Selecione', 'class': 'material-ignore', 'material-ignore': True })) local_emissao_cnh = forms.ModelChoiceField(queryset=Municipio.objects, label='Municipio Emissão da CNH', … -
ConnectionError:Socket connection error ssl wrap: [WinError 10054] An existing connection was forcibly closed by the host
from django.shortcuts import render, redirect from django.contrib import messages from django.core.management import call_command from ldap3 import Server, Connection, ALL from .forms import LDAPConfigForm from .models import LDAPConfig def ldap_config_view(request): if request.method == 'POST': form = LDAPConfigForm(request.POST) if form.is_valid(): server = Server(form.cleaned_data['server'],get_info=ALL) connection = Connection( server, user=form.cleaned_data['user_dn'], password=form.cleaned_data['password'], authentication="SIMPLE" ) print(connection.result) # Test LDAP connection # server = Server(config.server, get_info=ALL) # connection = Connection(server, user=config.user_dn, password=config.password, authentication="SIMPLE") print(connection) try: if connection.bind(): LDAPConfig.objects.all().delete() config = form.save() # Run sync_ldap command call_command('sync_ldap') messages.success(request, 'Connection successful!') return redirect('ldap_config') else: messages.error(request, 'Connection failed!') except Exception as e: messages.error(request, f'Connection error: {e}') else: messages.error(request, 'Invalid form data!') else: form = LDAPConfigForm() return render(request, 'ldap_sync/ldap_config_form.html', {'form': form})' In this code I am trying to connect the LDAP sever to my Django project with ldap3 package while I try to connect to the server I got the Error as ConnectionError:Socket connection error ssl wrap: [WinError 10054] An existing connection was forcibly closed by the host. Actually I am using the Hyper v virtual machine in my local machine to create the AD DS server. I have tried with the OpenLdap server from https://www.forumsys.com/2022/05/10/online-ldap-test-server/ While I try with this site credentials I am able to fetch the users in … -
How to localize Django duplicate key value violates unique constraint error message?
Problem description I would want to provide clear localized error messages to client using Django. I have the following unique field: class Foo(models.Model) email = models.EmailField(max_length=255, unique=True, default=None, blank=True, null=True, verbose_name=gettext_lazy('email address'), error_messages={'unique': gettext_lazy("Email address is already registered to another user.")}) When I try to save duplicate email address, I still get an error psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "foo_email_key" Question Why is my error message not localized? How can be the desired behaviour obtained? -
AsyncIO: Program still runs in a synchronous manner despite using AsyncIO in Django
I have created an API named APIDummyWait5. Now I want to test the following - I want the API to return the result in few milliseconds. - While the function that is being called inside the API should run in an asynchronous manner. The API - APIDummyWait5 randomly generates a number in between 1 - 25 and then sends that as an argument to a function named get_country_details along with another parameter named country that I will be fetching from API url params. Here is the API class APIDummyWait5(APIView): def get(self, request): print("Coming Here") worker = os.getpid() thread = threading.get_ident() country = request.GET.get('country') print(f"API wait 5 - for worker - {worker} at Thread {thread} starting at: {datetime.datetime.now()}") wait_time = rd.randint(1, 25) response = {'wait_time': wait_time, 'country': country} asyncio.run(main(wait_time=wait_time, country=country)) print(f"API Wait 5 - for worker - {worker} at Thread {thread} ending at: {datetime.datetime.now()}") return Response({ "data": response }) async def main(wait_time, country): result = await get_country_details(wait_time, country) I am creating a helper function named main to call the get_country_details function. The function - get_country_details actually sleeps for the wait time and then calls a third party API to fetch the name and capital of a country and store it in … -
Django different models' m2m relations fields comparsion related to same m2m model
I'm following this question to filter on M2M field: Django filter queryset __in for *every* item in list I'm using .annotation approach. My models: class Options(models.Model): name = models.CharField(max_length=50) class Product(models.Model): options = models.ManyToMany(Category) class Item(models.Model): options = models.ManyToMany(Category) I'm trying to filter Product instance to contain all categories as Item instance has: items = Item.objects.all() for item in items: item_options = [option.name for option in item.options.all()] queryset=models.Product.objects.filter( status=Status.COMPLETED, )\ .filter(options__name__in=item_options)\ .annotate(num_options=Count("options"))\ .filter(num_options=len(item_options)) It works in most cases except when Item doesn't contains any options. In this case I woul d like to match Product instance which also haven't any options but it fails returning no objects. -
How should I store google login info sent from frontend in backend Django? [closed]
In my Django application, I want to implement Google and Apple login. For Google login, the frontend (using Firebase Authentication) sends me the following details: Google ID, display name, email, and photo URL. How should I store this data in the backend so that users can log in again in the future? Should I use the django-allauth package (which requires setting up social providers with client ID and secret), or should I manually store the data in the default users table? Could you suggest the best approach? Thanks! -
How can we activate the dropdown menu items on the Wagtail Bakerydemo website?
I encountered an issue with the bakerydemo an Wagtail demo site. When clicking on "bread" menu item or its dropdown label, the submenu items did not display, despite marking the "Show in menus" checkbox for the child pages. Your prompt attention to this matter would be greatly appreciated.d up for child pages. -
Django OAuth2 Authentication Failing in Unit Tests - 401 'invalid_client' Error
I've been stuck on this issue for 3 days now, and I'm hoping someone can help me out. I'm trying to implement OAuth2 authentication for my Django backend with a REST interface. However, my unit tests for authentication are failing, and I'm getting a 401 error with the message 'invalid_client' instead of the expected 200 status code. My user model is configured to use email as the user ID. Here's the relevant part of my user model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) roles = models.ManyToManyField(UserRole, related_name="roles") objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model( email=email, **extra_fields) if password: user.set_password(password) else: user.set_unusable_password() user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields)` My Django settings from .settings import * # Use an in-memory SQLite database for testing DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } … -
Adding CSS styles to dynamically created HTML elements in JavaScript
I'm working on a Django project and I have an index.html file where I've connected a JavaScript file using the following script tag: <script src="{% static 'assets/js/bubble.js' %}"></script> In my JavaScript file, I have the following code: console.log("Bubble"); // Get the speech bubble container const speechBubbleContainer = document.querySelector('.speech-bubble-container'); // Function to create a speech bubble function createSpeechBubble(message) { const speechBubble = document.createElement('div'); speechBubble.style = ` background-color: #fff; border-radius: 10px; padding: 10px; font-size: 16px; font-weight: bold; color: #333; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); opacity: 1; transition: opacity 2s; `; speechBubble.textContent = message; speechBubbleContainer.appendChild(speechBubble); // Remove the speech bubble after 2 seconds setTimeout(() => { speechBubble.style.opacity = 0; setTimeout(() => { speechBubble.remove(); }, 2000); }, 2000); } // Create a speech bubble every 30 seconds setInterval(() => { createSpeechBubble('Hi'); }, 3000); And here's my HTML code: <div class="floating-button" style="..."> <!-- button styles --> <img src="..." alt="Button Image" style="..."> <!-- image styles --> <div class="speech-bubble-container" style="..."></div> </div> I want to add CSS styles to the dynamically created speech-bubble elements, but I'm not sure how to do it. I've tried adding the styles directly to the HTML elements, but it's not working as expected. Can someone help me figure out how … -
django import_export lib buttons not showing in admin site
from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import members @admin.register(members) class MembersAdmin(ImportExportModelAdmin): pass this is my code in admin.py .actually i am trying to use import-export lib for my project while running in server it show the models i have created but its not showing the button where we can import export.(btw i am a noob in this field) i need answer for my queries related to the python django library -
Empty Dynamic Nested Serializer for Generic Django Model
I have this generic Model called Thumbs with two fields which can describe another model. The two fields are: 'entity_type', a CharField values can be a family or product, both corresponding to Family and Product models, respectively Then there's 'entity_id', a IntegerField this is the PrimaryKey for the previous entity in another table. So, I want to create a serializer for this Thumbs model which implements a nested serializer for the specified 'entity_type'. For example, if the 'entity_type' is family, the serializer used a FamilySerializer so the serialized Thumbs object has the entity's data. This is how I implemented that behavior, but it is returning an empty family object. from rest_framework import serializers from app.models import Thumbs, Family from app.serializers.user_role_product_tool import FamilySerializer, ProductSerializer class ThumbSerializer(serializers.ModelSerializer): entity = serializers.SerializerMethodField() class Meta: model = Thumbs fields = '__all__' def get_entity(self, obj): if obj.entity_type == "family": return FamilySerializer(source=obj.entity_id, read_only=True).data else: return None Example output showing the Family serializer is being used when expected, but it's empty although the Family table has an entry with PrimaryKey of 107: { "id": 182, "entity": { "family_name": "", "status": "", "created_by": "", "last_updated_by": "" }, "entity_id": "107", "entity_type": "family", "thumbs_decision": "PENDING", "entity_parent_id": "181", "created_date": "2024-09-03T14:21:17.403159-07:00", "last_updated_by": "", … -
Problem creating a user with Social Django
In my settings.py I have - INSTALLED_APPS = [ *** 'social_django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] # Authentication backends AUTHENTICATION_BACKENDS = ( 'cloud.social_auth_backends.CustomGoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) # Google OAuth2 credentials SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.getenv('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.getenv('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET') # Login and logout redirection LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' In my project's urls.py I have - from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('cloud.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('auth/', include('social_django.urls', namespace='social')), ] urlpatterns += [ path("ckeditor5/", include('django_ckeditor_5.urls'), name="ck_editor_5_upload_file"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my social_auth_backends.py I have - from django.contrib.auth import get_user_model from social_core.backends.google import GoogleOAuth2 class CustomGoogleOAuth2(GoogleOAuth2): def user_data(self, access_token, *args, **kwargs): print(f"Fetching user data with access token: {access_token}") data = super().user_data(access_token, *args, **kwargs) print(f"User data fetched: {data}") return data def new_user(self, user, *args, **kwargs): email = user.email print(f"Creating a new user with email: {email}") if not email: raise ValueError("Email is required to create a user.") User = get_user_model() username = email.split('@')[0] print(f"Attempting to get or create user with email: {email} and username: {username}") user, created = User.objects.get_or_create( email=email, defaults={'username': username} ) if created: print(f"User created with email: {email}") user.set_unusable_password() … -
(unicode error) 'utf-8' codec can't decode byte 0xf3
I'm using django 5.0.8 and python 3.11, so in my view i use this: context = RequestContext(request, { 'title':'sómething', 'formLogin': formLogin }) As you can see i pass string with 'ó' value, when i try to run my project gives me the error '(unicode error) 'utf-8' codec can't decode byte 0xf3' this happen with any special characters for what i know using '# -- coding: utf-8 --' at first in my view solve this, but not now, what can i do?