Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use aggregate functions in subquery Dajngo
I'm trying to get the sum of the minimum values of an option price, grouped by option type, to use in a Subquery when displaying products, but I can't use the aggregate functions I need. My code: class ProductManager(models.Manager): def get_queryset(self): add_subquery = OptionOfProduct.objects.filter( product_fk_id=OuterRef('pk'), option_fk__required=True, price__isnull=False, option_fk__operation='add' ).values('option_fk').annotate( min_price=Min('price') ).values('min_price') # ^ I need to get Sum from this subquery results # it return structure like this: # <QuerySet [{'min_price': Decimal('200')}, {'min_price': Decimal('100')}]> lowest_option_price_subquery = OptionOfProduct.objects.filter( product_fk_id=OuterRef('pk'), option_fk__required=True, price__isnull=False ).values('product_fk').annotate( cheapest_equal_price=Min('price', filter=models.Q(option_fk__operation='equal')), cheapest_add_price=Subquery(add_subquery), cheapest_price= Case( When( cheapest_add_price__isnull=False, cheapest_equal_price__isnull=True, then=F('cheapest_add_price') + F('product_fk__price') ), When( cheapest_add_price__isnull=False, then=F('cheapest_equal_price') + F('cheapest_add_price') ), When( cheapest_add_price__isnull=True, then=F('cheapest_equal_price') ), default=F('product_fk__price') ), ).values('cheapest_price') return super().get_queryset().annotate( lowest_option_price_2=Coalesce( Subquery(lowest_option_price_subquery), F("price"), output_field=DecimalField(decimal_places=2, max_digits=9) ) ) -
How to validate JSON using serializers with rest_framework
i'm face with this problem : how to serialize list of int, string and bool using rest_framework ? Imagine this JSON : { "start_hour": "14:02:26", "DEVICE_INFO": [ "0101", true, 13 ] } I have tried ListSerializer(), ListField()... Any ideas ? -
A type errpr on my django admin site trying to load an image
TypeError at /media/images/Shirt_1.jpeg serve() got an unexpected keyword argument 'documents_root' Request Method: GET Request URL: http://127.0.0.1:8000/media/images/Shirt_1.jpeg Django Version: 4.2 Exception Type: TypeError Exception Value: serve() got an unexpected keyword argument 'documents_root' Exception Location: /Users/mac/Desktop/Duefex/myvenv/lib/python3.10/site-packages/django/core/handlers/base.py, line 197, in _get_response Raised during: django.views.static.serve Python Executable: /Users/mac/Desktop/Duefex/myvenv/bin/python Python Version: 3.10.9 Python Path: ['/Users/mac/Desktop/Duefex/ecommerce', '/opt/homebrew/Cellar/python@3.10/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/opt/homebrew/Cellar/python@3.10/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10', '/opt/homebrew/Cellar/python@3.10/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload', '/Users/mac/Desktop/Duefex/myvenv/lib/python3.10/site-packages'] Server time: Wed, 12 Apr 2023 09:37:21 +0000 Iran my server and trying to load my image but it didn’t work -
How to send an e-mail with image atachment using celery and dajngo?
I want to use celery for sending an e-mail with photo, but I am getting the "Object of type bytes is not JSON serializable" error. I just don't understand how to properly do it. As far as I see, celery doesn't support bytes. But I tried to convert it to string and get other error. views.py from main_app.tasks import send_creator_submission_email_task class BecomeCreatorView(TemplateView): template_name = 'become_creator.html' become_creator_form = BecomeCreatorForm success_url = reverse_lazy('index') def get(self, request, *args, **kwargs): form = self.become_creator_form() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.become_creator_form(request.POST, request.FILES) if form.is_valid(): photo = form.cleaned_data['photo'] send_creator_submission_email_task.delay(self.kwargs.get('slug'), photo.file, photo.name) messages.success(request, "Thank you!") return redirect(self.success_url) messages.error(request, "Error!") return render(request, self.template_name, {'form': form}) tasks.py @shared_task def send_creator_submission_email_task(slug, image_file, image_filename): return send_creator_submission_email(slug, image_file, image_filename) email.py def send_creator_submission_email(slug, image_file, image_filename): user = get_object_or_404(User, slug=slug) current_site = Site.objects.get_current().domain email_context = { 'current_site': current_site, 'user_email': user.email, 'user_slug': user.slug, 'approve_url': f"http://{current_site}{reverse_lazy('approve_user', kwargs={'slug': user.slug})}", "decline_url": f"http://{current_site}{reverse_lazy('decline_user', kwargs={'slug': user.slug})}" } html_message = render_to_string('email/admin_decision_email.html', email_context) plain_message = strip_tags(html_message) email = EmailMultiAlternatives( subject="New creator submission", body=plain_message, from_email=settings.DEFAULT_FROM_EMAIL, to=[settings.EMAIL_ADMIN], ) email.attach_alternative(html_message, "text/html") email.attach(image_filename, image_file.read()) email.send() If you want to recreate the case, these files are for you: forms.py class BecomeCreatorForm(forms.Form): photo = forms.ImageField( required=True, widget=forms.ClearableFileInput ) admin_decision_email.html {% autoescape off … -
How to prevent the user from seeing other subscribers email in Django
I created a django newsletter functionality where users subscribe and I use the emails subscribed to send the newsletter to those emails. Now the problem I want your help is when I send the newsletter to the subscribers the receiver can see other subscribers emails. I have tried to add BCC but still not working. bellow is my views.py def send_newsletter(request): if request.method == 'POST': subject = request.POST['subject'] body = request.POST['body'] from_email = settings.EMAIL_HOST_USER # get all subscribers' email addresses subscribers = Newsletter.objects.all() to_email = [subscriber.email for subscriber in subscribers] bcc = [instance.email if instance.email != from_email else None for instance in subscribers] html_message = get_template('newsletter/newsletter.html').render({'message': body}) # Create the email message object email = EmailMessage( subject, strip_tags(body), from_email, to_email, bcc, headers={'To': 'Undisclosed Recipients <{}>'.format(from_email)} ) email.content_subtype = 'html' email.attach_alternative(html_message, "text/html") email.send() # Save newsletter to database newsletter = NewsletterText.objects.create(subject=subject, body=body, status='Published') newsletter.save() messages.success(request, 'Newsletter sent successfully') return redirect('blog:home') return render(request, 'newsletter/send_newsletter.html') I also tried to use Undisclosed recipients as the code bellow shows def send_newsletter(request): if request.method == 'POST': subject = request.POST['subject'] body = request.POST['body'] from_email = settings.EMAIL_HOST_USER # get all subscribers' email addresses subscribers = Newsletter.objects.all() to_email = [subscriber.email for subscriber in subscribers] bcc = [] html_message = … -
Daterange not found in django
I am trying to build an app in my django. When I am trying to run the server it's showing the error of daterange module not found. i have installed daterange multiple time. what else could be the issue? This is the issue These are the folders Kindly let me know where and what I am doing wrong -
How to avoid similiar queries in for loop in django template
I have code with 2 for loops in django template which iterate my model and show info in template from that model But for some reason Debugger show me that i have similiar queries in my second for loop and i dont know how to avoid that template.html {% for info_list in details_list %} <tr> <td>{{ info_list.presence_info.object_presence }}</td> <td>{{ info_list.presence_info.counter_presence }}</td> <td>{{ info_list.work_date }}</td> <td>{{ info_list.amount_of_workers }}</td> <td> {% for sections in info_list.parts_with_sections.all %} {{ sections.presence_sections.name }} | {% endfor %} </td> </tr> {% endfor %} models.py class PresenceListInfo(models.Model): object_presence = models.ForeignKey(ObjectList, on_delete=models.CASCADE, verbose_name='Объект', default=None, null=True) counter_presence = models.ForeignKey(CounterParty, verbose_name='Контрагенты', default=None, null=True, on_delete=models.CASCADE) class PresenceDetailInfo(models.Model): presence_info = models.ForeignKey(PresenceListInfo, verbose_name='Объекты', default=None, null=True, on_delete=models.CASCADE, related_name='details_info') work_date = models.DateField(verbose_name='Дата', default=None) amount_of_workers = models.IntegerField(verbose_name='Количество работников', default=0) def parts_with_sections(self): return self.presence_sections_list.select_related('presence_sections') class PresenceSectionList(models.Model): presence_detail = models.ForeignKey(PresenceDetailInfo, on_delete=models.CASCADE, related_name='presence_sections_list') presence_sections = models.ForeignKey(CleanSections, blank=True, on_delete=models.CASCADE, null=True) views.py class ShowPresenceInfoList(ListView): model = PresenceDetailInfo template_name = 'common/presence_info.html' context_object_name = 'details_list' -
How do I set a one-to-many relationship in the Django database, so that the foreign key is the primary key?
enter image description here Here, for example, are such tables. When I connect them (it is necessary to connect them with such a connection), I get an error. This is what my code looks like from django.db import models class Pupil(models.Model): objects = models.Manager() last_name = models.CharField(max_length=15) first_name = models.CharField(max_length=15) id_control = models.IntegerField(unique=True, blank=False, null=False) class Control(models.Model): objects = models.Manager() id = models.ForeignKey('Control', on_delete=models.CASCADE, primary_key=True) answer_one = models.CharField(max_length=15) answer_two = models.CharField(max_length=15) answer_three = models.CharField(max_length=15) -
Not able to connect Django with rabbitmq using docker
I am trying to connect Django and rabbitmq using docker but I am getting this error "socket.gaierror: [Errno -2] Name or service not known" when I run docker-compose up. There is a connection failure between the Django container and rabbitmq container in producer.py even though I have given the name of rabbitmq container name in connection string. docker-compose.yml version: '3.8' services: rabbitmq: image: rabbitmq:3.8-management-alpine ports: - 15673:15672 environment: RABBITMQ_DEFAULT_VHOST: vhost RABBITMQ_DEFAULT_USER: guest RABBITMQ_DEFAULT_PASS: guest healthcheck: test: rabbitmq-diagnostics check_port_connectivity interval: 30s timeout: 30s retries: 10 restart: always backend: build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 volumes: - .:/app restart: always depends_on: rabbitmq: condition: service_healthy view.py from .producer import publish class SampleView(APIView): def get(self, request): print('HERE') publish('data send', {'message':'Here'}) return Response({'message': 'HERE'}) producer.py import pika import json import os connection = pika.BlockingConnection( pika.ConnectionParameters(host='amqp://guest:guest@rabbitmq:5672/vhost') ) channel = connection.channel() channel.queue_declare(queue='main') def publish(method, body): properties = pika.BasicProperties(method) # body = bytes(body) channel.basic_publish(exchange='', routing_key='main', body=body, properties=properties) channel.close() -
Django get value from foreign key in views.py
I am a beginner in dango. I am trying to retrieve the price from the service and make a sum of all the prices. I am asking for help. logopedija/models.py class Pricelist(models.Model): name=models.CharField('Name of service', max_length=60) price=models.DecimalField(default=0, decimal_places=2, max_digits=20) def __str__(self): return "%s %s" % (self.name, self.price) class Service(models.Model): id = models.AutoField(primary_key=True) user=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, limit_choices_to={'active': True},) service=models.ForeignKey(Pricelist, on_delete=models.CASCADE, null=True, blank=True) day=models.DateField(default=date) time_service = models.CharField(max_length=10, choices=TIME-CHOICE, default="16:00") is_paid = models.BooleanField(default=False) def __str__(self): return f"{self.user.name} | dan:{self.day} | time:{self.time_service} | service:{self.service.price}" logopedija/views.py def show_service(request, service_id): service = Service.objects.get(pk=service_id) return render(request, 'users/show_service.html', {'service':service}) logopedija/show_service.html {% extends 'pacijenti/base.html' %} {% block content %} \<div class="card"\> \<div class="card-header"\> Detalji termina \</div\> \<div class="card-body"\> \<h5 class="card-title"\>{{ service }}\</h5\> \<p class="card-text"\> {{ service.id }}\<br/\> {{ service.user }}\<br/\> {{ service.service }`your text`}\<br/\> {{ service.day }}\<br/\> {{ service.time_service }}\<br/\> \</p\> \</div\> \</div\> {% endblock %} -
How to override font familly in Django 4.2?
Django 4.2 release notes: The admin’s font stack now prefers system UI fonts and no longer requires downloading fonts. Additionally, CSS variables are available to more easily override the default font families. I noticed that the font familly of the admin panel changed from : font-family: Roboto, "Lucida Grande", "DejaVu Sans", "Bitstream Vera Sans", Verdana, Arial, sans-serif; To font-family: var(--font-family-primary); --font-family-primary: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; How can I customize font-family-primary and make it use Roboto as before ? -
Django raw SQL queries
Here is my code for raw SQL query: timeSeries=TimeSeries.objects.raw('select avg(value) from TimeSeries where station=%s group by date',[request.POST['station-number']]) it throws error: relation "timeseries" does not exist. what can be the problem can someone kindly help? -
Webpack does not allow Django to set sessionid Cookies
I setup React application using Webpack and Django for Backend, i wanted to make authorization with sessions, but whenever i try to make a request i get 200 OK status Response and in the Response Headers i see session-id in Set-Cookie header, but not in the COOKIES, everything is fine when i setup app with create-react-app, and i think that Webpack just does not allow Django to set Cookies or something, so are there anyone that can help me? Here is the React code: await fetch('http://127.0.0.1:8000/api/v1/account/login', { method: 'POST', body: JSON.stringify({ username: formData?.username, password: formData?.password }), headers: { 'Content-Type': 'application/json', 'X-CSRFToken': Cookies.get('csrftoken') as string, 'withCredentials': 'include' }, }) i tried to make requests with RTKQuery, but it didn't work, it just seems like Webpack does not allow to set Cookies :/ -
Axios can't sent value from template to viwes.py Django
I try to use axios with method POST in Django ,but This case server can't collect submodel value . it output to template always "Test". Where am I wrong ? IN TEMPLATE IN VIEWS.PY IN BROWSER Solution to solve it -
Set cronjobs to run everyday at 6am in django python
I am using Django-Crontabs to execute my function every day in the morning at 6 am. Here is my code for Django-Crontabs. Firstly I install Django-Crontabs with this command. pip3 install Django-crontab Settings.py INSTALLED_APPS = [ 'django_crontab', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] CRONJOBS = [ ('* 6 * * *', 'myapp.cron.cronfunction') ] Here I have set the code to run every day at 6 AM. As per the following template. But it is not working. # Use the hash sign to prefix a comment # +---------------- minute (0 - 59) # | +------------- hour (0 - 23) # | | +---------- day of month (1 - 31) # | | | +------- month (1 - 12) # | | | | +---- day of week (0 - 7) (Sunday=0 or 7) # | | | | | # * * * * * command to be executed cron.py def cronfunction(): logger.warning("========== Run Starts ====") logger.warning("========== Run Ends ======") If I am running this function every 2 or 3 minutes then it works fine. ('*/2 * * * *', 'myapp.cron.cronfunction') How do I set my cronjob to run every day, Can anyone help? please. -
Generate media url from file path in Django
Let's say I have a function that writes a file to MEDIA_ROOT: def write_file(): with open(settings.MEDIA_ROOT / 'myfile.txt') as file: file.write('foobar') Now I want the absolute URL for this file as it is served from MEDIA_URL. Does Django have any utility function to do this for me? Or do I need to build it myself? Note this file is NOT associated with a model's FileField. -
Django ModeuleNotFoundError:
I have a Django project all set up, several apps that work fine but I have a folder with a few python files in it and on top of each file I have: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'My Project.settings') import django django.setup() If I take the file out of the folder then it works fine but if I try to run in while it is in the folder I get ModuleNotFoundError: No module named 'MyProject' The setup looks like this: MyProject MyProject settings.py More Apps Folder .py file that wont work in folder Is there something I need to edit in my import above to get the files to work while in the folder? Thank you for your help. -
How to create seperate login system for user and service provider in django
I have this fully functional user auth system User model: class User(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name'] User login view.I'm using JWT tokens stored in cookies. @api_view(['POST']) def LoginView(request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.data = { 'jwt': token } return response In my React front-end i use react-auth-kit to check if the user if logged-in, and a userProfile component which is private as shown bellow. App.jsx const PrivateRoute = ({ Component }) => { const isAuthenticated = useIsAuthenticated(); const auth = isAuthenticated(); return auth ? <Component /> : <Navigate to="/login" />; }; <Router> <NavBar /> <Routes> <Route path="/" element={<Home />} /> <Route path="/login" element={<Login />} /> <Route path="/signup" element={<Signup />} /> <Route path="/profile" element={<PrivateRoute Component={UserProfile} />} /> <Footer /> </Router> The Login.jsx has a simple axios request axios .post( "/api/login", { email: values.email, password: values.password, }, { withCredentials: true, headers: … -
Django - HTMX: Render forms errors on modal and keep user on same page?
may you help me to understand how to use HTMX to render Form's Error messages when form is invalid? Docs says to use an attribute like : hx-post="{% url 'accounts:login' %}" but since I'm already using method=post should I still use it or delete it?I'd like users to stay on current page, however, right now when form is invalid users are redirected here: http://127.0.0.1:8000/accounts/login/ I didn't find a javascript function that opens the modal, so I think it is openened by some javascript implemented by bootstrap itself. this is my form: <form class="row my-4 align-items-center" method="post" action="{% url 'accounts:login' %}"> {% csrf_token %} {{ login_form.as_p }} {% if login_form.errors %} <ul> {% for field_errors in login_form.errors.values %} {% for error in field_errors %} <li>{{ error }}</li> {% endfor %} {% endfor %} </ul> {% endif %} <button type="submit" class="btn btn-primary">Ingresar</button> </form> ``` views: def login_view(request): if request.method == 'POST': login_form = LoginForm(request, data=request.POST) print("### Request is post") if login_form.is_valid(): print("### Request is VALID") username = login_form.cleaned_data.get('username') password = login_form.cleaned_data.get('password') print("User name", username, "type: ", type(username)) print("Pass", password, "type: ", type(password)) user = authenticate(request, username=username, password=password) if user is not None: login(request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect("/") else: print(login_form.errors.as_data()) return JsonResponse({'success': False, … -
I can`t get access token using python sdk
I want to get access token with python. this is my code: def get_access_token(request): with open("path/to/private.key", "r") as f: RAS_PRIVATE_KEY = f.read() RAS_PRIVATE_KEY = RAS_PRIVATE_KEY.encode("ascii").decode("utf-8") api_client = ApiClient() host_name = "account-d.docusign.com" api_client.set_oauth_host_name(oauth_host_name=host_name) api_client.host = "https://account-d.docusign.com" token = api_client.request_jwt_user_token( client_id=settings.CLIENT_ID, user_id=settings.IMPERSONATED_USER_ID, oauth_host_name=host_name, private_key_bytes=RAS_PRIVATE_KEY, expires_in=3600, scopes=['signature', 'impersonation'] ) access_token = token.access_token return access_token But this error will occurre: docusign_esign.client.api_exception.ApiException: (444) Reason: Trace-Token: 2f2837d6-883f-4511-821f-09a8fee568ab Timestamp: Tue, 11 Apr 2023 23:34:09 GMT HTTP response headers: HTTPHeaderDict({'Content-Type': 'text/html', 'X-DocuSign-TraceToken': '2f2837d6-883f-4511-821f-09a8fee568ab', 'X-DocuSign-Node': 'DA2DFE4', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload', 'Referrer-Policy': 'no-referrer,strict-origin-when-cross-origin', 'X-Content-Type-Options': 'nosniff', 'Date': 'Tue, 11 Apr 2023 23:34:09 GMT', 'Content-Length': '54', 'Connection': 'close', 'Vary': 'Accept-Encoding'}) HTTP response body: b'The custom error module does not recognize this error.' Then I set oauth_host_name="https://demo.docusign.net/restapi" and another error will occurre: raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='https', port=443): Max retries exceeded with url: //demo.docusign.net/restapi/oauth/token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7ff19117d450>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) I don't know where the problem is.How I can solve it? -
"sudo: apt: command not found" when trying to deploy a django app with aws
I am trying to deploy my first Django app with AWS. I did everything until I reached the step of using sudo in the ec2 environmental setup. when I try to run sudo apt update I get sudo: apt: command not found. What can I do to solve this? -
Django custom AuthenticationForm fields
I want to use email and password fields only to authenticate, but it seems Django forces me to get username field. I tried to use username to login by adding username field to my User model, but it also ended with valid=Unknown I've read Django docs custom AuthenticationForm guide, and it ended without making custom AuthenticationForm ... view from django.shortcuts import render, redirect from django.contrib.auth import login, logout, authenticate from .forms import UserLoginForm def login_view(request): if request.method == "POST": print(f"{request.POST=}") form = UserLoginForm(request.POST) print(f"{form=}") if form.is_valid(): print(" form valid") user = login(request, form) print(f" user login {user}") return redirect('home') else: form = UserLoginForm() return render(request, 'login.html', {'form': form}) UserLoginForm class UserLoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(AuthenticationForm, self).__init__(*args, **kwargs) class Meta: model = User fields = ('email', 'password', ) _base_attrs = { 'class': 'form-control', 'placeholder': '', } email = forms.EmailField( widget=forms.TextInput( attrs=_base_attrs ) ) password = forms.CharField( widget=forms.PasswordInput( attrs=_base_attrs ) ) User class User(AbstractBaseUser): email = models.EmailField( verbose_name="email", max_length=255, unique=True, ) is_leadership = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) register_date = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ('password', ) email_backend class EmailBackend(BaseBackend): def authenticate(self, request, email=None, password=None): UserModel = get_user_model() user = UserModel.objects.get(email=email) if user.check_password(password): return user … -
how to pass context to filter in django
I want to access context in filter: NOT working example (showing what I want to get) {% for phone in person.communicator_set.all|phones %} {{ phone.number }} {% endfor %} templatetags/filters.py @register.filter(takes_context=True) def context_filter(context,queryset): return queryset.filter(validity_range__contains=context['context_date']) But this doesn't work... -
add field with select number of fields in forms
I want to build a reservation site and I'm zero in javascript! in the form I want to when user select number of rooms for counting of his select appear select fields (adult count , child count) and when select child number (child > 0 >0 ) a select filed appear and catch the age of child and do this for all the rooms too if child > 0 I'm using django plz help me for do this ! tnx! -
How do I send anchor tag links in email template in django
I am fairly new to Django and I use Django 4.2. I am trying to send email as rendered templates from views.py. The email sends but in all plain text. The link does not show in the email as a link, it shows as a plain html text. views.py send email function def sendActivationMail(user, request): current_site = get_current_site(request) email_subject = 'Verify your account' # context = { # 'click_action': 'showDomainLink', # } email_body = render_to_string( 'mail_temp/confirm_temp.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': generator_token.make_token(user), }, # context ) email = EmailMessage( subject=email_subject, body=email_body, from_email=settings.EMAIL_HOST_USER, to=[user.email] ) email.content_subtype = 'html' email.send() def activate_token(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = Users.objects.get(pk=uid) except (ValueError, Users.DoesNotExist): user = None if user is not None and generator_token.check_token(user, token): user.is_email_verified = True user.save() messages.success(request, 'Successfully verified email') return redirect(reverse('login')) else: messages.error(request, 'Verification link was invalid') return redirect('index') email body template {% autoescape off %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> h1{ color: chocolate; } p{ font-size: 22px; } </style> </head> <body> <h1>Hey there, you are almost there!</h1> <p>Please click link to verify your account</p> <a class="underline" href="http://{{ domain }} {% url 'activate' uidb64=uid token=token%}">token</a> </body> </html> {% endautoescape %} I have …