Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return Google Login URL via REST api using django-allauth library?
There is a project with connected and working Google authorization using the django-allauth library. The problem is that django-allauth returns an html template with a redirect button to Google Auth by url .../account/google/login. How to return NOT a TEMPLATE, but a link to Google Auth? The provider_login_url variable is inserted only into the template and there is no access to it. -
Django import my app models AppRegistryNotReady
I will import my models in celery.py. But when I import and run the runserver command, I get the following error: raise AppRegistryNotReady("Apps aren't loaded yet.") My import code line: from app.models import model1, model2 -
Django admin form fields are all on one line
I have an admin action which is followed by a form where users can choose several dates. class AddReportDateForm(forms.Form): _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) date = forms.DateField(required=False, widget=forms.SelectDateWidget(years=[timezone.now().year, timezone.now().year-1, timezone.now().year-2])) date1 = forms.DateField(required=False, widget=forms.SelectDateWidget(years=[timezone.now().year, timezone.now().year-1, timezone.now().year-2])) date2 = forms.DateField(required=False, widget=forms.SelectDateWidget(years=[timezone.now().year, timezone.now().year-1, timezone.now().year-2])) But on the admin form all these datewidgets are inline. Is there an easy way to get them all on a separate line. Without creating an admin template. Thanks in advance -
Django didn't create test database
I have a postgresql database defined in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'blog', 'USER': 'blog', 'PASSWORD': 'blog', 'HOST': 'postgres', 'PORT': '5432', }} Also I have a dummy test that creates a few objects in db class LogicTestCase(TestCase): @classmethod def setUp(cls): User.objects.create(username='test_user') Tag.objects.create(name='test_tag') Post.objects.create(title='test_title', post_text='test post text', author=User.objects.get(username='test_user')) def test_home(self): self.view = Home() print(self.view.get_context_data()) But when I run the tests - Django does not create a test database, instead of it Django uses my main DB to create objects. What have I done wrong with configuring my project? Django version==3.2.9 I run tests in a docker container, here is my docker-compose version: '3' services: blog: build: . command: bash -c 'python manage.py runserver 0.0.0.0:8000' ports: - "8000:8000" container_name: blog volumes: - .:/usr/src/blog restart: always depends_on: - postgres redis: image: redis restart: always postgres: image: postgres volumes: - '/tmp/postgres:/var/lib/psql/data' environment: POSTGRES_DB: 'blog' POSTGRES_USER: 'blog' POSTGRES_PASSWORD: 'blog' PGDATA: 'var/lib/psql/data/postgres' celery: restart: always build: . container_name: 'blog_celery' command: bash -c 'celery -A justblog worker -l INFO -E -B' -
Error while trying to switch the identifier to email in Django User model
I want to change the unique identifier of Django's User model from Username to Email so I write this: models.py: from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUserManager(BaseUserManager): ''' Custom user model manager where email is the unique identifier for authentication instead of username.' ''' def create_user(self, email, password, **extra_fields): ''' Create and save a User with the given email and password. ''' 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): ''' Create and save a SuperUser with the given email and password. ''' 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 admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser # Register your models here. class CustomUserAdmin(UserAdmin): model = CustomUser list_display = ('email', 'is_staff', 'is_active') list_filter = ('email', 'is_staff', 'is_active') fieldsets = … -
How to migrate specific models in another database in django?
I have two databases in my Django project settings (app1_db, app2_db) and I have a model in app1 that I want to migrate to app1_db. How can I do this? I tried to use Django routers but it didn't work for me. the router goes to sync all models in an app to a specific database but I want that just a specific model goes to that database. -
How do I get the oldest item in an SQLite3 database with django [closed]
Using Django, how would I get the oldest object in my SQLite3 database and delete it if a specific condition is true? I am hoping to do this from the views.py file in my app. -
NameError: name 'model_object' is not defined
I'm trying to get all model operations in my django app with the following code but it returns an error. I get the error NameError: name 'model_object' is not defined def admin_main(request): logs = LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(model_object).pk, object_repr=unicode(obj), object_id=obj.id, message="", action_flag=ADDITION if create else DELETION) logs = logs.order_by('-action_time')[:40] return render(request,'history.html', {"logs":logs}) -
DJANGO : How to filter the last data collected for each type of object in a model?
Let's say I have this model class TreeCensus(models.Model): name = models.CharField() #Oak, elm, ... identified_at = models.DateTimeField(auto_now_add=True) I want to get a QS with the last Census of each tree. I tried naively this TreeCensus.object.order_by('name').last() But It obviously returned me the last of all the TreeCensus objects. So what is the best way (or at least a good one) to do this? For example if there are 2 Oak in the QS I want to get the first one filtered -
Terminate previous Celery task with same task id and run again if created
In my django project, I have made a view class by using TemplateView class. Again, I am using django channels and have made a consumer class too. Now, I am trying to use celery worker to pull quearyset data whenever a user reflesh the page. But the problem is, if user again reflesh the page before the task gets finished, it create another task which causes overload. Thus I have used revoke to terminate the previous running task. But I see, the revoke permanently revoked the task id. I don't know how to clear this. Because, I want to run the task again whenever user call it. views.py class Analytics(LoginRequiredMixin,TemplateView): template_name = 'app/analytics.html' login_url = '/user/login/' def get_context_data(self, **kwargs): app.control.terminate(task_id=self.request.user.username+'_analytics') print(app.control.inspect().revoked()) context = super().get_context_data(**kwargs) context['sub_title'] = 'Analytics' return context consumers.py class AppConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() analytics_queryset_for_selected_devices.apply_async( args=[self.scope['user'].username], task_id=self.scope['user'].username+'_analytics' ) -
Django ORM Query to get number of currently subbed user
I use an Event log that tracks subscriptions and unsubscriptions to given mailing lists. My objective is to hit the database one time (sqlite) to get the number of subscribed users, I don't need the objects, just a number. models.py class MailingListEvent(models.Model): """Events on mailing lists. This represents subscribes, unsubscribes, and bounces. We'd like to understand what happens and when, not just the current state of the system. """ class EventType(models.TextChoices): SUBSCRIBE = 'sub', 'inscription' UNSUBSCRIBE = 'unsub', 'désinscription' BOUNCE = 'bounce', 'bounce' user = models.ForeignKey(User, on_delete=models.CASCADE) mailing_list = models.ForeignKey(MailingList, on_delete=models.CASCADE) event_timestamp = models.DateTimeField(default=django.utils.timezone.now) event_type = models.CharField(max_length=6, choices=EventType.choices) So far I found only this solution to work with : def user_subscribe_count(mailing_list): """Return the number of users currently subscribed to the mailing list. We want to know how many users are currently subscribed. Note that individual users might subscribe and unsubscribe multiple times. Other (future) events could happen as well. """ user_list = MailingListEvent.objects.filter(mailing_list=mailing_list).values_list('user',flat=True).distinct() users_subscribed = list() for user in user_list: user_state = user_current_state(User.objects.get(pk=user),mailing_list) if user_state.event_type == MailingListEvent.EventType.SUBSCRIBE: users_subscribed.append(user_state) return len(users_subscribed) I know there is a .count() method on Django, but converting to list already hits the database anyway. Can someone suggest a query that would return the number of users … -
Django - How to return multiple querysets with get_queryset() - ListView
I have a blog with an option to view a specific user's profile showing a list of posts the user posted. The posts are being returned in a ListView. Each post also comes with comments. So currently, my get_queryset() method returns a queryset of the comments for the post ordered by total of highest likes. models.py class Post(models.Model): title = models.CharField(max_length=100, help_text="100 characters or less") content = models.TextField() category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) liked = models.ManyToManyField(Profile, blank=True, related_name='likes') views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): return ( super() .get_queryset() # Prefetch comment using a Prefetch object .prefetch_related( Prefetch( "comment_set", # Specify the queryset to annotate and order by Count("liked") queryset=Comment.objects.annotate( like_count=Count("liked") ).order_by("-like_count"), # Prefetch into post.comment_list to_attr="comment_list", ) ) ) How can I return another queryset? I read from another discussion to use chain(), but it didn't work for me. How to return multiple queryset object or add queryset result from get_queryset method in Django Right now, this returns Post.objects.all() But I want to return #second queryset user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') I could add this to a context as below … -
Django - How to query top products for each date in given interval of dates using aggregation and filter the results of TruncDay
If I have these 4 models of Order, LineItem, Payment, and Product. How can I get the most sold products at given days? class Product(models.Model): sku = models.CharField(...) ... class Order(models.Model): ... class LineItem(models.Model): order = models.ForeignKey(Order, ...) product = models.ForeignKey(Product, ...) amount = models.PositiveIntegerField(...) ... class Payment(models.Model): order = models.ForeignKey(Order, ...) paid_at = models.DateTimeField(...) .... I have tried to approach this from the LineItem model. ten_days_ago = timezone.now() - timedelta(days=10) queryset = LineItem.objects.filter( order__payment__paid_at__gte=ten_days_ago ) .annotate(date=TruncDay("order__payment__paid_at") .aggregate( max_sales=Max( "amount", filter=Q( order__payment__paid_at__gte="date", order__payment__paid_at__lte=F("date") + timedelta(days=1), ), ) ) this gives a django.core.exceptions.ValidationError: ['“date” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] I doubt the query will work even with valid date format, but, assuming it will work how do I do I format the "date" and F("date") expression to valid date? And if it indeed will not work, how do I query such cases? thank you. -
how I can open page for each user in list and add more information python django
I have a list of users in the table. I want when I click on any user it open "user_information page". "user_information page" has two buttons "ADD MORE" and "SAVE". The "SAVE" button saves the information and shows them as a block, and it should save for that user. The "ADD MORE" button allows user to fill the fields with different information (user name, work address, user position) -
Django: Only the First Image getting to Database with every pickd instance even though all images are properly read from the excel sheet
Hey guys I am having trouble extracting image links from an excel sheet and saving to database in django. The problem is, even though all image links are being extracted correctly, only the first image is getting into database. For example, if Picked is a model, and PickedImage has a foreign key to Picked. then even after extracting all images, only the first image is getting stored in database. if I provide 6 different images to PickedImage for a single Picked instance. The rest of the images are in the list but not getting stored to database instead the first image will be stored 6 times. This is the code, can someone help. for pickd in data['pickd']: # loop to create pickd image model instance if pickd['title'] is None or pickd['title'] == '': continue i += 1 try: if pickd['image1'] is not None: bulk_image.append(Image(picks=instance[i], images=downloadImage(pickd['image1'], pickd['title']).open(mode='rb'), main=True)) if pickd['image2'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image2'], pickd['title']).open(mode='rb'))) if pickd['image3'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image3'], pickd['title']).open(mode='rb'))) if pickd['image4'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image4'], pickd['title']).open(mode='rb'))) if pickd['image5'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image5'], pickd['title']).open(mode='rb'))) if pickd['image6'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image6'], pickd['title']).open(mode='rb'))) except Exception as e: continue def downloadImage(url, Name): """ Method to download images from a given url """ … -
request.user always returns AnonymousUser
I have created a django model which includes a foreign key to a user as follows: from authentication.models import User from django.db import models class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) My serializers.py file is as follows: class EventSerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) class Meta: model = Event fields = ['user', 'dr_notice_period', 'dr_duration', 'dr_request'] My views.py is as follows: from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from vpp_optimization.serializers import EventSerializer @api_view(['POST']) def event(request): serializer = EventSerializer(data=request.data) if serializer.is_valid(): instance = serializer.save(commit=False) instance.user = request.user instance.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) What I need to do is to go to a URL and login as a user. Then I need to go to another URL and add with POST request some details about the event and save the details as well as the user in the database. However after login and POST request I get the following error: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f7daf1469d0>": "Event.user" must be a "User" instance. It seems that it always returns an AnonymousUser, although I have logged in. Any idea of … -
how to create a python django model for elasticsearch with base library
In my view I query elasticsearch db but it isn't good pratice. I want follow mvc pattern, so how to create a python django model for elasticsearch? I use simple base elasticsearch library. Please, guide me. controller-view view_home.py from django.shortcuts import render, redirect from django.conf import settings from pygiustizia.models.model_users import Users from pygiustizia.models.model_docfields import * import logging import json from elasticsearch import Elasticsearch from django.http import JsonResponse from django.template.loader import render_to_string def show_results(request): print('####### show_results ########') ELASTICSEARCH_URL = getattr(settings, 'ELASTICSEARCH_URL', 'localhost:9200') ELASTICSEARCH_INDEX = getattr(settings, 'ELASTICSEARCH_INDEX', 'civile') print(ELASTICSEARCH_INDEX) esSearchPageClient = Elasticsearch([ELASTICSEARCH_URL]) size = 2 fromSize = 0 bodyPageAllDoc={ "size": size, "from": fromSize, "query": { "match": { "distretto": "MI"} }, "_source": ["text"], "sort": [{"_id": "asc"}] } resPage = esSearchPageClient.search(index=ELASTICSEARCH_INDEX, body=bodyPageAllDoc) #print(resPage) html = render_to_string('pygiustizia/home/process_show_results.html') return JsonResponse({'cat':1,'html':html}) -
Streaming video using Python - two different site users
I want to make a website where users can join that can be seen through their webcams. I mean streaming video of two different users of the site through their webcams e.g. on a laptop. I will be setting up the website probably on AWS. I want to do this using Python (Flask/Django, nginx, Ubuntu etc). Can you recommend a library/some sources to make this possible? OpenCV? Or something else? -
Django Ajax POST request fail to redirect
I am trying to create a website to capture picture from client's camera and save it in the database. However after everything was saved, I cant seem to redirect the page. views.py def facial_capture(request): if request.method == 'POST': file = request.FILES['snap'] if file: student = Student.objects.get(id=request.session['id']) if student: FaceImage.objects.create(student=student, image=file) return HttpResponse("{'status': 1}", content_type='application/json') return HttpResponse("{'status': 0}", content_type='application/json') return render(request, 'id_capture/facial_capture.html') face_capture.html {% block body %} <div class="container"> <form>{% csrf_token %} <video id="video" width="640" height="480" autoplay></video> <button id="send">Submit</button> <canvas id="image_canvas" width="640" height="480"></canvas> </form> </div> {% endblock %} face_capture.js $(document).ready(function () { var video = document.getElementById('video'); var canvas = document.getElementById('image_canvas'); var context = canvas.getContext('2d'); var w = 640, h = 480; if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }).then(stream => { video.srcObject = stream; video.play(); }); } document.getElementById("send").addEventListener("click", function() { context.translate(w, 0); context.scale(-1, 1); context.drawImage(video, 0, 0, w, h); canvas.toBlob(upload, "image/jpeg"); }); function upload(file) { var formData = new FormData(); formData.append("snap", file); const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; $.ajax({ headers: {'X-CSRFToken': csrftoken}, type: 'POST', url: '/signup/facial_capture', data: formData, cache: false, processData: false, contentType: false, enctype: 'multipart/form-data', success: function(data){ console.log('response received'); if (data.status == 1) { console.log('status ok'); window.location.href = "login"; } else { console.log('status failed'); window.location.reload(); } } }) } }); I assume … -
How to fix absolute import problem in Django?
I try to figure it out why can't I import a module but I have no success. My structure is very simple: exitinterview firm stressz -models.py performance -emails.py I want to import Projects class from stressz.models into emails.py like this: from stressz.models import Project But I always get this error: ModuleNotFoundError: No module named 'stressz' I have stressz in my settings.py in the INSTALLED_APPS -
Picking last item in before a time in django
Here i have to filter this model by created_at and after that i have to pick the last item per user this is my model: class UserWorkPattern(models.Model): user = models.ForeignKey("profile.User", on_delete=models.CASCADE) work_pattern = models.ForeignKey("workpattern.WorkPattern", on_delete=models.CASCADE) offset = models.ForeignKey('workpattern.ShiftPeriod', on_delete=models.CASCADE, null=True, blank=True, verbose_name='shift offset', help_text='delivered shift period.') created_at = models.DateTimeField(default=now) updated_at = models.DateTimeField(default=now) def __str__(self): return str(self.user) + ' - ' + str(self.work_pattern) How can i do that by writing a query and not pythonic way! -
I can't send file to django server through angular and error says: The submitted data was not a file. Check the encoding type on the form
my code is like this and I send data through httpClient and it returns error on upload my angular version is 13 and django version is 4 and I'm using django rest framework for restApi ng component const data={ "image_url":this.imgFile, "caption": this.caption, 'author':1 }; console.log(data); this.service.createPost(data).subscribe(res=>console.warn(res)); } onFileChanged(event:any) { const reader = new FileReader(); this.file = event.target.files[0]; if(!this. file) return reader.readAsDataURL(this.file); reader.onload = () => { this.imgFile = reader.result as string; }; } django model caption = models.CharField(max_length=4000) likes = models.IntegerField(default=0, blank=True) is_liked = models.BooleanField(default=False, blank=True) date = models.DateTimeField(auto_now_add=True) image_url = models.ImageField(upload_to='images', blank=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __unicode__(self): return (self.caption) def __str__(self): return self.caption + ' | ' + str(self.likes) django view def get(self, req): data = Post.objects.all() serialized = PostSerializer(data, many=True) return Response(serialized.data) def post(self, request): serializer = PostSerializer(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 Serializer class PostSerializer(serializers.ModelSerializer): # image_url = ThumbnailerSerializer(alias='avatar') class Meta: model = Post fields = '__all__' def create(self, validated_data): return Post.objects.create(**validated_data) -
How to apply a for statement to simplify repeated code in Django queryset
The filter is applied according to team_parameter(request.GET.get('team)) and it has very repetitive code. At the end of the if statement, no filter is applied only if team_parameter is 'ALL'. I think a for statement is necessary to minimize this code, but I did not know how to apply it, so I asked a question. Please let me know which loops are needed to simplify the code below. Help. [views.py] team_parameter = request.GET.get('team') if team_parameter == 'A' and not team_parameter: monthly_enroll = Feedback.objects.filter(uploader_id__contact__team='A')\ .values('uploader_id__first_name').distinct().order_by('uploader_id__first_name')\ .annotate(jan=Count('client_id', filter=Q(enroll_date__gte='2022-01-01', enroll_date__lte='2022-01-31')), feb=Count('client_id', filter=Q(enroll_date__gte='2022-02-01', enroll_date__lte='2022-02-28')), mar=Count('client_id', filter=Q(enroll_date__gte='2022-03-01', enroll_date__lte='2022-03-31')), apr=Count('client_id', filter=Q(enroll_date__gte='2022-04-01', enroll_date__lte='2022-04-30')), may=Count('client_id', filter=Q(enroll_date__gte='2022-05-01', enroll_date__lte='2022-05-31')), jun=Count('client_id', filter=Q(enroll_date__gte='2022-06-01', enroll_date__lte='2022-06-30')), jul=Count('client_id', filter=Q(enroll_date__gte='2022-07-01', enroll_date__lte='2022-07-31')), aug=Count('client_id', filter=Q(enroll_date__gte='2022-08-01', enroll_date__lte='2022-08-31')), sept=Count('client_id', filter=Q(enroll_date__gte='2022-09-01', enroll_date__lte='2022-09-30')), oct=Count('client_id', filter=Q(enroll_date__gte='2022-10-01', enroll_date__lte='2022-10-31')), nov=Count('client_id', filter=Q(enroll_date__gte='2022-11-01', enroll_date__lte='2022-11-30')), dec=Count('client_id', filter=Q(enroll_date__gte='2022-12-01', enroll_date__lte='2022-12-31')),)\ .values_list('uploader_id__first_name', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sept', 'oct','nov', 'dec')\ .order_by('uploader_id__first_name') elif team_parameter == 'B': monthly_enroll = Feedback.objects.filter(uploader_id__contact__team='B')\ .values('uploader_id__first_name').distinct().order_by('uploader_id__first_name')\ .annotate(jan=Count('client_id', filter=Q(enroll_date__gte='2022-01-01', enroll_date__lte='2022-01-31')), feb=Count('client_id', filter=Q(enroll_date__gte='2022-02-01', enroll_date__lte='2022-02-28')), mar=Count('client_id', filter=Q(enroll_date__gte='2022-03-01', enroll_date__lte='2022-03-31')), apr=Count('client_id', filter=Q(enroll_date__gte='2022-04-01', enroll_date__lte='2022-04-30')), may=Count('client_id', filter=Q(enroll_date__gte='2022-05-01', enroll_date__lte='2022-05-31')), jun=Count('client_id', filter=Q(enroll_date__gte='2022-06-01', enroll_date__lte='2022-06-30')), jul=Count('client_id', filter=Q(enroll_date__gte='2022-07-01', enroll_date__lte='2022-07-31')), aug=Count('client_id', filter=Q(enroll_date__gte='2022-08-01', enroll_date__lte='2022-08-31')), sept=Count('client_id', filter=Q(enroll_date__gte='2022-09-01', enroll_date__lte='2022-09-30')), oct=Count('client_id', filter=Q(enroll_date__gte='2022-10-01', enroll_date__lte='2022-10-31')), nov=Count('client_id', filter=Q(enroll_date__gte='2022-11-01', enroll_date__lte='2022-11-30')), dec=Count('client_id', filter=Q(enroll_date__gte='2022-12-01', enroll_date__lte='2022-12-31')),)\ .values_list('uploader_id__first_name', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sept', 'oct','nov', 'dec')\ .order_by('uploader_id__first_name') elif team_parameter == 'C': monthly_enroll = Feedback.objects.filter(uploader_id__contact__team='C')\ .values('uploader_id__first_name').distinct().order_by('uploader_id__first_name')\ .annotate(jan=Count('client_id', filter=Q(enroll_date__gte='2022-01-01', enroll_date__lte='2022-01-31')), … -
how to work with foreign key field in django
Hi Everyone i am working work django framework, where i used to upload excel file in Dailytrip table, current i get car_mumber from car table, but now i need to store car_number from Car_team table also team_id, i am storing car_id and team_id in car_team table also i need to store team_id in dailytrip table automaticlly based on car_id(car_number) i am to much confuse how to i work that, pls help me out models.py class Car_team(BaseModel): team = models.ForeignKey( Team, models.CASCADE, verbose_name='Team', null=True, ) car=models.ForeignKey( Car, models.CASCADE, verbose_name='Car', null=True) city =models.ForeignKey( City, models.CASCADE, verbose_name='City', ) start_date=models.DateField(null=True, blank=True) end_date=models.DateField(null=True, blank=True) views.py def add_payout_uber_daily_data(request): if request.method == 'POST': form = UberPerformanceDataForm(request.POST, request.FILES, request=request) if form.is_valid(): date = form.cleaned_data['date'] excel_file = request.FILES['file'] df = pd.read_excel(excel_file) is_na = pd.isna(df['Date']).sum().sum() + pd.isna(df['Name']).sum().sum() + pd.isna(df['UUID']).sum().sum() + pd.isna(df['Net Fare With Toll']).sum().sum() + pd.isna(df['Trips']).sum().sum() + pd.isna(df['Uber KMs']).sum().sum() + pd.isna(df['CashCollected']).sum().sum() + pd.isna(df['UberToll']).sum().sum() + pd.isna(df['Tips']).sum().sum() + pd.isna(df['Hours Online']).sum().sum() + pd.isna(df['Ratings']).sum().sum() + pd.isna(df['Acceptance Rate']).sum().sum() + pd.isna(df['Cancellation Rate']).sum().sum() error_list = [] if is_na > 0: error_list.append('Found #N/A or blank values in the sheet. Please correct and re-upload') context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, } return render(request, 'add_payout_uber_daily_data.html', context=context) date_match = True for d in df['Date']: if str(d.strftime("%Y-%m-%d")) != str(date): date_match … -
Django authentication with phone number and OTP
In my Django app, I have to authenticate with phone number and OTP on every login. I don't want to store passwords in the user table. How can i customize the Django user model and authentication backend for this?. please help me to figure this out.