Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django calculate value within Model save based on new field values
I've got a profile score of an object which is calculated within the save() because the fields to be used are based on how scoring is defined in another table. So within my model I have: def save(self, *args, **kwargs): self.profile_score = self.calc_profile_score() super().save() This uses the following: def scoring_recordset (self): query = models.Q() if self.service_care_home and self.care_residential: query = models.Q(query | models.Q(care_home_residential=True)) if self.service_care_home and self.care_nursing: query = models.Q(query | models.Q(care_home_nursing=True)) if self.service_care_home and self.care_dementia: query = models.Q(query | models.Q(care_home_dementia=True)) if self.service_care_home and self.care_respite: query = models.Q(query | models.Q(care_home_respite=True)) if self.service_home_care and self.regulated_personal_care: query = models.Q(query | models.Q(home_care_personal=True)) if self.service_home_care and self.care_nursing: query = models.Q(query | models.Q(home_care_nursing=True)) if self.service_home_care and self.care_dementia: query = models.Q(query | models.Q(home_care_dementia=True)) if self.service_live_in_care and self.regulated_personal_care: query = models.Q(query | models.Q(live_in_care_personal=True)) if self.service_live_in_care and self.care_nursing: query = models.Q(query | models.Q(live_in_care_nursing=True)) if self.service_live_in_care and self.care_dementia: query = models.Q(query | models.Q(live_in_care_dementia=True)) return Score.objects.filter(query) def field_score (self, score): if score.is_premium and not self.is_premium: return 0 if score.scoring_algorithm == 'boolean': try: if self._meta.get_field(score.field_name).value_from_object(self): return score.max_points except: #not a field so must be property if isinstance(getattr(Organisation, score.field_name), property): tmp = getattr(Organisation, score.field_name) if tmp.fget(self): return score.max_points elif score.scoring_algorithm == 'per item': tmp = 0 try: for item in self._meta.get_field(score.field_name).value_from_object(self): tmp … -
How to define ImageField in abstract model?
I have class for upload_to: class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename): ext = filename.split('.')[-1] if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: filename = '{}.{}'.format(uuid4().hex, ext) return os.path.join(self.path, filename) I have created abstract class for preview: class PreviewAbstract(models.Model): upload_path = '' preview = models.ImageField( verbose_name='Превью', upload_to=PathAndRename(upload_path) ) class Meta: abstract = True I want to be able to inherite this model like: class ChildClass(PreviewAbstract): upload_path = 'folder_name' , but in saves images in "root" folder How can i do it? Thank you for your answers. -
How can we edit content inside textarea feild?
Here i am using django 3.0.3/python and jquery for front-end,well my question is that i simple want to add some styling inside the textarea , Most of people are familiar with medium , I simple want to convert my blog form to the form like medium , right know my blog form looks like: and I simple want to change it like : I also want all these following tools during writing a blog: Well i am not saying that give all the code in the answers, I just want to know the steps which i need to make and the things which i will be going to use to make. I will extremely thankful to all of you who will answer this question. -
Automatic form validation based on user account data
Hi I have a question if I am able to write validations in such a way that the name is taken when you click submit and you only have the options to select the tournament and group this is my models.py file class Debatants(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) email = models.EmailField(max_length=256, null=True) class TournamentUsers(models.Model): user_first_name = models.CharField(max_length=256) user_last_name = models.CharField(max_length=256) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) user_group = models.ForeignKey(TournamentGroup, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user_last_name + ' ' + self.user_first_name and this is my views.py file def groups(request, pk): tournament_groups = get_object_or_404(TournamentGroup, pk=pk) users = TournamentUsers.objects.filter(user_group=tournament_groups) judges = TournamentJudges.objects.filter(user_group=tournament_groups) tournament = Tournament.objects.get(tournament_name=tournament_groups.tournament_name) form = TournamentUsersForm( initial={'user_tournament': tournament_groups.tournament_name, 'user_group': tournament_groups}) form2 = TournamentJudgesForm(initial={'user_tournament': tournament_groups.tournament_name, 'user_group': tournament_groups}) if request.method == "POST": form = TournamentUsersForm(request.POST) if form.is_valid(): form.save() form = TournamentUsersForm() if request.method == "POST": form2 = TournamentJudgesForm(request.POST) if form2.is_valid(): form2.save() form2 = TournamentJudgesForm() context = {'tournament_groups': tournament_groups, 'users': users, 'form': form, 'judges': judges, 'form2': form2, "tournament": tournament} return render(request, 'ksm_app2/groups.html', context) -
django Admin - Filter foreign key selected depending on other choice in edit form (ithout jQuery)
I am working on a project which is administered by a super admin who puts in data for different companies. Lets say, I have these models: class Company(models.Model): name = models.CharField(max_length=100) class ContactPerson(models.Model): name = models.CharField(max_length=100) company = models.ForeignKey(Company) class Item(models.Model): company = models.ForeignKey(Company) contact_person = models.ForeignKey(ContactPerson) I need to ensure that I (in django admin) in the edit mode I only see contact persons which belong to the selected company. Being not in the year 2005 anymore I want to avoid writing loads of super ugly jQuery code. I guess I could overwrite the admin form for Item. But still I had to make the contact_person optional, so when I create a new Item, the list of contact persons need to be empty. Then I'd select a company, save it and go back to edit. Now the contact_person list would be filled and I could add somebody. But if I now change the comany, I'd have to remove all selected contact persons. Sure, I could to this in the form... but it looks SO hacky and not like a nice django solution. Anybody got some fancy ideas? Thanks in advance! Ronny -
how can I use foreign key to import users login from google by Django-allauth
I am using 2 login methods, one is Django inbuilt authentication and another by using "allauth" of google. I want to make a separate model with only the entries from google logged-in people by using a "foreign key" and few more attributes. In Django admin page there is a table "Social accounts", which has only google logged in users, so how can I include that model? What all includes I have to use to get model like this and what should I write instead of something: class GoogleSignIn(models.Model): id= models.AutoField(primary_key=True) googleacc = models.ForeignKey(*something*, on_delete=models.CASCADE, null=True) productsTaken= models.CharField(max_length=50) ph = models.CharField(max_length=12) -
Error in django when I add two new fields to a class model
I have a class called Difference in my script "myProject.models.difference.py" that is: class Difference(models.Model): comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE) summary = models.CharField('summary',max_length=900000) And in my script "myProject.admin.scenario.py" I have the corresponding admin class: class DifferenceAdmin(admin.ModelAdmin): list_display = ("comparator","summary",) But I need to add two fields more to my Class Difference: class Difference(models.Model): comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE) summary = models.CharField('summary',max_length=900000) diff_class = models.CharField('diff_class',max_length=1000) diff_field = models.CharField('diff_field',max_length=500) After that I read the next error: "no such column: myproject_difference.diff_class". But if I comment the new fields diff_class, diff_field of this way: class Difference(models.Model): comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE) summary = models.CharField('summary',max_length=900000) #diff_class = models.CharField('diff_class',max_length=1000) #diff_field = models.CharField('diff_field',max_length=500) Then the error disappears. ¿What must I do in order to add the new fields? -
django-haystack returns "inexact" results when keyword contains multiple words
I'm using django-haystack with Solr as backend. I ahve a model with Author, Title, ISBN as fields. If I search for ex for Harry potter I get results for books that's the author name is Harris or contains Harris in their titles but no Harry potter. but when I putt the keywords between "" ("Harry Potter" for ex) I get the right results! Any idea how I can fix this? Thanks. -
Django query to get sum of previous values
I have the following table of logs that stores operations. An override operation means an absolute value stored, while add and sub operations are variance values. The override operations are like checkpoints. Id operation quantity --------------------------------------------------------- 1 ADD 10.00 2 ADD 20.00 3 OVERRIDE 15.00 4 SUB -5.00 5 SUB -10.00 My goal is to get the following results with one query Id operation quantity calculated_total_quantity --------------------------------------------------------- 1 ADD 10.00 10.00 2 ADD 20.00 30.00 3 OVERRIDE 15.00 15.00 4 SUB -5.00 10.00 5 SUB -10.00 0.00 I tried the following query Logs.objects.all().annotate( calculated_total_quantity=Case( When(operation="OVERRIDE", then=F('quantity')), default=Window( expression=Sum(F('quantity')), order_by=F('id').asc() ) ) ) With this query I am getting wrong results: Id operation quantity calculated_total_quantity --------------------------------------------------------- 1 ADD 10.00 10.00 2 ADD 20.00 30.00 3 OVERRIDE 15.00 15.00 4 SUB -5.00 40.00 5 SUB -10.00 30.00 I know that the error is because of the Sum expression, so my questions is if there is any way to reset the Sum expression to start again when the log operations is OVERRIDE. If anyone can help me with this I will be more than grateful. -
how to redirect to a page from botton?
Hello i am newbie using DJANGO , i am trying that when i click on 'Continue' it redirects me to the template carrito.html but it aint working :/ //i've tried this <a href="/base/carrito">Continue</a> // and i've tried this <button type="button"> <a href="{% url '/carrito/' %}">Comprar!</a> </button> i get this example the routes are plantilla/base/carrito.html -
AttributeError: 'NoneType' object has no attribute 'get' when verifying access_token from FE in Django/DRF API
Been trying to fix this for a few days now. Basically, I'm trying to pass an access_token from my Django FE to the Django/DRF BE so it can be verified there for subsequent communication between the two microservices. For reasons that are not clear to me, I am getting the following error from using python-social-auth and social-auth-app-django. Error: [api] Internal Server Error: /api/social/azuread-tenant-oauth2/ [api] Traceback (most recent call last): [api] File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner [api] response = get_response(request) [api] File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response [api] response = wrapped_callback(request, *callback_args, **callback_kwargs) [api] File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view [api] return view_func(*args, **kwargs) [api] File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view [api] return self.dispatch(request, *args, **kwargs) [api] File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch [api] response = self.handle_exception(exc) [api] File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception [api] self.raise_uncaught_exception(exc) [api] File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception [api] raise exc [api] File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch [api] response = handler(request, *args, **kwargs) [api] File "/usr/local/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler [api] return func(*args, **kwargs) [api] File "/usr/local/lib/python3.8/site-packages/social_django/utils.py", line 49, in wrapper [api] return func(request, backend, *args, **kwargs) [api] File "/app/users/views.py", line 85, in exchange_token [api] user = request.backend.do_auth( [api] File "/usr/local/lib/python3.8/site-packages/social_core/utils.py", line 251, in … -
Application error - When I uploading my Django app on Heroku
Uploading my Django app on Heroku An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail heroku logs: rn/workers/base.py", line 129, in init_process 2020-11-05T15:09:51.536472+00:00 app[web.1]: self.load_wsgi() 2020-11-05T15:09:51.536472+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2020-11-05T15:09:51.536473+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-11-05T15:09:51.536473+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-11-05T15:09:51.536474+00:00 app[web.1]: self.callable = self.load() 2020-11-05T15:09:51.536474+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2020-11-05T15:09:51.536474+00:00 app[web.1]: return self.load_wsgiapp() 2020-11-05T15:09:51.536475+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2020-11-05T15:09:51.536475+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-11-05T15:09:51.536476+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 350, in import_app 2020-11-05T15:09:51.536476+00:00 app[web.1]: __import__(module) 2020-11-05T15:09:51.536476+00:00 app[web.1]: File "/app/newspaper_project/wsgi.py", line 12, in <module> 2020-11-05T15:09:51.536477+00:00 app[web.1]: from django.core.wsgi import get_wsgi_application -
How to assign users in groups from Django views?
I have CRUD operations for users, which can be done only from the admin role. I have 6 different roles, that I made by creating groups and assign users to specific group from the admin panel. My question is is there some way to include these group fields with drop down menu when admin create new user, so he can choose what group to assign the new user but not from the admin panel? any help would be appreciated :) model.py class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', 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) class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email username = models.CharField(max_length=30, blank=True, default='') is_superuser = models.BooleanField(default=True) is_admin = models.BooleanField(default=True) is_employee = models.BooleanField(default=True) is_headofdepartment = models.BooleanField(default=True) is_reception = models.BooleanField(default=True) is_patient = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) forms.py class UserForm(ModelForm): class Meta: … -
Regrouping in Django Template With Grouping in views
I have a model with different forginekey wish I could like to group it by student. I was successfully done that but in my template, I want to nested the result or regroup it by subject according to students. model.py class Result(models.Model): examtype = models.ForeignKey(ExamType, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(SubjectAppointment, on_delete=models.CASCADE) test = models.FloatField() exam = models.FloatField() total = models.FloatField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): self.total = self.test + self.exam super().save(*args, **kwargs) def __str__(self): return self.student.matricnumber def get_result_total(self): return int(float(f'{self.test + self.exam}')) views.py def ReportView(request): template_name = 'teacher/report.html' score = Result.objects.values('student', 'exam', 'test', 'subject__subject__name').annotate(student_totalscore=Sum('total')).annotate(attending=Count('subject')) print(score) context = { 'score': score, } return render(request, template_name, context) report.html {% for s in score %} {% regroup score by s.student as student_list %} {% for a in student_list %} <!-- {% for b in a.list %} --> <tr> <td>{{ b.subject__subject__name }}</td> <td>{{ b.test }}</td> <td>{{ b.exam }}</td> <td></td> <td></td> <td></td> <td></td> </tr> <!-- {% endfor %} --> {% endfor %} {% endfor %} -
ordery_by is not working for boolean field in Django
i am running the query, but the ordery_by is not working for boolean field value. Any help, would be much appreciated. thank you. queryset = ShopOffer.objects.filter(added_by__user_id=user).order_by('-is_active') -
What is the right way to use service methods in Django?
As an example, let's say I am building an Rest API using Django Rest Framework. Now as part of the application, a few methods are common across all views. My approach is that in the root directory, I have created a services.py file. Inside that module, is a class (CommonUtils) containing all the common utility methods. In that same services.py module I have instantiated an object of CommonUtils. Now across the application, in the different views.py files I am importing the object from the module and calling the methods on that object. So, essentially I am using a singleton object for the common utility methods. I feel like this is not a good design approach. So, I want to get an explanation for why this approach is not a good idea and What would the best practice or best approach to achieve the same thing, i.e use a set of common utility methods across all views.py files. Thanks in advance. -
Django DLL load failed after trying to setup django project on pycharm
I just made a django project using pycharm professional in order to try and make an API that way. I try to run the django server using python manage.py runserver command and I get the following error:[[the errors][1]] 2 -
How to add formating options in django forms?
I just wanted to know how I can add formating options to a website powered by django for example stack overflow has this default editing option: example Is there any plugin or am I supposed to do this manusally if I wanted to add this functionality to my website, how would I go about doing it? -
Angular 9, Leaflet, Django: Add multiple HTTP get request layers to leaflet map
I have about 20 or so layers I need to add to a leaflet map from a django backend. The only way I've successfully implemented this, while also add those layers to layerControl is by using the following: map.component.ts layers: L.Layer[]; layersControl: any; constructor(private http: HttpClient) {} getFeatureOne = this.http.get<any>('http://localhost:8000/api/layerOne'); getFeatureTwo = this.http.get<any>('http://localhost:8000/api/layerTwo'); etc... ngOnInit() { this.getFeatureOne.subscribe( featureOne => { this.getFeatureTwo.subscribe( featureTwo => { etc.. const layerOne = L.geoJSON(featureOne); const layertwo = L.geoJSON(featureTwo); this.layers = [layerOne, layerTwo]; this.layersControl = { baseLayers: { 'Open Streets': this.openStreets }, overlays: { 'Layer One': layerOne, 'Layer Two': layerTwo } }; } ); } ); } map.component.html <div id="map" leaflet [leafletLayers]="layers" [leafletLayersControl]="layersControl" [leafletCenter]="center" [leafletZoom]="zoom" [leafletFitBounds]="fitBounds3"> </div> Surely there's something I'm missing, but I haven't been able to find it here or anywhere else. Any help would be greatly appreciated. -
How to implement Python in Django .html templates
I'm trying to build a web page using Django. I'm writing a simple stopwatch script in Python that I want to then have show up on my home.html file. So two questions : How can I put python code into my HTML file? Where can I create .py files in the Django framework so it can be located? Thanks in advance -
Django error 'URLs with hostname components are not permitted'
I have deployed a django application which invokes a python file to send captured data on django form to a third party independent server. The problem is that when the python file is invoked from django form, it leads to this error as seen on the browser - file: URLs with hostname components are not permitted Request Method: POST Request URL: http://127.0.0.1:8000/phone_associate_form/ Django Version: 3.1.3 Exception Type: ValueError Exception Value: file: URLs with hostname components are not permitted Exception Location: E:\INVOKEDID\lib\site-packages\requests_file.py, line 34, in send Here is the output for local variables as seen kwargs {'cert': None, 'proxies': OrderedDict(), 'stream': False, 'timeout': 20, 'verify': False} request <PreparedRequest [GET]> self <requests_file.FileAdapter object at 0x000001DBB1302B88> url_parts ParseResult(scheme='file', netloc='E:', path='/INVOKEDID/NumberRepo/MASTERHANDLER/axlsqltoolkit/schema/current/AXLAPI.wsdl', params='', query='', fragment='') Here is pip freeze output from django - appdirs==1.4.4 asgiref==3.3.0 attrs==20.3.0 beautifulsoup4==4.9.3 cached-property==1.5.2 certifi==2020.6.20 chardet==3.0.4 defusedxml==0.6.0 diff-match-patch==20200713 Django==3.1.3 django-crispy-forms==1.9.2 django-easy-audit==1.3.0 django-import-export==2.4.0 django-shibboleth-remoteuser==0.12 et-xmlfile==1.0.1 idna==2.10 isodate==0.6.0 jdcal==1.4.1 lxml==4.6.1 MarkupPy==1.14 numpy==1.19.4 odfpy==1.4.1 openpyxl==3.0.5 pandas==1.1.4 psycopg2==2.8.6 python-dateutil==2.8.1 pytz==2020.4 PyYAML==5.3.1 requests==2.24.0 requests-file==1.5.1 requests-toolbelt==0.9.1 six==1.15.0 soupsieve==2.0.1 sqlparse==0.4.1 tablib==2.0.0 urllib3==1.25.11 xlrd==1.2.0 xlwt==1.3.0 zeep==4.0.0 -
Is there a way to add middleware for a particular url route in django?
Say I have some URLs: urlpatterns = [ path('', Home.as_view()), path('games/', include('games.urls', namespace='games')), ] Is there a way that I can get a given middleware to run only when accessing urls under games? E.g. to check auth or to pre-fetch some data that will be useful to all views in the games app. -
Django model designing problem when creating a follower / following relationship
I'm trying to create a followig system for my application, and when I thought it worked, I realised that when account a started following account b, account b also started following account a My models: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): followers = models.ManyToManyField('self', blank=True, related_name='followers') following = models.ManyToManyField('self', blank=True, related_name='following') class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='p_author') body = models.TextField(max_length=500) time = models.TextField() #Added when creating object with the API likes = models.IntegerField(default=0) def serialize(self): return { 'id': self.id, 'author': self.author.username, 'body': self.body, 'time': self.time, 'likes': self.likes } class Comment(models.Model): post_commented = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='c_post') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='c_author') body = models.TextField(max_length=500) time = models.TextField() #Added when creating object with the API likes = models.IntegerField(default=0) The view that handles the follow action (called via a JS fetch call): ef follow(request, profile_name): user_object = User.objects.get(username=profile_name) if request.method == 'PUT': print(request.user) data = json.loads(request.body) if data.get('follow') == True: followers_set = user_object.followers followers_set.add(request.user) user_object.save() return JsonResponse({'status': 'success'}, status=204) I'm supposing that I will need to restructure my whole database and project to fix this bug, how would you suggest I do it? -
Course Details are not showing
I'm trying to get course details from enrolled course but it returns only the course ID. I tried with nested serializers but it went wrong. How can I get course details with the following setup models class Course(models.Model): course_name = models.CharField(max_length=300,default=None) author = models.ForeignKey(TeacherProfile,on_delete=models.CASCADE,null=True,default=None) course_description = models.TextField(null=True) course_cover = models.ImageField(null=True,blank=True,upload_to='course_covers/') def __str__(self): return self.course_name class Enrollment(models.Model): enroll_key = models.CharField(max_length=100,default="Text here",null=True) course = models.ForeignKey(Course,on_delete=models.CASCADE,null=True,related_name='enrollment') student = models.ForeignKey(StudentProfile,on_delete=models.CASCADE,null=True) def __str__(self): return self.course.course_name serializer class MycoursesSerializer(serializers.ModelSerializer): class Meta: model = Enrollment fields = "__all__" View @api_view(['GET']) @permission_classes([IsAuthenticated]) def MyCourses(request): student = StudentProfile.objects.get(user=request.user) courses_enrolled = Enrollment.objects.filter(student=student) serializer = MycoursesSerializer(courses_enrolled,many=True) return Response(serializer.data) response { "id": 1, "enroll_key": "Text here", "course": 1, "student": 1 } -
Test django allauth socialAccount creation
When a user signs up using a socialAccount (google in my case) I have a user_signed_up signal that tests if the user signed up using a socialAccount, and if they did then it associates data from the socialAccount instance with the User model instance. How would I create a user using the socialAccount method as part of a test, using pytest? the signal definition is: import logging from allauth.account.signals import user_signed_up from django.contrib.auth import get_user_model from django.dispatch import receiver User = get_user_model() logger = logging.getLogger("email_app.apps.users") @receiver(user_signed_up, sender=User, dispatch_uid="apps.users.signals") def associate_social_data_with_user_model(user, **kwargs): if user.socialaccount_set.filter(provider='google').count() < 1: logger.info(f"social account single sign on not used. user signed up the old fashioned way. {user = }") else: extra_data = user.socialaccount_set.filter(provider='google')[0].extra_data user.name = extra_data['given_name'] user.save()