Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which one is better pgpool vs pgBouncer for Database connection Pooling
Currently working on monolithic Django Service. Want to use a Database pool so which one is better pgpool vs pgBouncer. p -
Unbound Local Error: local variable 'files' referenced before assignment
Unbound Local Error: local variable 'files' referenced before assignment Getting error above: Please tell me where I am getting wrong in this code. I am beginner in Django. And I tried so many times. In this project, I am doing multiple file upload using model forms. Please help me to solve this. views.py: from Django. shortcuts import render from user master. forms import Feed Model Form, File Model Form from .models import Feed File def create_ to_ feed(request): user = request. user if request. method == 'POST': form = Feed Model Form(request .POST) file_ form = File Model Form(request. POST, request. FILES) files = request. FILES. get list('file') #field name in model if form.is_ valid() and file_ form.is_ valid(): feed_ instance = form. save(commit=False) feed_ instance. user = user feed_ instance. save() for f in files: file_ instance = Feed File(file=f, feed=feed_ instance) file_ instance. save() else: form = Feed Model Form() file_ form = File Model Form() return render(request,' user master/multiplefile.html',{'form': form, 'file_ form': file_ form, 'files': files, 'user': user}) urls.py: path('multiple/', views. create_ to_ feed, name='create_ to_ feed'), ]+static(settings. MEDIA_ URL, document_ root= settings. MEDIA_ROOT)+static(settings. STATIC_URL, document_ root=settings. STATIC_ROOT) models.py: from Django. d b import models Create your … -
Create dynamic action URL form in Django python
whenever I submit the form it takes me to the testformresult page like https://www.studnentdetail.com/student/testformresult but What I want is, when someone enters the name of the student in the form.html page then data of that student is fetched from the mysql database and displayed on another page something like https://www.studentdetail.com/student/<student_name>. Also I want to know how like many railway site when we search for particular train like 10029 then in the next page it shows url something like https://www.train/10029-running-status. form.html <form method="POST" action="{% url 'testformresult' %}"> <label for="fname">First Name</label> <input type="text" id="fname" name="firstname" placeholder="Your name.."> <input type="submit" value="Submit"> </form> views.py def testform(request): return render(request, 'testform.html') def testformr(request): fname = request.POST.get('firstname') return render(request, 'testformresult.html') urls.py path('testform', views.testform, name='testform'), path('student/testformresult/<slug:student>', views.testformresult, name='testformresult'), -
Django. Retrieving data from a related model for use in a form
How can I automatically associate a user with an id_ ticket and fill in a field in the form? Sample form - https://i.stack.imgur.com/9YMUv.png models.py class Ticket(models.Model): ticket_id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') ticket_title = models.CharField(max_length=100) ticket_date_open = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='User') class TicketMessage(models.Model): ticket_mes = models.TextField(verbose_name='Message') ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) forms.py class TicketMessageForm(ModelForm): ticket_mes = forms.CharField(label='Answer', required=True) class Meta: model = TicketMessage fields = ('ticket_mes', 'ticket') views.py class Ticket(DetailView, CreateView): model = Ticket form_class = TicketMessageForm ticket_message = TicketMessage template_name = 'support/ticket.html' context_object_name = 'one_ticket' allow_empty = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['ticket_message'] = TicketMessage.objects.filter() return context def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user return super(Ticket, self).form_valid(form) success_url = reverse_lazy('ticket_list') I assume that need to somehow take the data from the template and pass it to form_valid. Tried adding a hidden field where passed the necessary information. This is works, but it looks wrong and unsafe. <select class="d-none" name="ticket" required="" id="id_ticket"> <option value="{{ one_ticket.ticket_id }}" selected="">{{ one_ticket.ticket_id }}</option> </select> -
Async Request with OpenAPI Generator Python
Happy New Year EveryOne I have a particular Case in which i am using OpenAPI generator for calling the api in another Microservice. I have two microservices ie User and Customer so in Customer im am getting the information of the multiple users from User below is the example code from user.api_clients import User user_id = [1, 2, 3, 4, 5, 6, 7, 8, 9] user_list = [User.api.get(id=i) for i in user_id] and the above code will give me the user_data from User. In short it will hit user api from User 9 times one by one. So is there any way to hit this in a single shot with asyncio. I am new to this async thing in python. So ill really appreciate if anyone can give me an idea about how to do this. There is also a similar case like i want to get object from User model in oneshot for these user_id list. Yes i can use id__in=user_id but is ther anyway to hit the below code in oneshot like below code user_id = [1, 2, 3, 4, 5, 6, 7, 8, 9] user_obj = [User.objects.get(id=i) for i in user_id] Thanks for helping -
How to add property decorator with return url path in existing model field how?
I am make a model with the md5_name field but i want to return a share_url key using property decorator in django python how. -
using method 'build_standard_field(self, field_name, model_field)' to overcame the error [<class 'decimal.InvalidOperation'>]
I'm writing a Django Rest Framework, and I want to use a generics.CreateAPIView to create an operation in my database. my models.py: class User(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField("Email Address", unique=True) first_name = models.CharField("First Name", max_length=150) last_name = models.CharField("Last Name", max_length=150) mobile = models.CharField("Mobile Number", max_length=150, blank=True) balance = models.DecimalField(max_digits=9, decimal_places=2, default=0.0, verbose_name=("Balance")) created_at = models.DateTimeField("Created at", auto_now_add=True, editable=False) class Operation(models.Model): sender = models.ForeignKey("User", related_name=("Sender"), on_delete=models.CASCADE) receiver = models.ForeignKey("User", related_name=("Receiver"), on_delete=models.CASCADE) amount = models.DecimalField(max_digits=9, decimal_places=2, default=0.0, verbose_name=("Amount")) created_at = models.DateTimeField("Created at", auto_now_add=True, editable=False) I want to send uuid values when creation the operation and handle the users filter in the backend using the view. So I added extra fields to the serializers as this: class OperationCreateSerializer(serializers.ModelSerializer): sender_uuid = serializers.UUIDField(format='hex_verbose') receiver_uuid = serializers.UUIDField(format='hex_verbose') amount = serializers.DecimalField(max_digits=9, decimal_places=2, coerce_to_string=False) class Meta: model = Operation fields = ["sender_uuid", "receiver_uuid", "amount"] write_only_fields = ["sender_uuid", "receiver_uuid"] class OperationListSerializer(serializers.ModelSerializer): class Meta: model = Operation fields = ["sender", "receiver", "amount"] The Problem is when I try to create the transfert operation I get error [<class 'decimal.InvalidOperation'>] for the field 'amount' in the view. The logic I'm using in my view is: class TransferView(generics.CreateAPIView): serializer_class = OperationCreateSerializer queryset = Operation.objects.all() def create(self, request, *args, … -
Dict columns extraction using for loop
There is a dict named 'data' { "error":false, "message":"Ok", "data":{ "numFound":1845, "start":0, "numFoundExact":true, "docs":[ { "sub_farmer_id":0, "grade_a_produce":320, "commodity_image":"red_carrot.jpg", "farm_image":"", "batch_status":"completed", "batch_count":30, "franchise_type":"TELF", "sr_assignee_id":0, "farm_status":"converted", "state_name":"RAJASTHAN", "farmer_id":1648, "grade_a_sell_price":0, "id":"11", "commodity_name":"Carrot Red", "acerage":1, "soil_k":0, "lgd_state_id":8, "soil_n":0, "unique_key":"11_8", "historic_gdd":0.41, "farm_type":"soiless", "soil_test_report":"", "user_id":1648, "expected_yield_delivery_date":"2020-04-30T00:00:00Z", "current_gdd":0, "soil_p":0, "expected_grade_a_produce":636, "water_ph":0, "end_date":"2020-04-30T00:00:00Z", "batch_id":8, "expected_delivery_date":"2020-04-30T00:00:00Z", "previous_crop_ids":"0", "batch_updated_at":"2021-12-29T17:50:58Z", "grade_c_rejection":0, "water_test_report":"", "farm_updated_at":"2021-12-29T17:51:00Z", "water_ec":0, "start_date":"2019-10-30T00:00:00Z", "assignee_id":0, "pest_problems":"", "expected_production":1060, "is_active":true, "mobile":"7015150636", "grade_b_sell_price":0, "irrigation_type":"drip", "total_acerage":0, "current_pdd":0, "commodity_id":68, "stage":"flowering", "farm_health":"0", "expected_grade_b_produce":424, "grade_b_produce":740, "historic_pdd":0.31, "username":"Agritecture", "variety_name":"", "sr_assignee_name":"", "lng":0, "locality":"", "assignee_name":"", "subfarmer_mobile_no":"", "commodity_image_96px_icon":"", "subfarmer_name":"", "batch_end_date":"", "lat":0, "_version_":1720553030989906000 } But I am trying to extract data from list and append in a new csv with different columns so that it looks neat and clean so, Here I am trying code writer = csv.DictWriter(response_data, fieldnames=['Farmer Name', 'Mobile', 'Irrigation Type', 'Batch Status', 'Soil Parameters', 'Water Parameters', 'Crop Name', 'Farm Status', 'Farm Type', 'Franchise Type', 'Farm Total Acerage', 'Batch Acerage', 'Farm Health(%)', 'Historical Yield(/Acre)', 'Expected Produce', 'Actual Yield(/Acre)', 'Actual Produce', 'Crop health(%)', 'Stage', 'SOP Adherence', 'Assignee', 'Sub Farmer', 'Last Activity Update', 'Exp. Delivery Date'], delimiter=",") writer.writeheader() for docs in data.keys(): writer.writerow( {"Farmer Name": docs.get('username'), "Mobile": docs.get('mobile') "Irrigation Type": data.get('irrigation_type'), "Batch Status": data.get('batch_status'), "Soil Parameters": {'N:-': data.get('soil_n'), 'P:-': data.get('soil_p'), 'K:-': data.get('soil_k')}, "Water Parameters": {'ec:-': data.get('water_ec'), 'pH:-': data.get('water_ph'), }, "Crop Name": data.get('commodity_name'), … -
how to create multiple object in list using loop
So, I want to create different objects every time loops run, my object is [name, age, dob] which is appended in an empty list data = [] I am using class class PersonsData(object): # Object constructor def __init__(self): print("Person Data") self.name = '' self.age = 0 self.doB = 0 # Input Method def enter_data(self): size = int(input("Enter the number of data")) for i in range(size): self.name = str(input("Enter Your Name" + " ").upper()) try: self.age = int(input("Enter Your Age" + " ")) except: print("\n**Enter value in Number**") self.age = int(input("Enter Your Age" + " ")) self.doB = (input("Enter Your DOB" + " ")) print("\n") # Display Method def display(self): print("Name:", self.name) print("Age:", self.age) print("DOB:", self.doB) the problem is instead of creating new object its just overwritting other, so ho I can create new object my other half of the code while True: print() print(""" 1.Add New Detail 2.Display Detail 3.Quit """) choice = int(input("Enter Choice:" + " ")) if choice == 1: info = PersonsData() info.enter_data() print(info.name) data.append(info) print(data) elif choice == 2: for i in data: print("--------------------------------") i.display() print("--------------------------------") elif choice == 3: quit() else: print("Invalid choice") I am new to python so, please don't judge me on the … -
not getting fetch data from OneToOneFiled in Django Rest Framework
Models.py- In Hiring Model class Driver field is OneToOneField, how to fetch data from that, i did not find any proper solution how to work with OneToOneField relation, please help me out class Driver(BaseModel): employee_id = models.CharField(max_length=8,unique=True,null=True, default=True) city = models.ForeignKey( City, models.CASCADE, verbose_name='City', null=True, blank=True ) location = models.ForeignKey( Location, models.CASCADE, verbose_name='Location', null=True, blank=True ) class City(BaseModel): name = models.CharField('Name', max_length=80) employee_series = models.CharField('Name', max_length=3) available_employee_id = models.IntegerField(default=1) def __str__(self): return self.name class Location(BaseModel): city = models.ForeignKey( City, models.CASCADE, verbose_name='City', ) name = models.CharField('Name', max_length=80) def __str__(self): return self.name class Hiring(BaseModel): driver = models.OneToOneField( Driver, models.CASCADE, related_name='driver', verbose_name='Driver', null=True, blank=True ) status = models.CharField(max_length = 255,choices=STATUS_CHOICES, null=True, blank=True) serializers.py class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ('id', 'name') class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ('id', 'name') class HiringstatusSerializer(serializers.ModelSerializer): class Meta: model = Hiring fields = ('id','driver', 'status') class DriverEditListSerializer(serializers.ModelSerializer): city = CitySerializer(read_only=True) location = LocationSerializer() hiring=HiringstatusSerializer(many=True, required=False, allow_null=True) class Meta: model = Driver fields=('id','city','location','hiring') views.py class DriverViewSet(viewsets.ModelViewSet): queryset = Driver.objects.filter(is_active=1) serializer_class = DriverEditListSerializer output- in output u can see in hiring field showing null value { "id": 4343, "city": { "id": 1, "name": "Mumbai" }, "location": { "id": 89, "name": "Santacruz" }, "hiring": null … -
How to handle inline formset in post method of generic CreateView?
I have a form and inline formset, both on the same page to update Ad and Picture model. Here is the code: class AdCreateView(CreateView): form_class = AdForm template_name = 'main/ad_create.html' success_url = '/ads' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['picture_form'] = ImageFormset() return context def post(self, request, *args, **kwargs): form = ???? picture_form = ??? if form.is_valid() and picture_form.is_valid(): **somehow save data from both forms to DB.** ??? return ? So the question is, how can I take the inline formset in post method and validate and save it? And what should I return? I mean is this a proper way of doing it or maybe there are other ways to do it. -
multiple forms in one step, Django Wizard form
I am trying to create 2 Model Forms in on Step, one of them is Modelformset, does someone did this before, it will be very helpful if i get some working code. I am using Django 2 in my project. Thank you. -
Is Django Unleashed book good to use when starting to learn Django?
Im new to creating websites and i want to use Django as my backend framework. I learn better using books and after browsing the internet for some learning materials i saw this book Django Unleashed. This book uses Django 1.8 but the latest version as of now is Django 3. Is it ok to use outdated book to learn Django or is there any better books? I hope u can help me on this. Thank you -
Django, common model used in several applications
In my project, there are applications named "developer" and "startup" In developer and startup application, i need a table named "languages", which implies that the language developer use and startup use. So i made model named "languages", But I'm thinking about whether to make this in developer application or startup application, or make a new application and make it in it. When I made it in developer application, i could use it by importing startup application models.py. But actually, I don't think that the table "languages" is more relevant to application "developler" than "startup". How should I do? I referenced link https://stackoverflow.com/questions/4137287/sharing-models-between-django-apps -
How to implement DB Connection Pool in Django
Django kills db connection after every request. It is an overhead to create a new db connection every time so how can we implement a connection pool from where we can use connection objects. -
Is there a clean way to lower the cyclomatic complexity of Django templates?
I have a Django template I'm working on that takes an object that has multiple properties and adds different tags based on those properties. For example if object.bold == True it adds the <b></b> tag, and if object.strikethrough == True it adds the <strike></strike> tag. I've seen some other posts that smell which suggest nesting the ifs like: {% for object in objects %} {% if object.bold == True %} {% if object.strikethrough == True %} <b><strike>{{object.name}}</strike></b> {% else %} <b>{{object.name}}</b> {% endif %} {% else %} {% if object.strikethrough==True %} <strike>{{object.name}}</strike> {% else %} {{object.name}} {% endif %} {% endif %} {% endfor %} This code hurts me. I've also seen some wonky logic with only wrapping the beginning tags in if statements. Again, it's painful to introduce console errors. Is there a better, cleaner way to achieve this result without nesting ifs? I'm leaning towards making a custom Django tag but that seems like overkill for something that I'm really hoping can be simpler. -
Heart disease prediction
I have source code to predict heart diseases, but it shows 1-if disease is exist, and 0-if none disease. I need to make precent of disease. Here is an example with logistic regression, but i have 4 algorithms, so i need to show precentege of risk. Actually, i am new in AI, so this is not my code at all but i need to improve it view.py: import csv,io from django.shortcuts import render from .forms import Predict_Form from predict_risk.data_provider import * from accounts.models import UserProfileInfo from django.shortcuts import get_object_or_404, redirect, render from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth.decorators import login_required,permission_required from django.urls import reverse from django.contrib import messages @login_required(login_url='/') def PredictRisk(request,pk): predicted = False predictions={} if request.session.has_key('user_id'): u_id = request.session['user_id'] if request.method == 'POST': form = Predict_Form(data=request.POST) profile = get_object_or_404(UserProfileInfo, pk=pk) if form.is_valid(): features = [[ form.cleaned_data['age'], form.cleaned_data['sex'], form.cleaned_data['cp'], form.cleaned_data['resting_bp'], form.cleaned_data['serum_cholesterol'], form.cleaned_data['fasting_blood_sugar'], form.cleaned_data['resting_ecg'], form.cleaned_data['max_heart_rate'], form.cleaned_data['exercise_induced_angina'], form.cleaned_data['st_depression'], form.cleaned_data['st_slope'], form.cleaned_data['number_of_vessels'], form.cleaned_data['thallium_scan_results']]] standard_scalar = GetStandardScalarForHeart() features = standard_scalar.transform(features) SVCClassifier,LogisticRegressionClassifier,NaiveBayesClassifier,DecisionTreeClassifier=GetAllClassifiersForHeart() predictions = {'SVC': str(SVCClassifier.predict(features)[0]), 'LogisticRegression': str(LogisticRegressionClassifier.predict(features)[0]), 'NaiveBayes': str(NaiveBayesClassifier.predict(features)[0]), 'DecisionTree': str(DecisionTreeClassifier.predict(features)[0]), } pred = form.save(commit=False) l=[predictions['SVC'],predictions['LogisticRegression'],predictions['NaiveBayes'],predictions['DecisionTree']] count=l.count('1') result=False if count>=2: result=True pred.num=1 else: pred.num=0 pred.profile = profile pred.save() predicted = True colors={} if predictions['SVC']=='0': colors['SVC']="table-success" elif predictions['SVC']=='1': colors['SVC']="table-danger" if predictions['LogisticRegression']=='0': colors['LR']="table-success" else: colors['LR']="table-danger" if predictions['NaiveBayes']=='0': … -
install a django application for a client and protect its source code or convert it to an executable
I have a Django web application, I want to install it for a client who doesn't want to use the internet so I have to install it locally on his pc, My question: what should I do to protect my source code. See that I have to put all my source code on his pc to be able to install the application, is there a possibility to encrypt the source code or to convert the django project into exe? thank you ! -
how to update multiple fields via
how to update multiple fields via Model.objects.bulk_create(list) I try it Model.objects.bulk_create(list).update(startD=startD, endD=endD) but error show 'list' object has no attribute 'update' -
How I can create registration form using using my own usermodel in django
I wanted to create my own registration form without using the crispy forms, I wanted to give my own styling to the form, please help me with steps or provide me a tutorial link. Thank You -
Using a custom form inside django wizard
How would I use a custom form to display inside the session wizard so when it goes through each step it displays the html for each form inside the signup.html. createUser.html {% extends 'base.html' %} {% block title %}Create User{% endblock %} {% block content %} <form method="POST" action='.' enctype="multipart/form-data"> {% csrf_token %} <!-- A formwizard needs this form --> {{ wizard.management_form }} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button><a href="{% url 'signup' %}">Sign up</a></button> <button><a href="{% url 'login' %}">Log In</a></button> </form> {% endblock %} views.py class UserWizard(SessionWizardView): template_name = "registration/signup.html" form_list = [SignUpForm] def done(self, form_list, **kwargs): process_data(form_list) return redirect('home') signup.html {% extends 'base.html' %} {% load i18n %} {% block head %} {{ wizard.form.media }} {% endblock %} {% block title %}Sign up{% endblock %} {% block content %} <h2>Sign up</h2> <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in … -
Exception: Matching query does not exist
I am trying to generate a token for users requesting for forget password. I have a model to handle and store this. models.py class ForgetPassword(models.Model): user = models.ForeignKey(CustomUser, on_delete= models.CASCADE) forget_password_token = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add= True) def __str__(self): return self.user.email The view functions that handles the request are below views.py def forget_password(request): try: if request.method == 'POST': user_email = request.POST.get('email') if CustomUser.objects.filter(email = user_email).exists(): user_obj = CustomUser.objects.get(email = user_email) name = user_obj.full_name plan = user_obj.plan print("\n this is the user : ", user_obj, " this is its name : ", name,"\n") token = str(uuid.uuid4()) fp = ForgetPassword.objects.get(user = user_obj) fp.forget_password_token = token fp.save() forget_password_mail.delay(user_email, name, token) messages.info(request, 'An email has been sent to your registered email.') return redirect('forget-password') else: messages.info(request, 'User does not exist') return redirect('forget-password') except Exception as e: print("\nthe exception is comming from forget_password : ", e, "\n") return render(request, 'fp_email_form.html') So, here I am trying to get the user first in user_obj from my CustomUser model and then I am trying to get the same user in the ForgetPassword model and store the token against that user. But I am getting the below exception ForgetPassword matching query does not exist. Please suggest or correcct me where … -
Django pagination not showing using class base view
Hi looking for a solution and yet nothing solve to my problem, I do not know why but it is not showing the paginate number in html file. here is structure code: class ListEmployeeActivity(ListView, LoginRequiredMixin): paginate_by = 1 model = EmployeePersonalDetailsModel template_name = 'layout/employee_list_layout.html' context_object_name = 'datalist' def get_queryset(self): return self.model.objects.prefetch_related('ecdm_fk_rn').all() html file: {% if is_paginated %} <div class="pagination pagination-centered"> <ul> {% if datalist.has_previous %} <li><a href="?page={{ datalist.previous_page_number }}"><i class="icon-double-angle-left"></i></a></li> {% endif %} {% for total_pages in datalist.paginator.page_range %} <li><a href="?page={{ total_pages }}">1</a></li> {% endfor %} {% if datalist.has_next %} <li><a href="?page={{ datalist.next_page_number }}"><i class="icon-double-angle-right"></i></a></li> <li><a href="?page={{ datalist.paginator.num_pages }}">Last</a></li> {% endif %} </ul> </div> {% else %} <h3>Pagination not working.</h3> {% endif %} -
Django causes error when I'm trying to send email. Error message: [Errno 61] Connection refused
I'm trying to send email from Django. My Django settings configurations are as follows: # SMTP Settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "my_email@gmail.com" # my email address goes here. EMAIL_HOST_PASSWORD = "my_generated_password" # generated password EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = "fmk@gmail.com" However when I'm trying to send email from it either using celery or directly from views it says "[Errno 61] Connection refused". N.B: I'm using a mac matchine for the development. Is there any security reason for send email using Mac. Views Code Sample: def send_mail_to_all(request): send_mail('Celery Test Mail Subject', "Test Mail Body", from_email='sender@gmail.com', recipient_list=['repientsemail@gmail.com'], fail_silently=False ) # send_mail_func.delay() return HttpResponse('Sent') Celery Task Schedular Code: @shared_task(bind=True) def send_mail_func(self): users = get_user_model().objects.all() for user in users: mail_subject = "Celery Testing" message = f"This is the celery testing message at {datetime.now()}" to_email = user.email send_mail(mail_subject, message, from_email=settings.EMAIL_HOST_USER, recipient_list=[to_email,], fail_silently=False ) return 'Done' -
create a dictionary of with key as the attribute and value as model object
Say i have this table: class Blog(models.Model) title = models.CharField() body = models.CharField() author = models.ForeignKey(Author) I need to create 3 rows with the title (title_1, title_2, title_3). I need to fetch all the blog objects and create a dictionary with key as the title and value as blog object. blog_dict = {'title_1': <blog_object_1>, 'title_2': <blog_object_2>, 'title_2': <blog_object_3>} I have 1 million records to work. Is there any efficient way to do it?