Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django SESSION_COOKIE_AGE dynamically
In my django application I want to make this session cookie age dynamic.For example the default session is for two weeks in django .If i wanted to change into 1 weeks i can change by changing the setting in django but for this i need to go in the project settings.py file. Is there any solutions so that later after some time if i needed to change my SESSION_COOKIE_AGE i can change this with the admin panel butnot going in the projects settings.py file settings.py SESSION_COOKIE_AGE = 1209600 # I want to make this dynamic ANY HELP WOULD BE GREAT -
Django website for Subscriptions with paypal integration
Anyone help me on django with website for Subscription of two plans and integrate paypal payment gateway Thanks In advance -
(Django) Reverse dynamic urls with multiple arguments using Django Views
I am trying to pass two arguments to make a dynamic URL for each post of a blog app I'm working on. I get it to work if I pass the id, but don't know what's the syntax when using +1 arguments (nor if I'm doing things right). I want to make urls be 'post/<int:pk>/<slug:slug>/' but can only make it work with the id: 'post/<int:pk>/ Here's how I have it now: URLS.PY urlpatterns = [ ... path('post/<int:pk>/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete'), ... ] VIEWS.PY class PostDetailView(DetailView): model = Post I am calling this in the template: <ul class="secondary-menu menu-list"> <li class="menu-item"><a href="{% url 'post-update' object.slug %}">Edit Post</a></li> <li class="red-button"><a href="{% url 'post-delete' object.slug %}">Delete</a></li> </ul> And have this function to retrieve the path to any specific instance in MODELS.py def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk, 'slug':slug}) I get the following error during template rendering Reverse for 'post-detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$'] -
unable to apply search on multiple fields Django
def search(request): if request.method == 'POST': srch = request.POST['title'] if srch: match = Post.objects.filter(title__icontains=srch,email__icontains=srch) # match = Post.objects.annotate(search=SearchVector('title', 'email'),).filter(search=srch) if match: return render(request,'post/index.html',{'sr':match}) else: messages.add_message(request,messages.INFO,' No result found ') else: return redirect('post') return render(request,"post/index.html") -
Django regex url parsing to calling wrong view
I have a Django 2.2 project (using the rest framework) where I need to call a view function with a url of the following format: /class/students?date=07092019 and I've set up the following url route to handle this url:re_path(r'^class/students%3Fdate%3D(?P<date>\w+)/$',StudentsInClassView.as_view() ,name='student'). The corresponding view function has the following definition: class StudentsInClassView(APIView): def get(self, request, date,format=None): For some reason, whenever I go to url, it gets converted to /class/students/?date=07092019 and a different view, with the url path('nba/students/',StudentsView.as_view() ,name='students'), gets called instead. If I remove the "?date=" from the url and just include the actual date, the StudentsInClassView is called as expected. I've escaped both the question mark and the equal sign but doing so doesn't seem to make a difference. How can I get the "?date=" slug to remain in the url as it is used to call the StudentsInClassView? Is there a different regex that could be used to match the whole url? -
How can I display a list in tabs or pagination in django?
I am currently working on a django project where in from views.py, I am calling a function to render my HTML page and I am passing an argument which is list of lists. I want to display these lists in tabs or pagination where only first list is active and others are in pagination, how can I do that? And the list of lists I am passing may have different number of items in it. -
a superior user can change other user's password
as an assignment, i need to create this simple web app using django as the admin, I'll create a "low level" username + password. the salesmanager will then give this username and password to his salespersons. this is a "read-only" username. that means, the salespersons can only read/see the data available on this company webapp, simultaneously using just this one username. this username can't change the password. if one of the salespersons resigns, the password will need to be changed. because the salesperson turnover is rather high, I want the salesmanager to be able to change the password for this username, so i don't have to do it myself everytime. the salesmanager himself will use a different username + password as he has more permissions. how do i use django's change password to work in this situation? thank you -
Serializer Validate() method not invoking in serializer DRF
In DRF the serializer validate() method is not calling by default. i am using the serializer like this: class SampleListView(ListAPIView): queryset = Sample.objects.all() serializer_class = SampleSerializer def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) return Response(sorted_result) class SampleSerializer(serializers.ModelSerializer): custom_data = serializers.SerializerMethodField() class Meta: model = SampleModel fields = ('field_1', 'field_2') def validate(self, data): return data Execution not enter into the validate() method in serializer. Anyone have an idea about this? -
Password reset email not sending with the addition of a custom template
Trying to get my custom template to display with my password reset email, but it's not working. The email sends, but the custom email template does not render. path('accounts/password-reset/', auth_views.PasswordResetView.as_view( template_name='password_reset.html', html_email_template_name='password_reset_email_template.html', subject_template_name='password_reset_subject.txt' ), name='password_reset'), password_reset_email_template.html: <html> <tr> <td style="color:#333333; font-family: Helvetica, sans-serif;text-align:left; font-size:14px; line-height:20px; padding-bottom:18px;text-align:left;"> {% load i18n %} {% autoescape off %} You're receiving this e-mail because you requested a password reset for account. {% endautoescape %} <p>Follow the link below to reset:</p> <a href="https://domain{% url 'password_reset_confirm' uidb64=uid token=token %}"> Reset Password </a> </td> </html> -
set() argument after * must be an iterable, not NoneType in Django
I have recently implemented a system where users can only submit 3 tags on their posts, and it will tell them that they can't if they try to upload more than 3. (Thanks for helping me do this @minglyu). Whilst this does work, I get this error after trying to resubmit the form with the right amount of tags set() argument after * must be an iterable, not NoneType I am using django-taggit at the moment for tags by the way Here is my forms.py class PostForm(forms.ModelForm): class Meta(): model = Post fields = ['title','text','group','image','file','tags','spoiler','NSFW'] widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'textareaclass editable'}), } def clean_tags(self): tn = self.cleaned_data.get('tags', []) if len(tn) > 3: raise ValidationError('Invalid number of tags') def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['image'].required = False self.fields['file'].required = False The issue is coming from the clean_tags method. Here is the views.py class PostListView(SelectRelatedMixin,TagMixin,ListView): model = Post hit_count = True template_name = 'mainapp/post_list.html' selected_related = ("user","group") paginate_by = 10 context_object_name = 'posts' queryset = models.Post.objects.all() def get(self,request,): posts = Post.objects.all().order_by('-published_date') users = User.objects.exclude(id=request.user.id) count= User.objects.all().count() friend, created = Friend.objects.get_or_create(current_user=request.user) friends = friend.users.all() group = Group.objects.all() args = { 'users':users, 'friends':friends, 'posts':posts, 'group':group,'count':count } return render(request, self.template_name, args) def get_queryset(self): return … -
Microsoft login page and Django
enter image description here I want to bring the Microsoft login page like the above picture on my Django project. can anybody help me here how to do it? -
two forloop that generates every item using one table row
I have two loops from my python which generates every item with their respective. \html <table> {% for sensie in teacher %} <tr style='height:19px;'> <th id="703183278R34" style="height: 19px;" class="row-headers-background"> <div class="row-header-wrapper" style="line-height: 19px;">35</div> </th> <td class="s46"></td> <td class="s51" colspan="3">{{sensie.Subjects}}</td> <td class="s51" colspan="4">{{sensie.Employee_Users}}</td> {% endfor %} {% for room in roomsched %} <td class="s51" colspan="6">{{room.Classroom}}-{{room.Day_Name}}</td> </tr> {% endfor %} </table> \views def enrollmentform(request): id = request.GET.get('StudentID') if StudentsEnrollmentRecord.objects.filter(Student_Users=id).exists(): studentenroll = StudentsEnrollmentRecord.objects.filter(Student_Users=id) FeesType = SchoolFeesMasterList.objects.filter(Education_Levels__in=studentenroll.values_list('Education_Levels')) teachers = SubjectSectionTeacher.objects.filter(Education_Levels__in=studentenroll.values_list('Education_Levels')) roomsched = SubjectRoomSchedule.objects.filter(Subject_Section_Teacher__in=teachers) return render(request, 'Homepage/enrollmentrecords.html',{"studentenroll":studentenroll,"SchoolFeesType":FeesType,"teachers":teachers,"roomsched":roomsched}) else: . . . return render(whatever I want) \models class SchoolFeesMasterList(models.Model): Education_Levels= models.ForeignKey(EducationLevel, related_name='grade', on_delete=models.CASCADE,blank=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE,blank=True) Payment_Types = models.ForeignKey(PaymentType, on_delete=models.CASCADE,blank=True) Display_Sequence = models.IntegerField(blank=True, null=True) School_Fees_Type= models.ForeignKey(SchoolFeesType, on_delete=models.CASCADE,blank=True) Amount = models.FloatField() Amount_Per_Unit = models.FloatField() Effectivity_Date_From = models.DateField(null=True,blank=True) Effectivity_Date_To = models.DateField(null=True,blank=True) Remark = models.TextField(max_length=500,blank=True) def __str__(self): suser = '{0.Education_Levels} {0.Courses}' return suser.format(self) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE,null=True) Education_Levels = models.ForeignKey(EducationLevel, on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, on_delete=models.CASCADE,null=True) Start_Date = models.DateField(null=True,blank=True) End_Date = models.DateField(null=True,blank=True) Remarks = models.TextField(max_length=500) def __str__(self): suser = '{0.Employee_Users}' return suser.format(self) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', … -
How do I create a separate model for relating primary keys of two models in a single table?
I have a User model and a Position Model, Where Position and User model both has username and position name as unique key. I want to create a separate table(which will be a relation table) where I can associate each user to their position. This is what I have tried : class Profile(models.Model): STATUS_CHOICES = ( (1, ("Permanent")), (2, ("Temporary")), ) GENDER_CHOICES = ( (1, ("Male")), (2, ("Female")), (3, ("Not Specified")) ) user = models.OneToOneField(User, on_delete=models.CASCADE) emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1) contact = models.CharField(max_length=13, blank=True) whatsapp = models.CharField(max_length=13, blank=True) gender = models.IntegerField(choices=GENDER_CHOICES, default=3) avatar = models.ImageField(upload_to='users/images', default='users/images/default.jpg') manager_username = models.ForeignKey(User, blank=True, null=True, to_field='username',related_name='manager_username', on_delete=models.DO_NOTHING) def __str__(self): return self.user.username class Position: name = models.CharField(max_length=20, unique=True) class Emp_position: emp_uname = models.ForeignKey(User, related_name='emp_name', to_field='username', on_delete=models.CASCADE) position_name = models.ForeignKey(Position, related_name='position', to_field='name', on_delete=models.CASCADE) It was working fine until I migrated Position table but when I am adding the relation table i.e Emp_position, I am getting an error : Traceback (most recent call last): File "C:\Users\Himanshu Poddar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\related.py", line 786, in __init__ to._meta.model_name AttributeError: type object 'Position' has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Himanshu Poddar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 381, in … -
URL with question mark slug calling incorrect Django view
I have a Django 2.2 project (using the rest framework) where I need to call a view function with a url of the following format: /class/students?date=07092019 and I've set up the following url route to handle this url:path('class/students?date=<str:date>/',StudentsInClassView.as_view() ,name='student'). The corresponding view function has the following definition: class StudentsInClassView(APIView): def get(self, request, date,format=None): For some reason, whenever I go to url, it gets converted to /class/students/?date=07092019 and a different view, with the url path('nba/students/',StudentsView.as_view() ,name='students'), gets called instead. If I remove the "?date=" from the url and just include the actual date, the StudentsInClassView is called as expected. How can I get the "?date=" slug to remain in the url as it is used to call the StudentsInClassView? -
Django Rest Framework endpoint to fetch data from an api and store in postgresql database
I am trying to build an API endpoint to fetch data from https://randomuser.me/api/ fake JSON API. I know Django rest framework very well but not getting how to build api endpoint to fetch data from another api endpoint. Can anyone give me a guideline how to build endpoint to fetch api from another api. I am new in web development THanks and regards -
Django file upload: redirect views keep returning errors
I have been working on this music site in Django, basically just trying to get the upload view to work. When you upload a music file, I want it to redirect to the results page. I have been having real trouble with trying to get the redirect to work and it should be very simple but just has not been working. Any help would be greatly appreciated!! My error: ValueError at /uploads/home/ The view uploads.views.upload didn't return an HttpResponse object. It returned None instead. uploads/views.py (relevant buggy code): def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('uploads:results') else: form = UploadFileForm() return render(request, 'uploads/upload.html', {'form': form}) uploads/urls.py from django.urls import path from . import views app_name = 'uploads' urlpatterns = [ path('home/', views.upload, name='index'), path('<int:audiofile_id>/results/', views.ResultsView.as_view(), name='results'), ] upload.html (the upload template) {% extends 'uploads/base.html' %} {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} {% block content %} <div class="container"> <div class="row"> <div class="col-lg-12 col-md-8"> {% for audiofile in audiofiles %} <h1>{{ audiofile.title }}</h1> </div> </div> <div class="row"> <div class="col-lg-12 col-md-8"> <form action="{% url 'uploads:results' audiofile_id %}" method="post" name = "form" enctype = "multipart/form-data"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> … -
How to POST image to django rest API
I am not too practiced in handling image files, and I am very confused about posting and handling an image using my django REST API. I am using a python script as client just for testing (will be ios app eventually). Anyone who can help me receive an image file, and save it locally on the server would be greatly appreciated. Client: i = Image.open('image.jpeg') upload = { 'id': 3, 'picture': i } r = requests.post(ip, data=upload, stream=True) print(r.text) Server: class Picture_Upload(APIView): def post(self, request): f = request.data['picture'] return Response(f.content) -
TemplateDoesNotExist only happen on prod ec2 but Templates works on local
I have running on my windows pc a django app with following structure this app also runs locally and works with this settings 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_mysql', 'users', 'posts', 'comments', ] 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', # 'chango2.middelware.ProfileCompletionMiddelware', ] libraries: { 'tags': 'tags', } ROOT_URLCONF = 'chango2.urls' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] this app work as expected when its runned locally with python manage.py runserver now i trying to deploy this app on a ec2 , i have configurated the security gropus to allow port 80 **and **8000 for inbound and outbound on ec2 i run with (env) ubuntu@ip-172-31-3-242:~$ gunicorn --bind 0.0.0.0:8000 chango2.wsgi:application app starts listening on port 8000 got the first page but for other link then i recive the the only thing changed between prod and local was ALLOWED_HOSTS = [my ec2 dns] and DATABASES (but that its working) -
Django Model Field - is there anyway to define a field that stores an object
I'm trying to add Django to my react project. Currently, I'm stuck on defining correlating model fields in Django to what I had in React state. This is what my old state looks like (when I stored all the info directly in the state) This is what my new state looks like (when I fetched the data from api and stored it into the state) The reason I want to have "teamBackground", "textColor", "votedUpColor", "votedDownColor" properties is that I want to be able to style each team. I tried defining these properties as CharField and JSONField, but they don't seem to be working. Is there anyway to solve this problem? -
NOT NULL constraint failed: snippets_choice.post_id
am trying to use the POST method here but it is throwing me an error. this is Models.py: from django.db import models class Post(models.Model): post_text=models.CharField(max_length=200) def __str__(self): return self.post_text class Choice(models.Model): post=models.ForeignKey(Post, on_delete=models.CASCADE) choice_text=models.CharField(max_length=200) likes=models.IntegerField(default=0) def __str__(self): return self.choice_text this is serializes.py: from rest_framework import serializers from snippets.models import Post, Choice class PostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=Post fields=['id','post_text'] class ChoiceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=Choice fields=['id','choice_text','likes'] this is views.py: from django.shortcuts import render from rest_framework import generics from rest_framework.reverse import reverse from .models import Choice, Post from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from snippets.serializers import ChoiceSerializer, PostSerializer class PostList(generics.ListCreateAPIView): queryset=Post.objects.all() serializer_class=PostSerializer name='post-list' class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset=Post.objects.all() serializer_class=PostSerializer name='post-detail' class ChoiceList(generics.ListCreateAPIView): queryset=Choice.objects.all() serializer_class=ChoiceSerializer name='choice-list' class ChoiceDetail(generics.RetrieveUpdateDestroyAPIView): queryset=Choice.objects.all() serializer_class=ChoiceSerializer name='choice-detail' class ApiRoot(generics.GenericAPIView): name='api-root' def get(self, request, *args, **kwargs): return Response({ 'posts': reverse(PostList.name, request=request), 'choices': reverse(ChoiceList.name, request=request), }) urls.py: urlpatterns=[ path('post-list/', views.PostList.as_view(), name='post-list'), path('post-list/<int:pk>/', views.PostDetail.as_view()), path('choice-list/', views.ChoiceList.as_view(), name='choice-list'), path('choice-list/<int:pk>/', views.ChoiceDetail.as_view()), path('',views.ApiRoot.as_view(),name=views.ApiRoot.name), ] when I try to post: { "id":3 "choice_text": "random text", "likes": 0 } I got this error: IntegrityError at /choice-list/ NOT NULL constraint failed: snippets_choice.post_id if am providing the id, why it is throwing an error? even in Postman, it's asking me to put 'choice_text', … -
How to render db data from consumer into template using django channels
I'm in the process of upgrading my application to be able to update my site in real time using Django Channels. I have a dashboard that would render the DB values from my view into the template tags i've added on my template. Now I want to do this but using Django Channels instead. So i've created a consumer, but i'm not sure how to receive the data inside my template. Previously I would just call {% for a in taskposted %} {{ a.TaskType }} {% endfor %} inside my template, but how do I access this using channels? consumer.py import asyncio import json from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from dashboard.models import Usertasks class DashboardConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept", }) user = self.scope['user'] tasks = await self.getTasks(user) print(tasks) async def websocket_receive(self, event): await self.send({ "type": "websocket.send", "text": event["text"], }) async def websocket_disconnect(self, event): print("Disconnected", event) @database_sync_to_async def getTasks(self, user): return Usertasks.objects.all().filter(user=user).filter(TaskStatus__in=["Computing", "Failed", "Waiting", "Finished",]) dashboard.html <script> var loc = window.location var wsStart = 'ws://' if (loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) socket.onmessage = function(e){ console.log("message", e) console.log(e.data) } socket.onopen … -
Reset Site name in cookiecutter
How can I change my site.name after i've been working in my project for a while? I've looked under django.contrib.sites but didn't find anything except for a migration that has set the name. -
Invalid credentials on Django social auth
I am using Django social_django and rest_framework_social_oauth2 for authentication in my app. I have successfully integrated Facebook. However I am facing a challenge integrating GoogleOAuth2. For starters I have these in my django settings INSTALLED_APPS = [ ...... 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', ..... ] AUTHENTICATION_BACKENDS = ( # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # Google SSO 'social_core.backends.google.GoogleOAuth2', # django-rest-framework-social-oauth2 'rest_framework_social_oauth2.backends.DjangoOAuth2', # Django 'django.contrib.auth.backends.ModelBackend', ) # Google Config SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = env('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = env('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET') SOCIAL_AUTH_GOOGLE_OAUTH2_IGNORE_DEFAULT_SCOPE = True SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ] My view basically does serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) provider = serializer.data.get('provider', None) strategy = load_strategy(request) backend = load_backend(strategy=strategy, name=provider, redirect_uri=None) if isinstance(backend, BaseOAuth2): access_token = serializer.data.get('access_token') user = backend.do_auth(access_token) and the serialiser is class SocialSerializer(serializers.Serializer): """ Serializer which accepts an OAuth2 access token and provider. """ provider = serializers.CharField(max_length=255, required=True) access_token = serializers.CharField(max_length=4096, required=True, trim_whitespace=True) The way I retrieve the token is via android as below gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestScopes(Scope(Scopes.PROFILE)) .requestServerAuthCode(serverClientId) .requestEmail() .build() mGoogleSignInClient = GoogleApiClient.Builder(this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso!!) .build() val signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleSignInClient) startActivityForResult(signInIntent, RC_SIGN_IN) /// Then at the callback point val account : GoogleSignInAccount? = completedTask.getResult(ApiException::class.java) val authCode = account?.serverAuthCode val call = apiService!!.socialLogin(SocialAuthLoginDto(provider = "google-oauth2", access_token = authCode)) processSignInCall(call) The client can successfully retrieve and post the token … -
Specify model names in select_for_update instead of relations
I would like to specify the table/model names instead of the relations in the QuerySet's model. Reason being the relation I'm linking to is a multi-table inheritance model. When I use select_for_update and provide relations using the of parameter, only the parent tables are "selected for update". Consider the piece of code: order = Order.objects.filter(uuid=order_uuid).prefetch_related( Prefetch( lookup='items', queryset=items ) ).select_related('outlet').select_related('user').select_related('outlet__group') \ .select_for_update(of=('self', 'outlet')) Here, outlet is a relation defined by outlet = models.ForeignKey(Outlet, on_delete=models.PROTECT, related_name="orders") Both the Order as well as Outlet models are sub-models to Transaction and Cashless models (which are situated in another Django app) By logging PSQL, this is the query that is being executed: SELECT "payment_gateway_transaction"."uuid", "payment_gateway_transaction"."ref_number", "payment_gateway_transaction"."shop_id", "payment_gateway_transaction"."user_id", "payment_gateway_transaction"."timestamp", "payment_gateway_transaction"."amount", "payment_gateway_transaction"."payment_method", "payment_gateway_transaction"."transaction_status", "payment_gateway_transaction"."service", "cashless_order"."transaction_ptr_id", "cashless_order"."token", "cashless_order"."outlet_id", "cashless_order"."order_status", "cashless_order"."order_start_time", "cashless_order"."order_end_time", "cashless_order"."order_collect_time", "cashless_order"."order_review", "cashless_order"."order_ratings", "authentication_user"."id", "authentication_user"."password", "authentication_user"."last_login", "authentication_user"."is_superuser", "authentication_user"."email", "authentication_user"."student_id", "authentication_user"."first_name", "authentication_user"."last_name", "authentication_user"."date_joined", "authentication_user"."ip_address", "authentication_user"."mac_address", "authentication_user"."location", "authentication_user"."phone_number", "authentication_user"."total_spent", "authentication_user"."is_banned", "authentication_user"."needs_student_id", "authentication_user"."generated_at", "authentication_user"."verify_token", "authentication_user"."is_active", "payment_gateway_shop"."uuid", "payment_gateway_shop"."name", "payment_gateway_shop"."location_id", "payment_gateway_shop"."location_coords", "payment_gateway_shop"."tax_applicable", "payment_gateway_shop"."percentage_tax", "payment_gateway_shop"."gst_number", "payment_gateway_shop"."open", "payment_gateway_shop"."active", "payment_gateway_shop"."group_id", "cashless_outlet"."shop_ptr_id", "cashless_outlet"."start_time", "cashless_outlet"."end_time", "cashless_outlet"."break_start_time", "cashless_outlet"."break_end_time", "cashless_outlet"."items_limit", "cashless_outlet"."image", "cashless_outlet"."description", "cashless_outlet"."on_cashless", "cashless_outlet"."ratings", "cashless_outlet"."latest_token", "auth_group"."id", "auth_group"."name" FROM "cashless_order" INNER JOIN "payment_gateway_transaction" ON ("cashless_order"."transaction_ptr_id" = "payment_gateway_transaction"."uuid") INNER JOIN "authentication_user" ON ("payment_gateway_transaction"."user_id" = "authentication_user"."id") INNER JOIN "cashless_outlet" ON ("cashless_order"."outlet_id" = "cashless_outlet"."shop_ptr_id") INNER JOIN "payment_gateway_shop" ON ("cashless_outlet"."shop_ptr_id" = "payment_gateway_shop"."uuid") INNER … -
Add values to context for render in Django
I have the following code inside a view: return render( request, 'home/index.html', { 'mobile':False, 'title':'Home', #'year': datetime.now().year, } ) So I used to always calculate the year in every view. I had to since it was needed in my layout.html Because of that I thought it would be a good idea to extract this calculation so I don't have to write it in each view specifically. I tried this using the following middleware: from datetime import datetime from django.utils.translation import gettext as _ def get_vars(get_response): def middleware(request): request.year = datetime.now().year return get_response(request) return middleware But it seems that the year variable is not added the same way it would be in the view. So my question is: How can I implement this functionality?` If not with a middleware how can I otherwise do it?