Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible in django when user is login that time user active login browser name store in database?
Django in we already store session details in django_session, and last_login in the auth_user table but I want to store when user login in browser that time browser name store in the database. I already do: get browser name in frontend page from active browser with the use of javascript but actually, I want its store in the database. I expect the output is store active browser name in the database. This is my javascript code: <html> <body> <div id="demo"></div> <script> let browserName = ""; if(navigator.vendor.match(/google/i)) { browserName = 'Browser Name: Google Chrome'; } else if(navigator.vendor.match(/apple/i)) { browserName = 'Browser Name: Apple Safari'; } else if(navigator.userAgent.match(/firefox\//i)) { browserName = 'Browser Name: Mozila Firefox'; } else if(navigator.userAgent.match(/edge\//i)) { browserName = 'Browser Name: Microsoft Edge'; } else if(navigator.userAgent.match(/trident\//i)) { browserName = 'Browser Name: Internet Explorer'; } else { browserName = navigator.userAgent + "\n" + navigator.vendor; } </script> <h2><script type="text/javascript">document.write(browserName)</script></h2> </body> </html>``` -
what are META classes in python
What are metaclasses and what do we use them for? I was trying to get to know a detailed explanation of it. -
Transmit params to meta subclass of an abstract model
Django 2.2.3 Could you help me transmit a param to Meta inner class of an abstract model. My efforts: class GeneralUtmAbstract(models.Model): where = "" class Meta: def __init__(self): self.verbose_name_plural = "General UTM-labels: {}".format(GeneralUtmAbstract.where) self.verbose_name = verbose_name_plural class GeneralUtm(GeneralUtmAbstract): where = "Both" class BingUtm(GeneralUtmAbstract): where = "Bing" class GoogleUtm(GeneralUtmAbstract): where = "Google" My code doesn't raise any errors. But verbose names just don't show as planned. I get "general utm" instead of "General UTM-labels: both". Could you give me a kick here? -
Error Specifying a namespace in include() without providing an app_name
When I tried my project runserver, this error File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\apple\Desktop\web3start\tests\urls.py", line 8, in <module> url(r'^', include('web3auth.urls', namespace='web3auth')), File "C:\Users\apple\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. came out. conf.py if isinstance(urlconf_module, str): urlconf_module = import_module(urlconf_module) patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module) app_name = getattr(urlconf_module, 'app_name', app_name) if namespace and not app_name: raise ImproperlyConfigured( 'Specifying a namespace in include() without providing an app_name ' 'is not supported. Set the app_name attribute in the included ' 'module, or pass a 2-tuple containing the list of patterns and ' 'app_name instead.', urls.py # -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.conf.urls import url, include urlpatterns = [ url(r'^', include('web3auth.urls', namespace='web3auth')), ] What should I do?? I need a specific code directly to write on! -
"detail": "Method \"GET\" not allowed." Django Rest Framework
I know this question maybe a duplicate, but I have tried many solutions and could not understand any. I have followed this tutorial exactly and yet I get this error on the 'userlist' page. Everything else works just fine. Can somebody point out what the error is ? class UserList(APIView): """ Create a new user. It's called 'UserList' because normally we'd have a get method here too, for retrieving a list of all User objects. """ permission_classes = (permissions.AllowAny,) http_method_names = ['get', 'head'] def post (self, request, format=None): self.http_method_names.append("GET") serializer = UserSerializerWithToken(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django - "Post.user" must be a "User" instance
I have a memberships- app with a UserMembership-model that has a user field. memberships/models.py class UserMembership(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40) membership = models.ForeignKey( Membership, on_delete=models.SET_NULL, null=True) website = models.URLField(default='', blank=True) member = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username def post_save_usermembership_create(sender, instance, created, *args, **kwargs): user_membership, created = UserMembership.objects.get_or_create( user=instance) post_save.connect(post_save_usermembership_create, sender=settings.AUTH_USER_MODEL) When I try to use this user in another app, for example: user = request.user I get a unique constraint error or "usermembership cant be the sender of the message...". home/models.py from django.db import models from django.conf import settings class Post(models.Model): post = models.CharField(max_length=500) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) How do I get the user from the usermembership - model or the current logged-in user? home/views.py from django.contrib.auth import get_user_model user = get_user_model() class HomeView(TemplateView): template_name = 'home/home.html' def get(self,request): form = HomeForm() args = {'form': form} return render(request,self.template_name,args) def post(self,request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = user post.save() text = form.cleaned_data['post'] form = HomeForm() args = {'form':form,'text':text} return render(request, self.template_name, args) Thank you -
Got Stuck When trying to Deploy a Restaurants Sentimental Analysis Model using Django
I am trying to Deploy my sentimental analysis model using Django but getting the following error. views.py file from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth import authenticate import pandas as pd import matplotlib.pyplot as plt import pickle import re import nltk from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from string import punctuation from nltk.corpus import stopwords from sklearn.feature_extraction.text import CountVectorizer from sklearn.preprocessing import LabelEncoder # Create your views here. badfood=pickle.load(open('mymodel/pkl/BadFood.pickle','rb')) def index(request): return render(request,'mymodel/index.html') def remove_non_ascii_1(text): return ''.join(i for i in text if ord(i)<128) def clean_text(input_str): lemmatizer= WordNetLemmatizer() input_str=input_str.lower() remove_num=re.sub(r'\d+','',input_str) remove_punc=remove_num.translate(str.maketrans("","",punctuation)) remove_white=remove_punc.strip() stop_words=set(stopwords.words('english')) tokens=word_tokenize(remove_white) result=[i for i in tokens if not i in stop_words] lemmatized_words=[lemmatizer.lemmatize(word) for word in result] review=' '.join(lemmatized_words) return review def predict(request): # Grabbing data from user if request.method=="POST": review=request.POST.get('review','') city=request.POST.get('city','') input_data=[{'review':review,'city':city}] dataset=pd.DataFrame(input_data) dataset = dataset.replace(r'\r',' ', regex=True) dataset['review']=dataset['review'].apply(lambda x:remove_non_ascii_1(x)) dataset['review']=dataset['review'].apply(lambda x:clean_text(x)) # Bag of words vectorizer=CountVectorizer() features_data= pd.DataFrame(vectorizer.fit_transform(dataset.review).toarray()) features_data.columns=vectorizer.get_feature_names() features_data.insert(0,'city_x',dataset['city']) # Label Encoding the city column labelencoder=LabelEncoder() features_data['city_x']=labelencoder.fit_transform(features_data.city_x) features_data['city_x']=features_data['city_x'].astype('category') regressor=badfood.predict(features_data) return render(request,'mymodel/result.html',{'res':regressor}) ValueError at /predict/ Number of features of the model must match the input. Model n_features is 7397 and input n_features is 12 I have designed a user interface in which I am giving a text box field in which the … -
Django url error"NoReverseMatch at /2/ipd/"
I am having form which creates Ipd and Ipd model is created using patient model with one to many relationship, and I am already having one table with patient list in urls. I am trying to create the list of all Ipd that are created using form, I am trying to redirect the form page to Idp list after I submit for Ipd form but ending with this error "NoReverseMatch at /1/ipd/", One thing I want to clear is each Ipd is having unique id and Ipd is created from patient with one to many relationship which also have another unique id , the number which is in the error is patient id views.py @login_required def ipd(request, patient_id): object = get_object_or_404(Patient,pk=patient_id) if request.method == "POST": formtwo = IpdForm(request.POST) if formtwo.is_valid() : instance = formtwo.save(commit=False) instance.save() return HttpResponseRedirect(reverse('ipd_list', args=[patient_id])) else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'object':object, 'form2': formtwo}) @login_required def ipd_list(request): ipdlist = Ipd.objects.all() return render(request, 'Ipdlist.html', {'ipd': ipdlist }) urls.py re_path(r'^(?P<patient_id>\d+)/ipd/$', my_patient.ipd, name='ipd'), path(r'^ipdlist/', my_patient.ipd_list,name='ipdlist' ), Template <ul> <li><a href="{% url 'ipdlist' %}" ><span class="title">Indoor Patient Department</span></a></li> </ul> ######## in ipdform <form class="col s12" role="form" action="{% url 'ipd_list' 'patient_id' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} -
Customize Django Admin user password change form
I've customized my user model by using AbstractBaseUser. Everything works fine, but when I am in the Django Admin interface and us the form to change a user's password, in addition to the new password 1 and new password 2 fields, I also see their email in a text box: How can I remove their email address from appearing in my admin change password form? Is there a special Django form that I can subclass? -
How to append user data (the user who make request) into the tcp request that django make when querying postgresql database
I want my django authenticated user to make a data access request to the postgres db with a reverse proxy between the django application sever and postgres. So when my user makes a request, the request details are logged due to reverse proxy but I also want the details of the user to be logged. How can I append the user details(name/id of the user/requester) to the TCP request and reverse proxy server log? We have set up a django project, postgresql database for our application. We are planning to implement NGINX reverse proxy so as to block direct access to postgres server. But the reverse proxies only record the request details in the log while I wanted to record the details of the user who is requesting the data. -
How to make a compare system in django?
I'm making an E-commerce store, So far I have done almost everything, Just a few tweaks left. The problem in which I am stuck on is how to make a comparing system which can compare two same category products. If anyone knows how to write that into clean code. Please write your answer down. Examples I have item 1 and I want it to compare it with item two. I will select the item two. And then both will be added and will be evaluated and then the users will be recommended that this one is more good for you by grading it. Example : 78% Item1 and 22% item2, -
Django - user uploaded images not appearing in media/images folder
When I complete the profile of a test user, it adds the name of the uploaded file to the DB, and I am able to access the user's profile image file name with {{ user.profile.profile_pic }}, however the image does not appear in my_project/media/images. Thanks for any advice. Here are the relevant files, I can add more if needed: settings.py (last two lines) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' accounts/models.py from django.db import models from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, password=None, is_staff=False, is_superuser=False, is_active=True, is_confirmed=False): if not email: raise ValueError("Users must have an email address.") if not password: raise ValueError("Users mush have a password.") user_obj = self.model(email = self.normalize_email(email)) user_obj.set_password(password) #also to change password user_obj.staff = is_staff user_obj.admin = is_superuser user_obj.active = is_active user_obj.confirmed = is_confirmed user_obj.save(using=self._db) return user_obj def create_staffuser(self, email, password=None): user = self.create_user(email, password=password, is_staff=True) return user def create_superuser(self, email, password=None): user = self.create_user(email, password=password, is_staff=True, is_superuser=True) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255,unique=True) USERNAME_FIELD = 'email' active = models.BooleanField(default=False) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) confirmed = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS … -
celery cant find static files in django app during development
My django web app loads static files no problem in DEBUG mode with the magic of django.contrib.staticfiles. However, my celery service can't find the files! This makes sense, because Django docs say that django.contrib.staticfiles works automagically when runserver command is used, but celery doesn't use the runserver command, so how do I get celery to access those files in development? -
i am new to Django Framework and i am facing issues while storing Files
I am developing a form and i want to store all information to database, but i could save only the textbox data and couldn't save file field data. i am using a template designed fully in html, css and bootstrap and i am using django to connect the database. Html file code <div class="input-container"> <input class="input-field" type="text" id="u" placeholder="PortFolio URL " name="upurl" autocomplete="off" maxlength="300" > </div> <div class="row files" id="files1"> <span class="btn btn-default btn-file"> Upload you files <input type="file" id="fl" name="port" multiple /> </span> <br /> <ul class="fileList" id="fl"></ul> </div> This is my view.py def register(request): if request.method == "POST" and request.FILES['port']: fa = request.POST.get("usrnm1") la = request.POST.get("usrnm2") ph = request.POST.get("phone") gn= request.POST.get("radio") db = request.POST.get("dob") md = request.POST.get("emails") af= request.POST.get("aff") dp= request.POST.get("dept") fbk = request.POST.get("fb") twt =request.POST.get("tw") gtb= request.POST.get("gt") skr = request.POST.get("sks") lvl = request.POST.get("lvvv") exp = request.POST.get("expp") purl= request.POST.get("upurl") rmrk = request.POST.get("rmks") pfiles = request.FILES['port'] user1 = user(FIRST_NAME= fa, LAST_NAME = la, PHONE = ph,GENDER = gn, DATE_OF_BIRTH = db,MAIL_ID = md,AFILATION = af, DEPARTMENT = dp, FACEBOOK_ID = fbk, TWITTER_ID = twt, GITHUB_ID = gtb,SKILLS=skr,LEVEL =lvl,EXPERIENCE = exp,PORTFOLIO_FILES=pfiles, REMARKS =rmrk) user1.save() send_mail('System cretaed mail', 'Thank you for registering hackathon event, we will get back to you shortly','yourhackathon@mail.com',[md], … -
How to decode the wrong encoded "b'\\xc3\\xb1'" from Django CharField
I need to decode the values of Django CharField. The values were encoded with 'text'.encode('utf-8') before store them into the database. In the Django views, I get "b'text'" str objects from models and I can decode the text correctly. -
How to prevent user to access website by IP address
I have a django website, which can be accessed by, such as www.mysite.com. Site ip is: 33.33.33.33. If type 33.33.33.33, website also work. Is it possible to make: 33.33.33.33 not working? I only want: www.mysite.com to work. The reason is that same IP is hosting few website with different domain names. 33.33.33.33 works for only 1, which does not make any sense. -
Complete sample project for plotting graphs in bokeh
i am a fresher in django just received a project to create graphs with bokeh can . Can anyone please guide to how to complete it . i have a basic idea for django also gone through https://www.youtube.com/watch?v=YlOVR_1q4Ak . but want to know the simplest way to start with -
How to fix 'You must 'source' this script: PS> . ./Scripts/activate' error in PowerShell when activating virtual environment
Im making a Django project on my computer and Im running into an issue with powershell not allowing me to activate the virtual enviorment. Ive tried changing the 'activate' to activate.ps1' and 'activate.bat' neither of which worked. No matter where I am in the directories I get this issue. I also tried it from the cmd which did work but I'd prefer to work in the powershell. This is the error code in the activate file: ''' if (@($null,"Internal") -notcontains $myinvocation.commandorigin) { Write-Host -Foreground red "You must 'source' this script: PS> .$($myinvocation.invocationname)" exit 33 } ''' The input was: PS D:\library\Dev\python\DjangoVenv> ./Scripts/activate The output was: You must 'source' this script: PS> . ./Scripts/activate -
Is an extension in chrome trying to hack my site?
I have these suspicious logs showing up in the django console I have tried to disable https everywhere and a handful of extensions, this seems to be a problem only on chrome. [31/Jul/2019 19:37:11] "GET /?_=1562608ea67ac HTTP/1.1" 302 0 Not Found: /robots.txt [31/Jul/2019 19:37:11] "GET /robots.txt?_=1562608ea67ac HTTP/1.1" 404 2872 Not Found: /App.php [31/Jul/2019 19:37:12] "POST /App.php?_=1562608ea67ac HTTP/1.1" 404 2864 Not Found: /webdav/ [31/Jul/2019 19:37:13] "GET /webdav/ HTTP/1.1" 404 2850 Not Found: /java.php [31/Jul/2019 19:37:16] "GET /java.php HTTP/1.1" 404 2850 Not Found: /test.php [31/Jul/2019 19:37:20] "GET /test.php HTTP/1.1" 404 2850 Not Found: /db_cts.php [31/Jul/2019 19:37:21] "GET /db_cts.php HTTP/1.1" 404 2856 Not Found: /db_pma.php [31/Jul/2019 19:37:21] "GET /db_pma.php HTTP/1.1" 404 2856 Not Found: /logon.php [31/Jul/2019 19:37:22] "GET /logon.php HTTP/1.1" 404 2853 Not Found: /help-e.php [31/Jul/2019 19:37:22] "GET /help-e.php HTTP/1.1" 404 2856 Not Found: /license.php [31/Jul/2019 19:37:23] "GET /license.php HTTP/1.1" 404 2859 Not Found: /log.php [31/Jul/2019 19:37:24] "GET /log.php HTTP/1.1" 404 2847 Not Found: /hell.php [31/Jul/2019 19:37:25] "GET /hell.php HTTP/1.1" 404 2850 Not Found: /pmd_online.php [31/Jul/2019 19:37:25] "GET /pmd_online.php HTTP/1.1" 404 2868 Not Found: /x.php [31/Jul/2019 19:37:26] "GET /x.php HTTP/1.1" 404 2841 Not Found: /shell.php [31/Jul/2019 19:37:28] "GET /shell.php HTTP/1.1" 404 2853 Not Found: /htdocs.php [31/Jul/2019 19:37:29] "GET /htdocs.php HTTP/1.1" 404 2856 Not … -
Django admin get value from field and add to custom label in forms.Model django-colorful
I'm using the django-colorful package to add a color picker for my admin site but I want to put the hex value of the color that the user pick in a custom label but I can't make It work. How can you get the value for a widget and put it in a label?. Model class Colors(models.Model): color = RGBColorField(null=True,blank=True) Admin class ColorsAdminForm(forms.ModelForm): color_label = forms.CharField() def __init__(self, *args, **kwargs): super(ColorsAdminForm, self).__init__(*args, **kwargs) self.fields['color'].label = 'Actual Color' self.fields['color'].disabled = True self.fields['color_label'].initial = self.fields['color'].value #Can't make this work -
How to validate multiple fields with Django Admin Forms
I have two Django 2.2 models: class Collection(Model): collection_id = models.AutoField(primary_key=True) name = models.CharField('title', max_length=200) description = models.TextField('description') document = models.ManyToManyField(Document, through='CollectionDocument', related_name='collections') page_rows = models.IntegerField(default=1) page_columns = models.IntegerField(default=1) created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name="date created") updated = models.DateTimeField(auto_now=True, editable=False, verbose_name="last update") class CollectionDocument(Model): collection_id = models.ForeignKey(Collection, on_delete=models.CASCADE, ) document = models.ForeignKey(Document, on_delete=models.CASCADE, ) page = models.IntegerField(default=1) # the page for this document page_row = models.IntegerField(default=1,) page_column = models.IntegerField(default=1,) and I am using the Django Admin to add data to the models. The CollectionDocument is an inline in the CollectionAdmin page as shown below. The problem I am trying to solve is how to validate the data from this screen. I have validators that work to make sure that the page_row and page_col are not larger than the number of rows and columns defined in the collection. The one validation that is troubling me is how to validate the three values - page, page_row, and page_column together? The validation logic for a collection is that none of the page_rows or page_columns are skipped for a given page and collection, and that there are no duplicates of page_row or page_col for a given collection and page. For example,the Collection in the screenshot … -
Django render range() between 2 number values as float instead of int in template
I'm trying to populate select option in HTML with range between 2019 and 2021 in my views.py: return render(request, 'pages/list_working_sessions.html', { 'working_session_list': working_session_list, 'state': 'list-working-sessions', "months": range(1, 13), "years": range(2019, 2021) }) in my list_working_sessions.html: <td style="border-top:none"> <select name="year" class="form-control" id="year" required> {% for i in years %} {% if i == request.GET.year|add:"0" %} <option value="{{i}}" selected="selected">{{i}}</option> {% else %} <option value="{{i}}">{{i}}</option> {% endif %} {% endfor %} </select> </td> the option only show 2.019 and 2.020 instead of 2019 and 2020. but range(1,13) show properly int value Why is this happening and how to fix this ? Thank you -
Django redirecting to incorrect URL
I am working on the login/logout functionality of a basic Django website. (CS50's Pinocchio's Pizza). The logout path is being injected into the URL & I am unsure as to why. My navbar links to the home page, yet when I click on it it redirects me to the logout page. Any other link I click, that link's path is added to the URL but attached to the logout path. For example, clicking on the login button of my site, whose path is login_default, the url becomes: http://127.0.0.1:8000/logoutlogin_default Trying to click the link in the navbar that should link to the index page gets me: http://127.0.0.1:8000/logout The folder "orders" is an app which "pizza" is made aware of. All html pages are inside orders/templates/orders. This is orders/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name = "index"), path("register_default", views.register_default, name = "register_default"), path("register_setup", views.register_setup, name = "register"), path("login_default", views.login_default, name = "login_default"), path("login_setup", views.login_setup, name = "login"), path("logout", views.logout_view, name="logout"), ] In pizza/urls.py, the Orders app's URLs have been made known: from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("orders.urls")), path("register_default", include("orders.urls")), path("register_setup", include("orders.urls")), path("login_default", include("orders.urls")), path("login_setup", include("orders.urls")), path("logout", … -
How to add a comment liking system in Django
I'm attempting to allow a user to like comments of a particular post. However when I attempt to solve this, the expected result doesn't occur. urls.py: path('likecomment/<int:pk>/', post_views.likecomment, name='likecomment'), views.py: def likecomment(request, pk): if request.method == 'POST': comment = get_object_or_404(Comment, pk=pk) comment.likes += 1 comment.save() return redirect('home') comments.html: {% for com in comments %} <br> <br> <br> <b>{{ com.user.username }}</b> &nbsp {{ com.body }} <br> <p class="text-muted">{{ com.pub_date_pretty }} &nbsp &nbsp &nbsp &nbsp &nbsp {{ com.likes }} Likes</p> <a href="javascript: {document.getElementById('likecomment').submit()}"> Like </a> <form id="likecomment" method="post" action="{% url 'likecomment' com.id %}"> {% csrf_token%} <input type="hidden"> </form> <br> {% endfor %} The like occurs sometimes, however not for the right comment. The functionality isn't working correctly. -
Django IntegrityError on profile creation
Why am I getting the Integrity Error despite the fact that I'm checking that the username is unique here: (I also tried try/expect IntegretyError instead of e.count()) # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from slugify import slugify class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") username = models.CharField(max_length=30, blank=True, unique=True) #should be true on signup name = models.CharField(max_length=30, blank=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) email = models.EmailField() #should be true on signup avatar_url = models.URLField(default="https://image.flaticon.com/icons/png/512/64/64572.png") def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): # if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save(commit=False) from allauth.account.signals import user_logged_in, password_set, user_signed_up from django.db.models.signals import post_save from django.dispatch import receiver, Signal @receiver(user_logged_in) def populate_profile(sociallogin, user, **kwargs): # picture_url = "" if sociallogin.account.provider == 'github': user_data = user.socialaccount_set.filter(provider='github')[0].extra_data print(user_data) username = user_data['login'] avatar_url = user_data['avatar_url'] email = user_data['email'] name = user_data['name'] bio = user_data['bio'] location = user_data['location'] if sociallogin.account.provider == 'twitter': user_data = user.socialaccount_set.filter(provider='twitter')[0].extra_data print(user_data) username = user_data['screen_name'] avatar_url = user_data['profile_image_url'].replace("_normal", "") email = user_data['email'] name = user_data['name'] bio = user_data['description'] location = user_data['location'] e = Profile.objects.filter(username=username) if e.count() …