Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Como verifico o valor de uma variável que uma função das views retorna DJANGO
Estou a criar uma web application com o django, que contem um pequeno formulário com 3 campos e quando o usuário os preenche é gerado um ficheiro excel, este ficheiro está associado a um botão de download que só fica ativo quando o ficheiro foi gerado. Neste momento eu tenho o ficheiro e o botão deveria estar ativo mas eu penso que o problema é que não estou a conseguir passar a informação para o html de forma correta. urls.py app_name = 'form' urlpatterns = [ path('', views.index, name='index'), path('find_csv/', views.valid_csv_exist, name='valid_csv_exist'), path('download/', views.download_csv, name='download_csv'), path('', execute.execute, name='execute'), ] função da qual necessito da variável no html def valid_csv_exist(): # Define o caminho onde procurar o ficheiro path_files = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + f'/form/Exports/{client}/{execute.date_folder}' # Array with names of files files = [f for f in listdir(path_files) if isfile(join(path_files, f))] if 'tasksinfo.csv' in files: csv_file = True else: csv_file = False return csv_file parte do ficheiro html onde quero usar o valor retornado pela função {% if csv_file is True %} <a href="{% url 'form:download_csv' %}" download><button class="btn"> <i class="fa fa-download"></i>Download CSV File</button> </a> {% else %} <a href="/form" download><button class="btn" disabled> <i class="fa fa-download"></i>Download CSV File</button> </a> {% endif %} O … -
Django cannot find the settings.py file
I forgot the password to my admin page. I found a solution but in order to change it I had to include DJANGO_SETTINGS_MODULE to system path and pointed it to settings.py file in my folder, I did so. Since then I'm getting this error ModuleNotFoundError: No module named 'C:\\Users\\manda\\PycharmProjects\\firstsite\\firstsite\\settings' I revert back all my changes I made in files and removed 'DJANGO_SETTINGS_MODULE' from environment variable but nothing happened. -
How to make a permission that just allow users to modify only their own data in DRF
I'm trying to create a custom permission that prevents user to modify others user data.So far I'd tried this but is not working. the idea is to compare user id taken from the token against the user id fk designated to the object. costume permission class SameUserTransactionPermission(BasePermission): message = 'hey usuario no autorizado' def has_object_permission(self, request, view, obj): if obj.user_id_id != request.user.id or request.user_id_id != request.user.id: return False return True Model class Transactions(models.Model): TRANSACTION_TYPE = [(1, "Ingresos"), (2, "Egresos")] type = models.IntegerField( choices=TRANSACTION_TYPE, verbose_name="Tipo", blank=False, null=False) user_id = models.ForeignKey( 'expenseApi.Users', verbose_name="Usuario", blank=False, null=False, on_delete=models.PROTECT) description = models.CharField( verbose_name="Concepto", blank=False, null=False, max_length=50) date = models.DateTimeField( verbose_name="Fecha", editable=False, auto_now_add=True) amount = models.FloatField(verbose_name="Monto", blank=False, null=False, validators=[MinValueValidator(MIN_AMOUNT)]) class Meta: ordering = ['-date'] def __str__(self): return '{}'.format(self.pk) I want it to affect all hhtp methods. -
(Angular + Django REST) Suppress Browser Auth Dialog?
I use JWT Authentication for my Angular + Django REST project. Recently the browser keeps showing the Basic auth dialog whenever the token expires. I know by removing/changing the WWW-Authenticate header can suppress the dialog but I could not get it to work. On Django, I have tried to use a custom Response object to force the response header: def BaseResponse(data, status=None, template_name=None, headers=None, content_type=None): response = Response(data, status, template_name, {'WWW-Authenticate': 'xBasic'}, content_type=None) response['WWW-Authenticate'] = 'xBasic' return response Also I have tried to use a middleware: AuthHeaderMiddleware.py class AuthHeaderMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_response(self, request, response): if response.status == 401: r = Response(response.data, response.status, response.template_name, {'WWW-Authenticate': 'xBasic'}, response.content_type) return response Middleware settings in settings.py: 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', 'corsheaders.middleware.CorsMiddleware', 'middleware.AuthHeaderMiddleware', ] The problem is the WWW-Authenticate header remains Basic for all 401 responses (but 'xBasic' for other statuses). I use the djangorestframework-simplejwt package in Django. On Angular, I have tried to force a blank token with the Bearer declaration for the Authorization header: add_header(request, token=null) { var r = request.clone({ setHeaders: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${request.withCredentials ? token : ''}` } }); return r; } … -
Count & Sum of Order Values for each customer (through iteration) in Django
I have Customer & Order models as below: class Customer(models.Model): name = models.CharField(max_length = 100) city = models.CharField(max_length = 100) class Order(models.Model): value = models.FloatField() customer = models.ForeignKey(Customer, on_delete=models.CASCADE) Now I would like to generate a table of (distinct) customers along with a count of number of orders placed by each of them and the sum of values of those orders. I tried this in the views.py: def customers(request): customer_orders = Order.objects.distinct().annotate(Sum('value')) Then in my html template, I tried the following: <ul> {% for customer in customer_orders %} <li>{{customer.customer}} - {{customer.value__sum}}<li> {% endfor %} </ul> After all this, instead of getting unique customers (and respective order records), I'm getting a list of all orders and customers are getting repeated (as shown below). Not sure what I'm missing here. Bosco-Ward - 16,700.0 Ernser PLC - 51,200.0 Murphy Ltd - 21,400.0 Kohler-Veum - 29,200.0 Schmidt-Legros - 96,800.0 Brown-Weissnat - 8,200.0 Bosco-Ward - 36,400.0 Ernser PLC - 66,600.0 Murphy Ltd - 84,200.0 Also wanted to know if there's a possibility to generate a table of city names with order count and total value of orders received from that city (note that my order model doesn't have city field). -
Cannot store image as binary in mysql django and also check the size of the image in forms.py
I am creating a website in django. I need to store the image as binary in mysql database as well as check its size before saving. Tried many ways nothing seems to help. views.py def client_create_view(request): base_form = ClientForm(None, initial=initial_data) context={ "form": base_form } if request.method == 'POST': form = ClientForm(request.POST,request.FILES) if form.is_valid(): form.save() return render(request,'cc.html',context) forms.py class ClientForm(ModelForm): def clean(self): super(ClientForm, self).clean() photo_image = self.cleaned_data['photo'].file.read() if photo_image.file_size > 0.250: raise ValidationError(['Image Size should be lower than 250kb']) html <form method="post" enctype='multipart/form-data'> #some data </form> -
How to filter data in the backend for displaying geotags via GeoJSONLayerView to the Map
I need to display weather stations only in the areas(filter by id_ugms) of the country that the user chooses. But the geodjango tools do not allow you to filter the data in the backend. GeoJSONLayerView extracts all the data from the table, and I have to filter the entire list in leaflet on the frontend. There are a lot of records in the table, which is why the response time is very long(it takes more than 5 minutes to display and filter), or it crashes from the server altogether. How do I do backend filtering? Maybe there's another way? I tried just to make a selection, and serialize the data via geojsonserializer - nothing worked, leaflet does not give an error of input data. Technology stack: Postgis, Django, Leaflet. There is a model of my entity: models.py class WeatherStation(gismodels.Model): id_station = models.IntegerField(primary_key=True) station_index = models.IntegerField(default = None) name_station_rus = models.CharField(default="", max_length=256) name_station_en = models.CharField(default="", max_length=256) id_ugms = models.ForeignKey(Ugms, on_delete=models.CASCADE, default = None) id_country = models.ForeignKey(Country, on_delete=models.CASCADE, default = None) id_subrf = models.ForeignKey(Subrf, on_delete=models.CASCADE, default = None) latitude = models.CharField(default ="", max_length=256) longitude = models.CharField(default ="", max_length=256) geom = gismodels.PointField(default ='POINT EMPTY',srid = 4326) objects = gismodels.Manager() height_above_sea = models.CharField(default="", max_length=256) … -
Open a file from a network drive django in a new tab
I'm trying to have a table that opens an invoice in a new tab but I'm not getting on how to use the url format to have the mapping done to a shared network folder. I'm trying by doing the following in the table definition <tbody> {% for datarow in dataset %} <tr> <td>{{datarow.supplierName}}</td> <td>{{datarow.invoiceNumber}}</td> <td>{{datarow.reference}}</td> <td><a href = "open(r'\\REMOTESERVER\Shared1\FOLDER\FOLDER Images\{{datarow.docId|urlize}}\file.tiff')">Open Invoice</a> {% endfor %} </tr> </tbody> however it doesn't open as the url still tries to map from localhost. Also in each folder I have one .tiff file but other files as well, I'm also looking into having a way to open that .tiff file (different name per folder) to be used in the url but I haven't got there yet. -
How to access javascript variable in Django template
How can I update a javascript variable and use it in a if statement? <button onclick="hire = true"> Hire </button> {% if hire %} //does not work <!-- print something --> {% endif %} <script> let hire = false; </script> I tried to declare the variable in views.py but then I can't update it in the template -
# replacing url template tag in django
On my home page I have my navbar and in my navbar i have a link for the about page and use the template url tag inside a href which looks like this <a href="{% url 'about' %}" class="nav-link">About</a> But when i run my project and view it in a preview window it does not work. When clicked on a # key appears in the url where '/about' should appear. when i use googles dev tools to look at the element # is inside the href instead of the template url tag and when i edit the html in google dev tools and change it to '/about/' the link works and takes me to the about page and i dont know why this is happening here is the code in my /about/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.about, name='about'), ] and here is the code inside my /about/views.py from django.shortcuts import render from django.http import HttpResponse def about(request): return render(request, 'about/about.html') any help is much appreciated and thank you in advance -
how to append result loop into list
How i can append every value that total_penjualan1 give? this code will append just last total_penjualan1 result, what i must change? agen = UserAddress.objects.filter(status="Agen") for tampungini in agen: postingan_list2 = WriteStream.objects.filter(created_at__year=pkk, created_at__month=pk, nama_userr=tampungini.nama) for tampunglain in postingan_list2: get_transactions = api.getaddresstransaction(tampunglain.userr, tampunglain.address) amount = get_transactions['balance'].get('assets')[0].get('qty') total_penjualan1 = total_penjualan1 + amount tampunganjumlah = [] if total_penjualan1 >=1: tampunganjumlah.append(total_penjualan1) total_penjualan1 = 0 -
Django order by to just put all Null at the end
There is the django order by method, here is an example: Purchase.objects.all().order_by(F('price').desc(nulls_last=True)) This will order by the field price with the additional constraint to have all nulls as last. I want something slightly different, take this example: I have a queryset of Purchase with the following prices in THIS EXACT ORDER: [5, None, 13, None, 2] I want to order by so the result is like this [5, 13, 2, None, None] Basically I am looking for a way to simply move all instances where price=None at the end, not affecting the order of the rest of the elements in the queryset. The method in the example at the top would also sort the rest of the elements in descendent order which I do no want. Any help appreciated if this is even possible. -
How to call Django API with Javascript with Authenticated user in Django
I'm using Django for Backend, PostgresSQL as DB and HTML, CSS and Javascript as Frontend. I am calling Django API via Javascript. Where user is adding a product to a cart, and I'm calling the cart with DRF to show all the data to the user. But problem is that, user can see all the data of other user. So, how can authenticated user can see his/her selected product on a cart. Here is a detailed code: views.py adding product to cart def addProduct(request): user = request.user product_id = request.GET.get('product_id') product_cart = Product.objects.get(id=product_id) Cart(user=user, product=product_cart).save() return render(request, 'cart/addtocart.html') Api View (views.py) @api_view(['GET']) def showproduct(request): if request.method == 'GET': result = Cart.objects.all() serialize = productserializers(result, many = True) return Response(serialize.data) serializer.py from .models import * from rest_framework import serializers class productserializers(serializers.ModelSerializer): class Meta: model = Cart fields = '__all__' depth = 1 Javascript to call Django API $(document).ready(function() { $.ajax({ url: 'http://127.0.0.1:8000/showproduct/', dataType: 'JSON', success: function(data){ for (var i = 0; i < data.length; i++) { var row = $('<tr> .. ..........</tr>'); $("#table").append(row); } } }); }); NOW, How to show the specific user(authenticated user) there specific cart item. -
Django get all objects that contains a pk of a many to many relationship
I have the following model and I need to retrieve all the subscriptions that have among their connected subscriptions a subscription (of which I know the primary key) In practice I need all the subscriptions that contains a subscription in their connected_subscription field Subscription(models.Model): connected_subscriptions=models.ManyToManyField('self', blank=True) How can I retrieve all the subscriptions? Subscription.objects.filter(connected_subscription__???=subscription_key) -
Ruby on Rails download freezes while downloading
I have installed ruby on rails and about to create a project while downloading the dependencies using git bash it freezes at some point please help. -
How to connect my filter form to filter view Django?
I have such html form on my page: <form action="{% url 'filter' %}" method="get"> <h2>Color:</h2> <input type="checkbox" name="red" id="">Red<br> <input type="checkbox" name="blue" id="">Blue<br> <h2>Material:</h2> <input type="checkbox" name="wood" id="">Wood<br> <input type="checkbox" name="plastic" id="">Plastic<br> <input type="checkbox" name="metal" id="">Metal<br> <button type="submit">Find!</button> </form> My Django model: class Toy(models.Model): COLORS = ( ('Blue', 'Blue'), ('Red', 'Red') ) MATERIALS = ( ('Plastic', 'Plastic'), ('Wood', 'Wood'), ('Metal', 'Metal') ) photo = models.ImageField(upload_to='images/', blank=True) title = models.CharField(max_length=128, blank=False) description = models.CharField(max_length=5000, blank=False) price = models.PositiveIntegerField(blank=False) count = models.PositiveIntegerField(blank=False) color = models.CharField(max_length=128, blank=False, choices=COLORS) material = models.CharField(max_length=128, blank=False, choices=MATERIALS) and my view.py def filter(request): products = Toy.objects.all() material = request.GET.get("material") color = request.GET.get("color") if material: products = products.filter(material__in=material) if color: products = products.filter(color__in=color) return render(request, 'catalog/products.html', {'products': products}) It should check my checkboxes and filter toys from a database that satisfied checked checkboxes -
How to manage password when entegrating sign with google/facebook?
I'm working on register with social media. When I get data from auth token, google or facebook doesn't sent anything about password. How should I manage that? Or should I use same password for every user as above? def register_social_user(provider,email,name): filtered_user_by_email = User.objects.filter(email=email) if filtered_user_by_email.exists(): if provider == filtered_user_by_email[0].auth_provider: registered_user = authenticate(email = email,password="test") return{ 'email': registered_user.email, } else: raise AuthenticationFailed( detail='Please continue your login using '+ filtered_user_by_email[0].auth_provider ) else: user = { 'email':email, 'password': "test" } user = User.objects.create_user(**user) user.is_active = True user.auth_provider = provider user.save() new_user = authenticate(email=email,password = "test") print("new_user : ",new_user) return { 'email':new_user.email } -
Correct way of implementing custom 404 page in Django 3 in production
I’ve tried importing and editing handler404 in urls.py, made sure pointed to right template etc but kept getting server 500 error responses. The only way I could get it to work was changing return render( to return HttpResponseNotFound( but in that case I only get the text representation of ‘mysite.views.404_error.html’ as need to return HTML directly with HttpResponseNotFound. Wondering what is the correct way to return a custom 404 error template. Thanks a lot. -
DRF - Djoser: Setting 'USER_CREATE_PASSWORD_RETYPE': True overrides other User Model fields
from .models import User from djoser.serializers import UserCreateSerializer, UserSerializer class UserCreateSerializer(UserCreateSerializer): phone = serializers.IntegerField() class Meta(UserCreateSerializer.Meta): model = User fields = ['username', 'email', 'password','first_name','last_name','phone'] When 'USER_CREATE_PASSWORD_RETYPE': True is not used DJOSER = { 'LOGIN_FIELD': 'email', # 'USER_CREATE_PASSWORD_RETYPE': True, 'SERIALIZERS': { 'user_create': 'djangopwa.apps.restapi.serializers.UserCreateSerializer', 'user': 'djangopwa.apps.restapi.serializers.UserSerializer', }, } /users { "username": "", "email": "", "password": "", "first_name": "", "last_name": "", "phone": null } when 'USER_CREATE_PASSWORD_RETYPE': True is used only 3 fields are seen. DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'SERIALIZERS': { 'user_create': 'djangopwa.apps.restapi.serializers.UserCreateSerializer', 'user': 'djangopwa.apps.restapi.serializers.UserSerializer', }, } /users { "email": "", "password": "", "re_password": "" } -
Setting up continuous integration with django 3, postgres and gitlab CI
I'm setting up a continuous integration with Django 3 and Gitlab CI. Having done it previously with Django 2 but now I'm struggling to get things done with Django 3. This warning is shown and I'm wondering if it's the reason : /usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py:304: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. And this error at the end : django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known Here is my config : image: python:3.8 services: - postgres:10.17 variables: POSTGRES_DB : db_test POSTGRES_USER : postgres POSTGRES_PASSWORD : "" POSTGRES_HOST : postgres POSTGRES_PORT : 5432 stages: - tests cache: paths: - ~/.cache/pip/ before_script: - python -V - apt-get update && apt install -y -qq python3-pip - pip install -r requirements.txt test: stage: tests variables: DATABASE_URL: "postgres://postgres:postgres@postgres:5432/$POSTGRES_DB" script: - coverage run manage.py test - coverage report coverage: "/TOTAL.+ ([0-9]{1,3}%)/" Will be grateful if somebody can help me fix this. -
PyCharm type hinting issue: 'Expected type 'str', got 'TruncatingCharField' instead'
I have a custom TruncatingCharField that overrides the general CharField in django: class TruncatingCharField(models.CharField): def get_prep_value(self, value): if value: value = value[:self.max_length] return super().get_prep_value(value) I the use it in a model: class Cartoon(models.Model): authors = JSONField(default=list, blank=True, null=True) title = TruncatingCharField(max_length=400, blank=True) Now, when I define the Cartoon model's methods involving TruncatingCharField, I am getting PyCharm's type hinting warnings. Interestingly, they are shown only when I use an 'if,' for example: def one(self): if self.title: a = '(' + self.title # Expected type 'str', got 'TruncatingCharField' instead return self.title + self.title + 'a' # Class 'TruncatingCharField does not define '__add__' method, so the '+' operator cannot be used on its instances def two(self): a = '(' + self.title # no warnings return self.title + self.title + 'a' # no warnings If I change the 'title' field to the general CharField, the warnings disappear. The code is working fine, the problem is just in the distracting warnings. Django support is enable in the settings. What am I doing wrong? -
Getting results with the correct time zone shift (Postgresql, Django)
In my project (Django, using Postgresql) I need to display statistics on the number of registered users by day. In the database, all time fields are stored with the UTC zone. In settings.py parameters set: USE_TZ = True TIME_ZONE = 'Europe/Moscow' Code in a view that returns this stitistic: (date1 & date2 parameters are obtained from a request) self.queryset = User.objects if date1 and date2: self.queryset = self.queryset.filter( created_at__range=(date1, date2.replace(hour=23, minute=59, second=59)) ) self.queryset = self.queryset \ .extra({'day': "date(created_at)"}) \ .values("day") \ .annotate( count=Count("id"), site_count=Count("id", filter=Q(account_type=User.TYPE_WEBSITE)), bot_count=Count("id", filter=Q(account_type=User.TYPE_TELEGRAM)), ) \ .order_by('day') return Response({ "new_users": self.queryset }) Unfortunately, if I specify date parameters both '2021-05-11', then the "wrong" answer will be formed: "new_users": [ { "day": "2021-05-10", "count": 2, "site_count": 1, "bot_count": 1 }, { "day": "2021-05-11", "count": 4, "site_count": 2, "bot_count": 2 } ], We see the two days instead of one. The following SQL is generated by Django: SELECT (date(created_at)) AS "day", COUNT("authentication_user"."id") AS "count", COUNT("authentication_user"."id") FILTER (WHERE "authentication_user"."account_type" = 'Website') AS "site_count", COUNT("authentication_user"."id") FILTER (WHERE "authentication_user"."account_type" = 'Telegram') AS "bot_count" FROM "authentication_user" WHERE "authentication_user"."created_at" BETWEEN '2021-05-11 00:00:00+03:00' AND '2021-05-11 23:59:59+03:00' GROUP BY (date(created_at) ) ORDER BY "day" ASC I experimented and made select queries manually: SELECT * from … -
Django Widgets with Bootstrap
I am trying to stylize my form using bootstrap. As you know bootstrap uses a lot of classes in order to do what it does. By googling I have found to inject some new classes into my form I could use widgets with django. My form is as follows: class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password1'].label = 'Password' self.fields['password2'].label = 'Password Confirmation' self.fields['first_name'].label = 'First Name' self.fields['last_name'].label = 'Last Name' self.fields['password1'].help_text = None self.fields['password2'].help_text = None class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) help_texts = { 'username': None, } widgets = { 'username': forms.TextInput( attrs={ 'class': 'form-control' } ), 'first_name': forms.TextInput( attrs={ 'class': 'form-control' } ), 'last_name': forms.TextInput( attrs={ 'class': 'form-control' } ), 'email': forms.EmailInput( attrs={ 'class': 'form-control' } ), 'password1': forms.PasswordInput( attrs={ 'class': 'form-control' } ), 'password2': forms.PasswordInput( attrs={ 'class': 'form-control' } ) } But for some reason this is only applying the class to the username field in HTML. It does not apply the class 'form-control' to anything else. Is this some simple format issue I am overlooking or am I doing something wrong? Any help is greatly appreciated! -
Uploading multiple files to django database at once not working
I have a problem with django and it is that I cannot handle the files that I am uploading to a File Uploader. The File Uploader that I am using is the one that we can download in Bootstrap Studio called "Drag and Drop Multiple File Form Input upload" whose code (modified with the csrf_token necessary to make it work in django) is the following: HTML <div id="backdrop" class="backdrop backdrop-transition backdrop-dark"> <div class="text-center w-100" style="position: absolute;top: 50%;"> <div class="bg-light border rounded border-success shadow-lg m-auto" style="width: 150px;height: 150px;"><i class="fa fa-upload d-block p-4" style="font-size: 50px;"></i><span>Drop file to attach</span></div> </div> </div> <div class="jumbotron pt-1"> <div class="alert alert-success invisible mt-5" role="alert"><span id="notify"></span></div> <h1>Subir Ficheros<br></h1> <p><label for="form-files"><a class="btn btn-secondary btn-sm" role="button">Seleccione ficheros</a></label>&nbsp;o arrastre los ficheros a cualquier lugar de la página.<br></p> <p id="filecount"><br></p> <div id="list"></div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="form-files" class="invisible" name="files" multiple=""> <button class="btn btn-outline-primary btn-block" type="submit">Procesar</button> <button class="btn btn-danger mt-5" type="reset" onclick="clearFiles()">Reiniciar</button> </form> </div> <div class="text-center bg-light border rounded border-dark shadow-lg p-3"><img id="image_preview" width="100"> <div><button class="btn btn-warning btn-sm m-3" onclick="previewClose()">Cerrar</button></div> </div> JS var dt_allowed=false,readerfiles,drop,fileCount,fileinput,backdrop,notify,list,listwait,listsync=false,image_preview; addEventHandler(window, 'load', function () { init_elements(); init_fileinput(); if (window.FileReader && window.DataTransfer) { init_datatransfer(); } else { notify_msg('Your browser does not support the HTML5 FileReader.<br/> Drag … -
Allauth social_account_added signal not sent
views.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(social_account_added) def after_social_account_added(request, sociallogin, **kwargs): profile = Profile.objects.filter(user=request.user).first() sc = sociallogin.account if DEFAULT_PP in profile.avatar.url: if sc.provider == 'facebook': profile.avatar = f"http://graph.facebook.com/{sociallogin.account.uid}/picture" else: profile.avatar = sc.extra_data[ALL_AUTH_IMAGE_KEYS[sc.provider]] profile.save() The create_profile is fired when a user is created, it creates a new Profile. When a user add their social account, the after_social_account_added is fired, it updates the avatar of the Profile and sets it to the image provided by the Provider. The create_profile works fine, but the after_social_account_added does not run. Any help is highly appreciated. Thank you